text:
Git
===

Provides nice git aliases and functions.

Also provides functions necessary for many prompts.

Many thanks to [Sorin Ionescu](https://github.com/sorin-ionescu) for the excellent aliases.

Aliases
-------

### Git

  - `g` is short for `git`.

### Branch

  - `gb` lists, creates, renames, and deletes branches.
  - `gbc` creates a new branch.
  - `gbl` lists branches and their commits.
  - `gbL` lists local and remote branches and their commits.
  - `gbs` lists branches and their commits with ancestry graphs.
  - `gbS` lists local and remote branches and their commits with ancestry
    graphs.
  - `gbx` deletes a branch.
  - `gbX` deletes a branch irrespective of its merged status.
  - `gbm` renames a branch.
  - `gbM` renames a branch even if the new branch name already exists.

### Commit

  - `gc` records changes to the repository.
  - `gca` stages all modified and deleted files.
  - `gcm` records changes to the repository with the given message.
  - `gco` checks out a branch or paths to work tree.
  - `gcO` checks out hunks from the index or the tree interactively.
  - `gcf` amends the tip of the current branch using the same log message as
    *HEAD*.
  - `gcF` amends the tip of the current branch.
  - `gcp` applies changes introduced by existing commits.
  - `gcP` applies changes introduced by existing commits without committing.
  - `gcr` reverts existing commits by reverting patches and recording new
     commits.
  - `gcR` removes the *HEAD* commit.
  - `gcs` displays various types of objects.
  - `gcl` lists lost commits.

### Conflict

  - `gCl` lists unmerged files.
  - `gCa` adds unmerged file contents to the index.
  - `gCe` executes merge-tool on all unmerged file.
  - `gCo` checks out our changes for unmerged paths.
  - `gCO` checks out our changes for all unmerged paths.
  - `gCt` checks out their changes for unmerged paths.
  - `gCT` checks out their changes for all unmerged paths.

### Data

  - `gd` displays information about files in the index and the work tree.
  - `gdc` lists cached files.
  - `gdx` lists deleted files.
  - `gdm` lists modified files.
  - `gdu` lists untracked files.
  - `gdk` lists killed files.
  - `gdi` lists ignored files.

### Fetch

  - `gf` downloads objects and references from another repository.
  - `gfc` clones a repository into a new directory.
  - `gfm` fetches from and merges with another repository or local branch.
  - `gfr` fetches from and rebases on another repository or local branch.

### Grep

  - `gg` displays lines matching a pattern.
  - `ggi` displays lines matching a pattern ignoring case.
  - `ggl` lists files matching a pattern.
  - `ggL` lists files that are not matching a pattern.
  - `ggv` displays lines not matching a pattern.
  - `ggw` displays lines matching a pattern at word boundary.

### Index

  - `gia` adds file contents to the index.
  - `giA` adds file contents to the index interactively.
  - `giu` adds file contents to the index (updates only known files).
  - `gid` displays changes between the index and a named commit (diff).
  - `giD` displays changes between the index and a named commit (word diff).
  - `gir` resets the current HEAD to the specified state.
  - `giR` resets the current index interactively.
  - `gix` removes files/directories from the index (recursively).
  - `giX` removes files/directories from the index (recursively and forced).

### Log

  - `gl` displays the log.
  - `gls` displays the stats log.
  - `gld` displays the diff log.
  - `glo` displays the one line log.
  - `glg` displays the graph log.
  - `glG` displays the graph log with authors and dates.
  - `glb` displays the brief commit log.
  - `glc` displays the commit count for each contributor in descending order.

### Merge

  - `gm` joins two or more development histories together.
  - `gmC` joins two or more development histories together but does not commit.
  - `gmF` joins two or more development histories together but does not commit
     generating a merge commit even if the merge resolved as a fast-forward.
  - `gma` aborts the conflict resolution, and reconstructs the pre-merge state.
  - `gmt` runs the merge conflict resolution tools to resolve conflicts.

### Push

  - `gp` updates remote refs along with associated objects.
  - `gpf` forcefully updates remote refs along with associated objects.
  - `gpa` updates remote branches along with associated objects.
  - `gpA` updates remote branches and tags along with associated objects.
  - `gpt` updates remote tags along with associated objects.
  - `gpc` updates remote refs along with associated objects and adds *origin*
     as an upstream reference for the current branch.
  - `gpp` pulls and pushes from origin to origin.

### Rebase

  - `gr` forward-ports local commits to the updated upstream head.
  - `gra` aborts the rebase.
  - `grc` continues the rebase after merge conflicts are resolved.
  - `gri` makes a list of commits to be rebased and opens the editor.
  - `grs` skips the current patch.

### Remote

  - `gR` manages tracked repositories.
  - `gRl` lists remote names and their URLs.
  - `gRa` adds a new remote.
  - `gRx` removes a remote.
  - `gRm` renames a remote.
  - `gRu` fetches remotes updates.
  - `gRp` prunes all stale remote tracking branches.
  - `gRs` displays information about a given remote.
  - `gRb` opens a remote on GitHub in the default browser.

### Stash

  - `gs` stashes the changes of the dirty working directory.
  - `gsa` applies the changes recorded in a stash to the working directory.
  - `gsx` drops a stashed state.
  - `gsX` drops all the stashed states.
  - `gsl` lists stashed states.
  - `gsL` lists dropped stashed states.
  - `gsd` displays changes between the stash and its original parent.
  - `gsp` removes and applies a single stashed state from the stash list.
  - `gsr` recovers a given stashed state.
  - `gss` stashes the changes of the dirty working directory, including untracked.
  - `gsS` stashes the changes of the dirty working directory interactively.
  - `gsw` stashes the changes of the dirty working directory retaining the index.
  - `gsu` unapplies (reverts) applied changes.

### Submodule

  - `gS` initializes, updates, or inspects submodules.
  - `gSa` adds given a repository as a submodule.
  - `gSf` evaluates a shell command in each of checked out submodules.
  - `gSi` initializes submodules.
  - `gSI` initializes and clones submodules recursively.
  - `gSl` lists the commits of all submodules.
  - `gSm` moves a submodule.
  - `gSs` synchronizes submodules' remote URL to the value specified in
    .gitmodules.
  - `gSu` fetches and merges the latest changes for all submodule.
  - `gSx` removes a submodule.

### Working directory

  - `gws` displays working-tree status in the short format.
  - `gwS` displays working-tree status.
  - `gwd` displays changes between the working tree and the index (diff).
  - `gwD` displays changes between the working tree and the index (word diff).
  - `gwr` resets the current HEAD to the specified state, does not touch the
     index nor the working tree.
  - `gwR` resets the current HEAD, index and working tree to the specified state.
  - `gwc` removes untracked files from the working tree (dry-run).
  - `gwC` removes untracked files from the working tree.
  - `gwx` removes files from the working tree and from the index recursively.
  - `gwX` removes files from the working tree and from the index recursively and
    forcefully.

### Shadows

The following aliases may shadow system commands:

  - `gpt` shadows the GUID partition table maintenance utility.
  - `gs` shadows Ghostscript.

If you frequently use the above commands, you may wish to remove said aliases
from this module or to disable them at the bottom of the zshrc with `unalias`.

You can temporarily bypass an alias by prefixing it with a backward slash:
`\gpt`.

Functions
---------

  - `git-branch-current` displays the current branch.
  - `git-commit-lost` lists lost commits.
  - `git-dir` displays the path to the Git directory.
  - `git-hub-browse` opens the GitHub repository in the default browser.
  - `git-hub-shorten-url` shortens GitHub URLs.
  - `git-ignore-add` adds any arguments to the .gitignore in the project root.
  - `git-root` displays the path to the working tree root.
  - `git-stash-clear-interactive` asks for confirmation before clearing the stash.
  - `git-stash-dropped` lists dropped stashed states.
  - `git-stash-recover` recovers given dropped stashed states.
  - `git-submodule-move` moves a submodule.
  - `git-submodule-remove` removes a submodule.


text:
package session

import (
	codec "github.com/gorilla/securecookie"
	"github.com/webx-top/echo"
	ss "github.com/webx-top/echo/middleware/session/engine"
	cookieStore "github.com/webx-top/echo/middleware/session/engine/cookie"
)

func NewSession(ctx echo.Context) echo.Sessioner {
	return ss.NewSession(ctx)
}

type Store interface {
	ss.Store
}

func NewMySession(store ss.Store, name string, ctx echo.Context) echo.Sessioner {
	return ss.NewMySession(store, name, ctx)
}

func StoreEngine(options *echo.SessionOptions) (store Store) {
	store = ss.StoreEngine(options)
	if store == nil {
		cs := cookieStore.New(&cookieStore.CookieOptions{
			KeyPairs: [][]byte{
				[]byte(codec.GenerateRandomKey(32)),
				[]byte(codec.GenerateRandomKey(32)),
			},
			SessionOptions: options,
		})
		cookieStore.Reg(cs)
		store = cs
	}
	return
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<comment version="3.0">
  <caption/>
  <note>Blender:File:/home/kj/Nextcloud/Graphics/3D/P1X Market/dunes-shader.blend</note>
  <place/>
  <categories/>
</comment>


text:
<?php

require_once 'Swift/Tests/SwiftSmokeTestCase.php';

class Swift_Smoke_HtmlWithAttachmentSmokeTest
  extends Swift_Tests_SwiftSmokeTestCase
{

  public function setUp()
  {
    $this->_attFile = dirname(__FILE__) . '/../../../_samples/files/textfile.zip';
  }

  public function testAttachmentSending()
  {
    $mailer = $this->_getMailer();
    $message = Swift_Message::newInstance('[Swift Mailer] HtmlWithAttachmentSmokeTest')
      ->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Swift Mailer'))
      ->setTo(SWIFT_SMOKE_EMAIL_ADDRESS)
      ->attach(Swift_Attachment::fromPath($this->_attFile))
      ->setBody('
This HTML-formatted message should contain an attached ZIP file (named "textfile.zip").' . PHP_EOL .
        'When unzipped, the archive should produce a text file which reads:
' . PHP_EOL .
        '
<q>This is part of a Swift Mailer v4 smoke test.</q>
', 'text/html'
      )
      ;
    $this->assertEqual(1, $mailer->send($message),
      '%s: The smoke test should send a single message'
      );
    $this->_visualCheck('http://swiftmailer.org/smoke/4.0.0/attachment.jpg');
  }

}


text:
require 'abstract_unit'
require 'fixtures/tag'
require 'fixtures/tagging'
require 'fixtures/post'
require 'fixtures/item'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
require 'fixtures/vertex'
require 'fixtures/edge'
require 'fixtures/book'
require 'fixtures/citation'

class AssociationsJoinModelTest < Test::Unit::TestCase
  self.use_transactional_fixtures = false
  fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books

  def test_has_many
    assert authors(:david).categories.include?(categories(:general))
  end

  def test_has_many_inherited
    assert authors(:mary).categories.include?(categories(:sti_test))
  end

  def test_inherited_has_many
    assert categories(:sti_test).authors.include?(authors(:mary))
  end

  def test_has_many_uniq_through_join_model
    assert_equal 2, authors(:mary).categorized_posts.size
    assert_equal 1, authors(:mary).unique_categorized_posts.size
  end

  def test_has_many_uniq_through_count
    author = authors(:mary)
    assert !authors(:mary).unique_categorized_posts.loaded?
    assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
    assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
    assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
    assert !authors(:mary).unique_categorized_posts.loaded?
  end

  def test_polymorphic_has_many
    assert posts(:welcome).taggings.include?(taggings(:welcome_general))
  end

  def test_polymorphic_has_one
    assert_equal taggings(:welcome_general), posts(:welcome).tagging
  end

  def test_polymorphic_belongs_to
    assert_equal posts(:welcome), posts(:welcome).taggings.first.taggable
  end

  def test_polymorphic_has_many_going_through_join_model
    assert_equal tags(:general), tag = posts(:welcome).tags.first
    assert_no_queries do
      tag.tagging
    end
  end

  def test_count_polymorphic_has_many
    assert_equal 1, posts(:welcome).taggings.count
    assert_equal 1, posts(:welcome).tags.count
  end

  def test_polymorphic_has_many_going_through_join_model_with_find
    assert_equal tags(:general), tag = posts(:welcome).tags.find(:first)
    assert_no_queries do
      tag.tagging
    end
  end

  def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection
    assert_equal tags(:general), tag = posts(:welcome).funky_tags.first
    assert_no_queries do
      tag.tagging
    end
  end

  def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection_with_find
    assert_equal tags(:general), tag = posts(:welcome).funky_tags.find(:first)
    assert_no_queries do
      tag.tagging
    end
  end

  def test_polymorphic_has_many_going_through_join_model_with_disabled_include
    assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
    assert_queries 1 do
      tag.tagging
    end
  end

  def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
    assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
    tag.author_id
  end

  def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
    assert_equal tags(:misc), taggings(:welcome_general).super_tag
    assert_equal tags(:misc), posts(:welcome).super_tags.first
  end

  def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class
    post = SubStiPost.create :title => 'SubStiPost', :body => 'SubStiPost body'
    assert_instance_of SubStiPost, post

    tagging = tags(:misc).taggings.create(:taggable => post)
    assert_equal "SubStiPost", tagging.taggable_type
  end

  def test_polymorphic_has_many_going_through_join_model_with_inheritance
    assert_equal tags(:general), posts(:thinking).tags.first
  end

  def test_polymorphic_has_many_going_through_join_model_with_inheritance_with_custom_class_name
    assert_equal tags(:general), posts(:thinking).funky_tags.first
  end

  def test_polymorphic_has_many_create_model_with_inheritance
    post = posts(:thinking)
    assert_instance_of SpecialPost, post

    tagging = tags(:misc).taggings.create(:taggable => post)
    assert_equal "Post", tagging.taggable_type
  end

  def test_polymorphic_has_one_create_model_with_inheritance
    tagging = tags(:misc).create_tagging(:taggable => posts(:thinking))
    assert_equal "Post", tagging.taggable_type
  end

  def test_set_polymorphic_has_many
    tagging = tags(:misc).taggings.create
    posts(:thinking).taggings << tagging
    assert_equal "Post", tagging.taggable_type
  end

  def test_set_polymorphic_has_one
    tagging = tags(:misc).taggings.create
    posts(:thinking).tagging = tagging
    assert_equal "Post", tagging.taggable_type
  end

  def test_create_polymorphic_has_many_with_scope
    old_count = posts(:welcome).taggings.count
    tagging = posts(:welcome).taggings.create(:tag => tags(:misc))
    assert_equal "Post", tagging.taggable_type
    assert_equal old_count+1, posts(:welcome).taggings.count
  end

  def test_create_bang_polymorphic_with_has_many_scope
    old_count = posts(:welcome).taggings.count
    tagging = posts(:welcome).taggings.create!(:tag => tags(:misc))
    assert_equal "Post", tagging.taggable_type
    assert_equal old_count+1, posts(:welcome).taggings.count
  end

  def test_create_polymorphic_has_one_with_scope
    old_count = Tagging.count
    tagging = posts(:welcome).tagging.create(:tag => tags(:misc))
    assert_equal "Post", tagging.taggable_type
    assert_equal old_count+1, Tagging.count
  end

  def test_delete_polymorphic_has_many_with_delete_all
    assert_equal 1, posts(:welcome).taggings.count
    posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDeleteAll'
    post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)

    old_count = Tagging.count
    post.destroy
    assert_equal old_count-1, Tagging.count
    assert_equal 0, posts(:welcome).taggings.count
  end

  def test_delete_polymorphic_has_many_with_destroy
    assert_equal 1, posts(:welcome).taggings.count
    posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDestroy'
    post = find_post_with_dependency(1, :has_many, :taggings, :destroy)

    old_count = Tagging.count
    post.destroy
    assert_equal old_count-1, Tagging.count
    assert_equal 0, posts(:welcome).taggings.count
  end

  def test_delete_polymorphic_has_many_with_nullify
    assert_equal 1, posts(:welcome).taggings.count
    posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyNullify'
    post = find_post_with_dependency(1, :has_many, :taggings, :nullify)

    old_count = Tagging.count
    post.destroy
    assert_equal old_count, Tagging.count
    assert_equal 0, posts(:welcome).taggings.count
  end

  def test_delete_polymorphic_has_one_with_destroy
    assert posts(:welcome).tagging
    posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneDestroy'
    post = find_post_with_dependency(1, :has_one, :tagging, :destroy)

    old_count = Tagging.count
    post.destroy
    assert_equal old_count-1, Tagging.count
    assert_nil posts(:welcome).tagging(true)
  end

  def test_delete_polymorphic_has_one_with_nullify
    assert posts(:welcome).tagging
    posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneNullify'
    post = find_post_with_dependency(1, :has_one, :tagging, :nullify)

    old_count = Tagging.count
    post.destroy
    assert_equal old_count, Tagging.count
    assert_nil posts(:welcome).tagging(true)
  end

  def test_has_many_with_piggyback
    assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
  end

  def test_include_has_many_through
    posts              = Post.find(:all, :order => 'posts.id')
    posts_with_authors = Post.find(:all, :include => :authors, :order => 'posts.id')
    assert_equal posts.length, posts_with_authors.length
    posts.length.times do |i|
      assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
    end
  end

  def test_include_polymorphic_has_one
    post    = Post.find_by_id(posts(:welcome).id, :include => :tagging)
    tagging = taggings(:welcome_general)
    assert_no_queries do
      assert_equal tagging, post.tagging
    end
  end

  def test_include_polymorphic_has_one_defined_in_abstract_parent
    item    = Item.find_by_id(items(:dvd).id, :include => :tagging)
    tagging = taggings(:godfather)
    assert_no_queries do
      assert_equal tagging, item.tagging
    end
  end

  def test_include_polymorphic_has_many_through
    posts           = Post.find(:all, :order => 'posts.id')
    posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id')
    assert_equal posts.length, posts_with_tags.length
    posts.length.times do |i|
      assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
    end
  end

  def test_include_polymorphic_has_many
    posts               = Post.find(:all, :order => 'posts.id')
    posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id')
    assert_equal posts.length, posts_with_taggings.length
    posts.length.times do |i|
      assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
    end
  end

  def test_has_many_find_all
    assert_equal [categories(:general)], authors(:david).categories.find(:all)
  end

  def test_has_many_find_first
    assert_equal categories(:general), authors(:david).categories.find(:first)
  end

  def test_has_many_with_hash_conditions
    assert_equal categories(:general), authors(:david).categories_like_general.find(:first)
  end

  def test_has_many_find_conditions
    assert_equal categories(:general), authors(:david).categories.find(:first, :conditions => "categories.name = 'General'")
    assert_equal nil, authors(:david).categories.find(:first, :conditions => "categories.name = 'Technology'")
  end

  def test_has_many_class_methods_called_by_method_missing
    assert_equal categories(:general), authors(:david).categories.find_all_by_name('General').first
    assert_equal nil, authors(:david).categories.find_by_name('Technology')
  end

  def test_has_many_going_through_join_model_with_custom_foreign_key
    assert_equal [], posts(:thinking).authors
    assert_equal [authors(:mary)], posts(:authorless).authors
  end

  def test_belongs_to_polymorphic_with_counter_cache
    assert_equal 0, posts(:welcome)[:taggings_count]
    tagging = posts(:welcome).taggings.create(:tag => tags(:general))
    assert_equal 1, posts(:welcome, :reload)[:taggings_count]
    tagging.destroy
    assert posts(:welcome, :reload)[:taggings_count].zero?
  end

  def test_unavailable_through_reflection
    assert_raise(ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings }
  end

  def test_has_many_through_join_model_with_conditions
    assert_equal [], posts(:welcome).invalid_taggings
    assert_equal [], posts(:welcome).invalid_tags
  end

  def test_has_many_polymorphic
    assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do
      assert_equal posts(:welcome, :thinking), tags(:general).taggables
    end
    assert_raise ActiveRecord::EagerLoadPolymorphicError do
      assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable)
    end
  end

  def test_has_many_polymorphic_with_source_type
    assert_equal posts(:welcome, :thinking), tags(:general).tagged_posts
  end

  def test_eager_has_many_polymorphic_with_source_type
    tag_with_include = Tag.find(tags(:general).id, :include => :tagged_posts)
    desired = posts(:welcome, :thinking)
    assert_no_queries do
      assert_equal desired, tag_with_include.tagged_posts
    end
  end

  def test_has_many_through_has_many_find_all
    assert_equal comments(:greetings), authors(:david).comments.find(:all, :order => 'comments.id').first
  end

  def test_has_many_through_has_many_find_all_with_custom_class
    assert_equal comments(:greetings), authors(:david).funky_comments.find(:all, :order => 'comments.id').first
  end

  def test_has_many_through_has_many_find_first
    assert_equal comments(:greetings), authors(:david).comments.find(:first, :order => 'comments.id')
  end

  def test_has_many_through_has_many_find_conditions
    options = { :conditions => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
    assert_equal comments(:does_it_hurt), authors(:david).comments.find(:first, options)
  end

  def test_has_many_through_has_many_find_by_id
    assert_equal comments(:more_greetings), authors(:david).comments.find(2)
  end

  def test_has_many_through_polymorphic_has_one
    assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tagging }
  end

  def test_has_many_through_polymorphic_has_many
    assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.uniq.sort_by { |t| t.id }
  end

  def test_include_has_many_through_polymorphic_has_many
    author            = Author.find_by_id(authors(:david).id, :include => :taggings)
    expected_taggings = taggings(:welcome_general, :thinking_general)
    assert_no_queries do
      assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
    end
  end

  def test_has_many_through_has_many_through
    assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tags }
  end

  def test_has_many_through_habtm
    assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).post_categories }
  end

  def test_eager_load_has_many_through_has_many
    author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id'
    SpecialComment.new; VerySpecialComment.new
    assert_no_queries do
      assert_equal [1,2,3,5,6,7,8,9,10], author.comments.collect(&:id)
    end
  end

  def test_eager_load_has_many_through_has_many_with_conditions
    post = Post.find(:first, :include => :invalid_tags)
    assert_no_queries do
      post.invalid_tags
    end
  end

  def test_eager_belongs_to_and_has_one_not_singularized
    assert_nothing_raised do
      Author.find(:first, :include => :author_address)
      AuthorAddress.find(:first, :include => :author)
    end
  end

  def test_self_referential_has_many_through
    assert_equal [authors(:mary)], authors(:david).favorite_authors
    assert_equal [],               authors(:mary).favorite_authors
  end

  def test_add_to_self_referential_has_many_through
    new_author = Author.create(:name => "Bob")
    authors(:david).author_favorites.create :favorite_author => new_author
    assert_equal new_author, authors(:david).reload.favorite_authors.first
  end

  def test_has_many_through_uses_conditions_specified_on_the_has_many_association
    author = Author.find(:first)
    assert !author.comments.blank?
    assert author.nonexistant_comments.blank?
  end

  def test_has_many_through_uses_correct_attributes
    assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"]
  end

  def test_raise_error_when_adding_new_record_to_has_many_through
    assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags << tags(:general).clone }
    assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).clone.tags << tags(:general) }
    assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.build }
    assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.new }
  end

  def test_create_associate_when_adding_to_has_many_through
    count = posts(:thinking).tags.count
    push = Tag.create!(:name => 'pushme')
    post_thinking = posts(:thinking)
    assert_nothing_raised { post_thinking.tags << push }
    assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
                message = "Expected a Tag in tags collection, got #{wrong.class}.")
    assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
                message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
    assert_equal(count + 1, post_thinking.tags.size)
    assert_equal(count + 1, post_thinking.tags(true).size)

    assert_kind_of Tag, post_thinking.tags.create!(:name => 'foo')
    assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
                message = "Expected a Tag in tags collection, got #{wrong.class}.")
    assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
                message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
    assert_equal(count + 2, post_thinking.tags.size)
    assert_equal(count + 2, post_thinking.tags(true).size)

    assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => 'abc'), Tag.create!(:name => 'def')) }
    assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
                message = "Expected a Tag in tags collection, got #{wrong.class}.")
    assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
                message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
    assert_equal(count + 4, post_thinking.tags.size)
    assert_equal(count + 4, post_thinking.tags(true).size)

    # Raises if the wrong reflection name is used to set the Edge belongs_to
    assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
  end

  def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
    author = authors(:david)
    assert_equal 9, author.comments.size
    assert !author.comments.loaded?
  end

  uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do
    def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
      author = authors(:david)
      author.stubs(:read_attribute).with('comments_count').returns(100)
      assert_equal 100, author.comments.size
      assert !author.comments.loaded?
    end
  end

  def test_adding_junk_to_has_many_through_should_raise_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
  end

  def test_adding_to_has_many_through_should_return_self
    tags = posts(:thinking).tags
    assert_equal tags, posts(:thinking).tags.push(tags(:general))
  end

  def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id
    count = books(:awdr).references.count
    references_before = books(:awdr).references
    book = Book.create!(:name => 'Getting Real')
    book_awdr = books(:awdr)
    book_awdr.references << book
    assert_equal(count + 1, book_awdr.references(true).size)

    assert_nothing_raised { book_awdr.references.delete(book) }
    assert_equal(count, book_awdr.references.size)
    assert_equal(count, book_awdr.references(true).size)
    assert_equal(references_before.sort, book_awdr.references.sort)
  end

  def test_delete_associate_when_deleting_from_has_many_through
    count = posts(:thinking).tags.count
    tags_before = posts(:thinking).tags
    tag = Tag.create!(:name => 'doomed')
    post_thinking = posts(:thinking)
    post_thinking.tags << tag
    assert_equal(count + 1, post_thinking.tags(true).size)

    assert_nothing_raised { post_thinking.tags.delete(tag) }
    assert_equal(count, post_thinking.tags.size)
    assert_equal(count, post_thinking.tags(true).size)
    assert_equal(tags_before.sort, post_thinking.tags.sort)
  end

  def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags
    count = posts(:thinking).tags.count
    tags_before = posts(:thinking).tags
    doomed = Tag.create!(:name => 'doomed')
    doomed2 = Tag.create!(:name => 'doomed2')
    quaked = Tag.create!(:name => 'quaked')
    post_thinking = posts(:thinking)
    post_thinking.tags << doomed << doomed2
    assert_equal(count + 2, post_thinking.tags(true).size)

    assert_nothing_raised { post_thinking.tags.delete(doomed, doomed2, quaked) }
    assert_equal(count, post_thinking.tags.size)
    assert_equal(count, post_thinking.tags(true).size)
    assert_equal(tags_before.sort, post_thinking.tags.sort)
  end

  def test_deleting_junk_from_has_many_through_should_raise_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete("Uhh what now?") }
  end

  def test_has_many_through_sum_uses_calculations
    assert_nothing_raised { authors(:david).comments.sum(:post_id) }
  end

  def test_calculations_on_has_many_through_should_disambiguate_fields
    assert_nothing_raised { authors(:david).categories.maximum(:id) }
  end

  def test_calculations_on_has_many_through_should_not_disambiguate_fields_unless_necessary
    assert_nothing_raised { authors(:david).categories.maximum("categories.id") }
  end

  def test_has_many_through_has_many_with_sti
    assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments
  end

  def test_uniq_has_many_through_should_retain_order
    comment_ids = authors(:david).comments.map(&:id)
    assert_equal comment_ids.sort, authors(:david).ordered_uniq_comments.map(&:id)
    assert_equal comment_ids.sort.reverse, authors(:david).ordered_uniq_comments_desc.map(&:id)
  end

  private
    # create dynamic Post models to allow different dependency options
    def find_post_with_dependency(post_id, association, association_name, dependency)
      class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
      Post.find(post_id).update_attribute :type, class_name
      klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
      klass.set_table_name 'posts'
      klass.send(association, association_name, :as => :taggable, :dependent => dependency)
      klass.find(post_id)
    end
end


text:
using System;

namespace NadekoBot.Services.Database.Models
{
    public class DiscordUser : DbEntity
    {
        public ulong UserId { get; set; }
        public string Username { get; set; }
        public string Discriminator { get; set; }
        public string AvatarId { get; set; }

        public ClubInfo Club { get; set; }
        public DateTime LastLevelUp { get; set; } = DateTime.UtcNow;
        public XpNotificationType NotifyOnLevelUp { get; set; }

        public override bool Equals(object obj)
        {
            return obj is DiscordUser du
                ? du.UserId == UserId
                : false;
        }

        public override int GetHashCode()
        {
            return UserId.GetHashCode();
        }

        public override string ToString() =>
            Username + "#" + Discriminator;
    }
}


text:
Contributor Acknowledgements
============================

Companies
---------
Linaro Limited

NVIDIA Corporation

Individuals
-----------


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jsDatePick Javascript example</title>

<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />

JsDatePick's Javascript Calendar usage example using the jQuery library

    Look at the comments on the HTML source to fully understand how this very simple example works.

    <input type="text" size="12" id="inputField" />


text:
/**
 * @since 2017-04-17 21:20
 * @author chenyiqin
 */

require('babel-polyfill')
require('babel-register')()
require('./dev/index')


text:
#rights .form .text-field { width:320px; }

#rights #updateAuthItem .parents,
#rights #updateAuthItem .children { margin-bottom:30px; }

#rights .type-column { width:100px; }
#rights .actions-column { width:80px; text-align:right; }

#rights .parent-table,
#rights .child-table,
#rights .user-assignment-table { width:420px; }

#rights .assignment-table td { vertical-align:top; }
#rights .assignment-table .role-column,
#rights .assignment-table .task-column,
#rights .assignment-table .operation-column { width:25%; }
#rights .permission-table .inherited-item { cursor:pointer; }

/**
* Flash message style.
*/

#rights .flashes {
	width:910px;
	height:40px;
	position:absolute;
	top:60px;
	left:20px;
}
#rights .flash {
	margin:0;
	padding:8px 12px;
	font-size:12px;
	font-style:italic;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
}
#rights .flash.success { color:#007700; background-color:#e0f8dd; }
#rights .flash.error { color:#7a0000; background-color:#fdd9d9; }

/**
* Installer style.
*/

#rights #installer { margin:30px 0; text-align:center; }

#rights .green-text { color:#00aa00; }
#rights .red-text { color:#ff0000; }

/**
* Generator style.
*/

#rights #generator table.items { margin:0; }
#rights #generator table.items th,

#rights #generator table.items td { cursor:pointer; }
#rights #generator table.items .module-row { background-color:#f0edec; }
#rights #generator table.items .controller-row { background-color:#FFFFFF; }
#rights #generator table.items .action-row .name-column { padding-left:20px; }
#rights #generator table.items .checkbox-column { width:20px; text-align:center; }
#rights #generator table.items .checkbox-column input { margin:2px 0; }
#rights #generator table.items .path-column { color:#808080; font-style:italic; }
#rights #generator table.items .exists * { color:#a0a0a0; }
#rights #generator table.items .odd td { background:#FFFFFF; }
#rights #generator table.items .even td { background:transparent; }

/**
* Sortable style.
*/

#rights .sortable-table .sortable-placeholder { height:38px; background-color:#000000; }

/**
* Tooltip style.
*/

#rightsTooltip {
	max-width:500px;
	padding:8px;
    position:absolute;
	background:url('../images/bg_tooltip.gif') 100% 100% repeat-x #ffffff;
    border:1px solid #c0c0c0;
    font-family:Consolas, Arial, san-serif !important;
    font-size:11px;
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
}
#rightsTooltip .heading { font-weight:bold; }
#rightsTooltip .content { color:#808080; }

#generator table th{
    padding: 0.1em 1em;
}


text:
*Issue #Number*
571

**Author:**
- Jiajun Mao

## The Problem

In last year's IGVC competition, Jessie turned 180 degrees before starting traveling on the course. This is presumably caused by the current navigation model ignoring everything behind Jessie and default that nothing exists there. This caused the problem with the path planning algorithm thinking that the shortest path is to walk backward to the place where "no line exists".

## Proposed Solution

- The problem could potentially be solved by creating a semi-circle behind the robot with the diameter of the distance between the left and right lines of the course and make the robot think that that is a part of the line defining the course. Thus the robot would not travel backwards.
- How to measure the location of the cone
    - Obtain the layered_costmap_ from the costmap2d::layer which contains a getPlugin method that will return a vector of **boost::shared_ptr``<Layer``>** with each shared_ptr pointing to a layer
    - From the vector of layers we can obtain the LineLayer representing the lines the robot is seeing around itself
    - detect in a small radius of that line whether a point belongs to the same line still exist, until reaching the endpoint of the line
    - when both endpoints of the line on the right and left are reached, use a grid-based search algorithm to draw a line between the two points (or a cone)
- Create a new layer in the 2D cost map and artificially insert points on the line/cone created above to act as an obstacle behind the robot
    - Create a new layer in igvc_navigation/mapper
    - Incorporate the new layer into the cost map
- Create a ROS service that generate the new cost2d map
    - call when service when the robot reaches a waypoint and at the start of the course
    - the service will also contain a remove method that will remove the cone created at the course start after the robot has reached the first way point [or some other specific period of time]

## Questions & Research

- ROS Service
    - Similar to subscriber and pubisher but is a one time call
    - written with a .srv file and a structure with response/request classes will be generated
    - ServiceClient calls a service with
        - ros::ServiceClient srvClient = nh.serviceClient<serviceType>("service_name");
        - srvClient.call(serviceInstantiation); [returns true if service calls with success and serviceInstantion is filled, and false otherwise]
    - Service contains a callback method used to process the request upon received. It is called with
        - ros::ServiceServer srvServer = nh.advertiseService(serviceType, <callback>);

- Costmap2d layer
    - A map that indicates discretized information about the world the robot is in
    - consist of a flattened array that represent a two-dimensional map
    - contains useful functions such as:
        - void GridLayer::updateCosts - update the cost in the master grid map according to the value in this layer
        - void GridLayer::updateBounds - expand the cost map layer to include new cells that the robot is in

## Overall Scope

### Affected Packages

- igvc_navigation/src/mapper

### Schedule

Subtask 1 (11/24/2019): Finish generating the line/cone

Subtask 2 (11/28/2019): Modify mapper.cpp to insert the new layer

Code Review (12/2/2019): Most likely I would have everything figured out by then and ready for review. Hopefully it could be sooner.


text:
package org.elasticsearch.transport;

import org.elasticsearch.ElasticSearchWrapperException;
import org.elasticsearch.cluster.node.DiscoveryNode;

/**
 *
 */
public class SendRequestTransportException extends ActionTransportException implements ElasticSearchWrapperException {

    public SendRequestTransportException(DiscoveryNode node, String action, Throwable cause) {
        super(node == null ? null : node.name(), node == null ? null : node.address(), action, cause);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<todolist>
    <tasks>
        <desc>Buy milk</desc>
        <priority>Very Important</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>health</tagged>
    </tasks>
    <tasks>
        <desc>Do CS2103 tutorial</desc>
        <priority>Important</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>tutorial</tagged>
        <tagged>NUS</tagged>
    </tasks>
    <tasks>
        <desc>Exercise at home</desc>
        <priority>Normal</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>health</tagged>
    </tasks>
    <tasks>
        <desc>Have some beauty sleep</desc>
        <priority>Normal</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>health</tagged>
    </tasks>
    <tasks>
        <desc>Do more tutorials</desc>
        <priority>Important</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>tutorial</tagged>
    </tasks>
    <tasks>
        <desc>Talk to people</desc>
        <priority>Normal</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
        <tagged>interests</tagged>
    </tasks>
    <tasks>
        <desc>hello</desc>
        <priority>Normal</priority>
        <finishedStatus>false</finishedStatus>
        <startDate>null</startDate>
        <endDate>null</endDate>
    </tasks>
    <tags>health</tags>
    <tags>NUS</tags>
    <tags>tutorial</tags>
    <tags>interests</tags>
</todolist>


text:
package org.apache.skywalking.oap.server.configuration.apollo;

import com.google.common.base.Strings;
import org.apache.skywalking.oap.server.configuration.api.AbstractConfigurationProvider;
import org.apache.skywalking.oap.server.configuration.api.ConfigWatcherRegister;
import org.apache.skywalking.oap.server.library.module.ModuleStartException;

/**
 * Get configuration from Apollo configuration center.
 */
public class ApolloConfigurationProvider extends AbstractConfigurationProvider {
    private ApolloConfigurationCenterSettings settings;

    @Override
    public String name() {
        return "apollo";
    }

    @Override
    public ConfigCreator newConfigCreator() {
        return new ConfigCreator<ApolloConfigurationCenterSettings>() {
            @Override
            public Class type() {
                return ApolloConfigurationCenterSettings.class;
            }

            @Override
            public void onInitialized(final ApolloConfigurationCenterSettings initialized) {
                settings = initialized;
            }
        };
    }

    @Override
    protected ConfigWatcherRegister initConfigReader() throws ModuleStartException {
        final String apolloCluster = settings.getApolloCluster();

        if (!Strings.isNullOrEmpty(apolloCluster)) {
            System.setProperty("apollo.cluster", apolloCluster);
        }

        final String apolloMeta = settings.getApolloMeta();

        if (!Strings.isNullOrEmpty(apolloMeta)) {
            System.setProperty("apollo.meta", apolloMeta);
        }

        final String appId = settings.getAppId();

        if (!Strings.isNullOrEmpty(appId)) {
            System.setProperty("app.id", appId);
        }

        final String env = settings.getApolloEnv();

        if (!Strings.isNullOrEmpty(env)) {
            System.setProperty("env", env);
        }

        return new ApolloConfigWatcherRegister(settings);
    }
}


text:
/*---------------breadcrumbs---------------*/
/* @import "../variables/core-utils"; */


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * A request message for Images.Get. See the method description for details.
 *
 * Generated from protobuf message google.cloud.compute.v1.GetImageRequest
 */
class GetImageRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Name of the image resource to return.
     *
     * Generated from protobuf field string image = 100313435 [(.google.api.field_behavior) = REQUIRED];
     */
    private $image = '';
    /**
     * Project ID for this request.
     *
     * Generated from protobuf field string project = 227560217 [(.google.api.field_behavior) = REQUIRED];
     */
    private $project = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $image
     *           Name of the image resource to return.
     *     @type string $project
     *           Project ID for this request.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Name of the image resource to return.
     *
     * Generated from protobuf field string image = 100313435 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Name of the image resource to return.
     *
     * Generated from protobuf field string image = 100313435 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setImage($var)
    {
        GPBUtil::checkString($var, True);
        $this->image = $var;

        return $this;
    }

    /**
     * Project ID for this request.
     *
     * Generated from protobuf field string project = 227560217 [(.google.api.field_behavior) = REQUIRED];
     * @return string
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * Project ID for this request.
     *
     * Generated from protobuf field string project = 227560217 [(.google.api.field_behavior) = REQUIRED];
     * @param string $var
     * @return $this
     */
    public function setProject($var)
    {
        GPBUtil::checkString($var, True);
        $this->project = $var;

        return $this;
    }

}


text:
.class interface abstract Lcom/htc/hfm/HfmClient$ICallback;
.super Ljava/lang/Object;
.source "HfmClient.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/hfm/HfmClient;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x60a
    name = "ICallback"
.end annotation

# virtual methods
.method public abstract onAbortComplete(I)V
.end method

.method public abstract onCancelReservationComplete(I)V
.end method

.method public abstract onHfmShutdown()V
.end method

.method public abstract onInterrupt()V
.end method

.method public abstract onReleaseServiceComplete(I)V
.end method

.method public abstract onReserveServiceComplete(I)V
.end method

.method public abstract onSelectCommandComplete(ILjava/lang/String;)V
.end method

.method public abstract onSpeakComplete(I)V
.end method

.method public abstract onStartRecording()V
.end method

.method public abstract onStopRecording()V
.end method

.method public abstract onTestWakeUpPhraseComplete(I)V
.end method

.method public abstract onTimeout()V
.end method

.method public abstract onWakeUpModeComplete(I)V
.end method


text:
package christophedelory.playlist.smil;

/**
 * Defines a time container with semantics based upon par,
 * but with the additional constraint that only one child element may play at any given time.
 * If any element begins playing while another is already playing, the element that was playing is stopped.
 * More clearly, this time container is used to define a mutually exclusive set of clips,
 * and to describe pausing and resuming behaviors among these clips.
 * @version $Revision: 90 $
 * @author Christophe Delory
 * @castor.class xml="excl"
 */
public class ExclusiveTimingElement extends AbstractTimingElement
{
    @Override
    public void acceptDown(final SmilVisitor visitor)
    {
        visitor.beginVisitExclTimingElement(this); // Throws NullPointerException if visitor is null.

        super.acceptDown(visitor);

        visitor.endVisitExclTimingElement(this);
    }
}


text:
import React from "react";
import { TileLayer } from "react-leaflet";

const OSMTileLayer = () => {
  return (
    <TileLayer
      url="//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      attribution="© OpenStreetMap contributors"
    />
  );
};

const MapBoxTileLayer = ({ apiKey }) => {
  return (
    <TileLayer
      attribution={[
        '© Mapbox',
        '© OpenStreetMap',
        'Improve this map'
      ].join(" ")}
      url={`https://api.tiles.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token=${apiKey}`}
    />
  );
};

const ToucanTileLayer = () => {
  return process.env.MAPBOX_API_KEY
    ? <MapBoxTileLayer apiKey={process.env.MAPBOX_API_KEY} />
    : <OSMTileLayer />;
};

export default ToucanTileLayer;


text:
package tap.pipelines

import akka.NotUsed
import akka.stream.scaladsl.{Flow, Framing, Source}
import akka.util.ByteString
import tap.data.CustomTypes.{DocumentStr, SectionStr}
import tap.data.{OldTapDocument, OldTapSection, OldTapSentence, OldTapTags}
//import tap.nlp.old.{NlpBuilders, NlpDocument, OldNlpSentence}

/**
  * Created by andrew@andrewresearch.net on 24/2/17.
  */
object Parsing_OpenNLP {

  object Pipeline {
    /** A stream of document strings split into sections on newline,
      *  which are treated as NLP Documents and then used to produce
      *  TapSections that are folded into a OldTapDocument
      */
    //val default:Flow[SectionStr,OldTapDocument,NotUsed] = nlpDocs.via(nlpSentences).via(tapSentences).via(tapSection).via(tapDocument)

  }

  //import tap.nlp.old.openNlp.OpenNlpImplicits._

/*
  val nlpDocs:Flow[SectionStr,NlpDocument,NotUsed] = Flow[String].map(s => NlpBuilders.document(s))

  val nlpSentences:Flow[NlpDocument,List[OldNlpSentence],NotUsed] = Flow[NlpDocument].map(_.sentences)

  val tapSentences:Flow[List[OldNlpSentence],List[OldTapSentence],NotUsed] = Flow[List[OldNlpSentence]].map(_.map(s => buildTapSentence(s)))

  val tapSection:Flow[List[OldTapSentence],OldTapSection,NotUsed] = Flow[List[OldTapSentence]].map(OldTapSection(_))

  val tapDocument = Flow[OldTapSection].fold(List[OldTapSection]())(_:+_).map(OldTapDocument(_))

  def buildTapSentence(sentence:OldNlpSentence) = OldTapSentence(
    sentence.text,
    sentence.words.map(_.toLowerCase),
    OldTapTags(
      sentence.lemmas,
      sentence.posTags
    )
  )
*/

}


text:
@interface WHChartBar : UIView

@property (nonatomic, strong)   UIColor *backgroundColorofChart;
@property (nonatomic, strong)   UIColor *colorofBar;
@property (nonatomic, strong)   CAShapeLayer *bar;
@property (nonatomic)           float percentage; //      percentage = (bar's height) / (self.view's height)
@property (nonatomic)           float labelValue;

@end


text:
/**********************************************************************

  Audacity: A Digital Audio Editor

  Generator.h

  Two Abstract classes, Generator, and BlockGenerator, that effects which
  generate audio should derive from.

  Block Generator breaks the synthesis task up into smaller parts.

  Dominic Mazzoni
  Vaughan Johnson

**********************************************************************/

#include "../Prefs.h"

#include "Generator.h"
#include "TimeWarper.h"

bool Generator::Process()
{
   if (mDuration < 0.0)
      return false;

   // Set up mOutputTracks.
   // This effect needs Track::All for sync-lock grouping.
   this->CopyInputTracks(Track::All);

   // Iterate over the tracks
   bool bGoodResult = true;
   int ntrack = 0;
   TrackListIterator iter(mOutputTracks);
   Track* t = iter.First();

   while (t != NULL)
   {
      if (t->GetKind() == Track::Wave && t->GetSelected()) {
         WaveTrack* track = (WaveTrack*)t;

         bool editClipCanMove;
         gPrefs->Read(wxT("/GUI/EditClipCanMove"), &editClipCanMove, true);

         //if we can't move clips, and we're generating into an empty space,
         //make sure there's room.
         if (!editClipCanMove &&
             track->IsEmpty(mT0, mT1+1.0/track->GetRate()) &&
             !track->IsEmpty(mT0, mT0+mDuration-(mT1-mT0)-1.0/track->GetRate()))
         {
            wxMessageBox(
                  _("There is not enough room available to generate the audio"),
                  _("Error"), wxICON_STOP);
            Failure();
            return false;
         }

         if (mDuration > 0.0)
         {
            // Create a temporary track
            WaveTrack *tmp = mFactory->NewWaveTrack(track->GetSampleFormat(),
                                                    track->GetRate());
            BeforeTrack(*track);
            BeforeGenerate();

            // Fill it with data
            if (!GenerateTrack(tmp, *track, ntrack))
               bGoodResult = false;
            else {
               // Transfer the data from the temporary track to the actual one
               tmp->Flush();
               SetTimeWarper(new StepTimeWarper(mT0+mDuration, mDuration-(mT1-mT0)));
               bGoodResult = track->ClearAndPaste(mT0, mT1, tmp, true,
                     false, GetTimeWarper());
               delete tmp;
            }

            if (!bGoodResult) {
               Failure();
               return false;
            }
         }
         else
         {
            // If the duration is zero, there's no need to actually
            // generate anything
            track->Clear(mT0, mT1);
         }

         ntrack++;
      }
      else if (t->IsSyncLockSelected()) {
         t->SyncLockAdjust(mT1, mT0 + mDuration);
      }
      // Move on to the next track
      t = iter.Next();
   }

   Success();

   this->ReplaceProcessedTracks(bGoodResult);

   mT1 = mT0 + mDuration; // Update selection.

   return true;
}

bool BlockGenerator::GenerateTrack(WaveTrack *tmp,
                                   const WaveTrack &track,
                                   int ntrack)
{
   bool bGoodResult = true;
   numSamples = track.TimeToLongSamples(mDuration);
   sampleCount i = 0;
   float *data = new float[tmp->GetMaxBlockSize()];
   sampleCount block = 0;

   while ((i < numSamples) && bGoodResult) {
      block = tmp->GetBestBlockSize(i);
      if (block > (numSamples - i))
         block = numSamples - i;

      GenerateBlock(data, track, block);

      // Add the generated data to the temporary track
      tmp->Append((samplePtr)data, floatSample, block);
      i += block;

      // Update the progress meter
      if (TrackProgress(ntrack, (double)i / numSamples))
         bGoodResult = false;
   }
   delete[] data;
   return bGoodResult;
}


text:
void wrenLoadIOLibrary(WrenVM* vm);

WrenForeignMethodFn wrenBindIOForeignMethod(WrenVM* vm, const char* className,
                                            const char* signature);

#endif

#endif


text:
@implementation BRMerkleBlockEntity

@dynamic blockHash;
@dynamic height;
@dynamic version;
@dynamic prevBlock;
@dynamic merkleRoot;
@dynamic timestamp;
@dynamic target;
@dynamic nonce;
@dynamic totalTransactions;
@dynamic hashes;
@dynamic flags;

- (instancetype)setAttributesFromBlock:(BRMerkleBlock *)block;
{
    [self.managedObjectContext performBlockAndWait:^{
        self.blockHash = block.blockHash;
        self.version = block.version;
        self.prevBlock = block.prevBlock;
        self.merkleRoot = block.merkleRoot;
        self.timestamp = block.timestamp;
        self.target = block.target;
        self.nonce = block.nonce;
        self.totalTransactions = block.totalTransactions;
        self.hashes = [NSData dataWithData:block.hashes];
        self.flags = [NSData dataWithData:block.flags];
        self.height = block.height;
    }];

    return self;
}

- (BRMerkleBlock *)merkleBlock
{
    __block BRMerkleBlock *block = nil;

    [self.managedObjectContext performBlockAndWait:^{
        block = [[BRMerkleBlock alloc] initWithBlockHash:self.blockHash version:self.version prevBlock:self.prevBlock
                 merkleRoot:self.merkleRoot timestamp:self.timestamp target:self.target nonce:self.nonce
                 totalTransactions:self.totalTransactions hashes:self.hashes flags:self.flags height:self.height parentBlock:nil];
    }];

    return block;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using Aurora.ScriptEngine.AuroraDotNetEngine;

namespace Aurora.ScriptEngine.AuroraDotNetEngine.MiniModule
{
    public interface IAvatar : IEntity
    {

        bool IsChildAgent { get; }

        //// <value>
        /// Array of worn attachments, empty but not null, if no attachments are worn
        /// </value>

        IAvatarAttachment[] Attachments { get; }

        /// <summary>
        /// Request to open an url clientside
        /// </summary>
        void LoadUrl(IObject sender, string message, string url);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">HelloAndroid! First app by Luke Schoen</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>


text:
/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('Emergence.cms.view.DualViewController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.emergence-cms-dualview',
    requires: [
        'Ext.util.MixedCollection'
    ],

    control: {
        'emergence-cms-editor': {
            contentrecordchange: 'onContentRecordChange'
        },
        'emergence-cms-editor field[reference=titleField]': {
            change: 'onTitleChange'
        },
        'emergence-cms-editor field[reference=tagsField]': {
            change: 'onTagsChange'
        },
        'emergence-cms-editor button[reference=publishedTimeBtn] menucheckitem': {
            checkchange: 'onPublishTimeChange'
        },
        'emergence-cms-editor button[reference=publishedTimeBtn] field': {
            change: 'onPublishTimeChange'
        },
        'emergence-cms-editor dashboard-column': {
//            add: 'onComposerAdd', // TODO: uncomment when this is fixed: http://www.sencha.com/forum/showthread.php?288314-Having-an-add-event-listener-in-a-ViewController-prevents-menu-item-events...
            move: 'onComposerMove',
            remove: 'onComposerRemove'
        },
        'emergence-cms-composer': {
            previewchange: 'onComposerPreviewChange'
        }
    },

    // lifecycle overrides
    beforeInit: function() {
        this.itemEls = new Ext.util.MixedCollection();
    },

    // TODO: delete this method and uncomment the identical listener in the control config above after upgrading to ext 5.0.1
    init: function() {
        this.control('emergence-cms-editor dashboard-column', {add: 'onComposerAdd'});
    },

    // event handlers
    onContentRecordChange: function(editor, contentRecord) {
        var view = this.getView(),
            previewCmp = view.rendered && view.lookupReference('preview'),
            author = contentRecord.phantom ? (window.SiteEnvironment && window.SiteEnvironment.user) : contentRecord.get('Author'),
            context = contentRecord.get('Context');

        if (previewCmp) {
            if (author) {
                previewCmp.authorLink.set({href: '/people/' + (author.Username || author.ID)}).update(author.FirstName + ' ' + author.LastName);
                previewCmp.authorWrapper.show();
            }
            if (context) {
                previewCmp.contextLink.set({href: context.recordURL}).update(context.recordTitle);
                previewCmp.contextWrapper.show();
            }
            if (author || context) {
                previewCmp.infoWrapper.show();
            }
        }
    },

    onTitleChange: function(titleField, value) {
        var previewCmp = this.lookupReference('preview'),
            contentRecord = this.lookupReference('editor').getContentRecord(),
            href = contentRecord && !contentRecord.phantom && contentRecord.toUrl();

        previewCmp.titleLink.set({href: href || '#'}).update(value);
    },

    onTagsChange: function(tagsField) {
        var previewCmp = this.lookupReference('preview'),
            tagsWrapper = previewCmp.tagsWrapper,
            tagsData = Ext.pluck(tagsField.getValueRecords(), 'data');

        Ext.suspendLayouts();

        if (!tagsData || !tagsData.length) {
            tagsWrapper.hide();
        } else {
            previewCmp.lookupTpl('tagsListTpl').overwrite(previewCmp.tagsCt, tagsData);
            tagsWrapper.show();
        }

        Ext.resumeLayouts(true);
    },

    onPublishTimeChange: Ext.Function.createBuffered(function() {
        var editorView = this.lookupReference('editor'),
            previewCmp = this.lookupReference('preview'),
            date = editorView.lookupReference('publishedTimeBtn').down('menucheckitem').checked ? new Date() : editorView.getSelectedDateTime();

        previewCmp.timeEl.set({datetime: Ext.Date.format(date, 'c')}).update(Ext.Date.format(date, 'l, F n, Y \\a\\t g:i a'));
        previewCmp.timeWrapper.show();
        previewCmp.infoWrapper.show();
    }, 50),

    onComposerAdd: function(column, itemComposer, position) {
        var me = this,
            itemEls = me.itemEls,
            previewCmp = me.lookupReference('preview'),
            itemTpl = previewCmp.lookupTpl('itemTpl'),
            itemId = itemComposer.getContentItemId(),
            itemData = {
                itemId: itemId,
                contentCls: itemComposer.self.contentCls
            };

        itemComposer.getPreviewHtml(function(html) {
            itemData.html = html;

            if (position > 0 && itemEls.getCount()) {
                itemEls.insert(position, itemId, itemTpl.insertAfter(itemEls.getAt(position - 1), itemData, true));
            } else {
                itemEls.add(itemId, itemTpl.insertFirst(previewCmp.itemsCt, itemData, true));
            }
        });
    },

    onComposerMove: function(column, itemComposer, prevIndex, newIndex) {
        var me = this,
            itemEls = me.itemEls,
            previewCmp = me.lookupReference('preview'),
            itemId = itemComposer.getContentItemId(),
            itemEl = itemEls.get(itemId),
            anchorItemEl = itemEls.getAt(newIndex);

        // reorder in DOM
        if (newIndex > prevIndex) {
            itemEl.insertAfter(anchorItemEl);
        } else {
            itemEl.insertBefore(anchorItemEl);
        }

        // reorder internal collection
        itemEls.remove(itemEl);
        itemEls.insert(newIndex, itemId, itemEl);
    },

    onComposerRemove: function(column, itemComposer) {
        var itemEls = this.itemEls,
            itemEl = itemEls.get(itemComposer.getContentItemId());

        itemEls.remove(itemEl);
        itemEl.destroy();
    },

    onComposerPreviewChange: function(itemComposer, html) {
        this.itemEls.get(itemComposer.getContentItemId()).update(html);
    }
});


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ContainerViewController *customContainer;

@property BOOL appInBackground;

@end


text:
package com.youzu.clan.base.widget.list;

public interface OnMutipleChoiceListener {

	public void onChoiceChanged(RefreshListView listView, int checkedCount);
	/**
	 * 列表是否正处在编辑状态
	 * @param listView
	 * @param isEditable
	 */
	public void onEditableChanged(RefreshListView listView);

}


text:
package models.services

import com.mohiva.play.silhouette.core.LoginInfo
import com.mohiva.play.silhouette.core.providers.CommonSocialProfile
import com.mohiva.play.silhouette.core.services.{AuthInfo, IdentityService}
import models.User
import models.daos.UserDAO
import org.bson.types.ObjectId
import play.api.libs.concurrent.Execution.Implicits._
import scaldi.{Injectable, Injector}

import scala.concurrent.Future

class UserService(implicit inj: Injector)  extends IdentityService[User] with Injectable {

  val userDAO = inject[UserDAO]
  /**
   * Retrieves a user that matches the specified login info.
   *
   * @param loginInfo The login info to retrieve a user.
   * @return The retrieved user or None if no user could be retrieved for the given login info.
   */
  def retrieve(loginInfo: LoginInfo): Future[Option[User]] = userDAO.find(loginInfo)

  /**
   * Saves a user.
   *
   * @param user The user to save.
   * @return The saved user.
   */
  def save(user: User) = userDAO.save(user)

  /**
   * Saves the social profile for a user.
   *
   * If a user exists for this profile then update the user, otherwise create a new user with the given profile.
   *
   * @param profile The social profile to save.
   * @return The user for whom the profile was saved.
   */
  def save[A <: AuthInfo](profile: CommonSocialProfile[A]) = {
    userDAO.find(profile.loginInfo).flatMap {
      case Some(user) => // Update user with profile
        userDAO.save(user.copy(
          firstName = profile.firstName,
          lastName = profile.lastName,
          fullName = profile.fullName,
          email = profile.email,
          avatarURL = profile.avatarURL
        ))
      case None => // Insert a new user
        userDAO.save(User(
          userID = new ObjectId(),
          loginInfo = profile.loginInfo,
          firstName = profile.firstName,
          lastName = profile.lastName,
          fullName = profile.fullName,
          email = profile.email,
          avatarURL = profile.avatarURL
        ))
    }
  }
}


text:
"""
Some basic tests for STR load.
"""

import os
import flopy
import numpy as np

path = os.path.join('..', 'examples', 'data', 'mf2005_test')
pthgw = os.path.join('..', 'examples', 'groundwater_paper', 'uspb', 'flopy')
cpth = os.path.join('temp', 't014')
# make the directory if it does not exist
if not os.path.isdir(cpth):
    os.makedirs(cpth)

mf_items = ['str.nam', 'DG.nam']
pths = [path, pthgw]

exe_name = 'mf2005dbl'
v = flopy.which(exe_name)

run = True
if v is None:
    run = False

def load_str(mfnam, pth):
    m = flopy.modflow.Modflow.load(mfnam, exe_name=exe_name, forgive=False,
                                   model_ws=pth, verbose=True)
    assert m.load_fail is False

    # rewrite files
    m.model_ws = cpth
    m.write_input()

    # attempt to run the model
    if run:
        try:
            success, buff = m.run_model(silent=False)
        except:
            pass
        assert success, 'base model run did not terminate successfully'

    # load files
    pth = os.path.join(cpth, '{}.str'.format(m.name))
    str2 = flopy.modflow.ModflowStr.load(pth, m)
    for name in str2.dtype.names:
        assert np.array_equal(str2.stress_period_data[0][name],
                              m.str.stress_period_data[0][name]) is True
    for name in str2.dtype2.names:
        assert np.array_equal(str2.segment_data[0][name],
                              m.str.segment_data[0][name]) is True

    return

def test_mf2005load():
    for namfile, pth in zip(mf_items, pths):
        yield load_str, namfile, pth
    return

if __name__ == '__main__':
    for namfile, pth in zip(mf_items, pths):
        load_str(namfile, pth)


text:
import os
import sys
import array
import getopt
import math
import random
import networkx

class Txt2MetisScript:
    def __init__(self, argv):
        self.argc = len(argv)
        self.argv = argv

    def usage(self):
        print "Usage: " + sys.argv[0] + " [-w] <in txt graph> <out metis graph>"
        print "Example: " + sys.argv[0] + "../../../data/graphs/graph_ba_1k.txt ../../../data/graph_ba_1k.metis\n"
        print "\t[-h]              : This help message"
        print "\t[-w]              : Input graph has weights"
        print "\t<in txt graph>    : Input networkx txt graph"
        print "\t<out metis graph> : Output metis graph"
        sys.exit(1)

    def main(self):
        # Parse options
        try:
            opts, args = getopt.getopt(self.argv[1:], "wh", ["weight","help"])
        except getopt.GetoptError, err:
            print str(err)
            self.usage()
            return(1)

        # Defaults
        useweight = False;

        for o, a in opts:
            if o in ("-h", "--help"):
                self.usage()
                return(0)
            elif o in ("-w", "--weight"):
                useweight = True
            else:
                print "Invalid option %s" % (o)
                return(1)

        # Check command-line arguments
        if (len(args) != 2):
            self.usage()
            return(1)

        infile = args[0]
        outfile = args[1]

        print "Converting graph %s from txt format to metis weighted edge format" % (infile)

        try:
            # Read from file
            print "Reading graph file %s" % (infile)
            f = open(infile, "rb")
            if (useweight):
                g = networkx.read_weighted_edgelist(f, nodetype=int);
            else:
                g = networkx.read_edgelist(f, nodetype=int);
            f.close()
        except:
            print "ERROR: Failed to read input graph, check that it exists and you are using the correct weight (-w) option."
            return(1)

        if ((useweight) and ('weight' not in g.edges(data=True)[0][2])):
            print "ERROR: Weight option specified yet no weights in graph"
            return(1)

        print "Read %d nodes, %d edges" % (g.number_of_nodes(), g.number_of_edges())

        # Sort the nodes in increasing order
        snodes = g.nodes()
        snodes.sort(key=int)

        # Remove self loops
        selflist = []
        for s in snodes:
            if (s in g.neighbors(s)):
                selflist.append(s)

        print "Removing %d self loops" % (len(selflist))
        for s in selflist:
            g.remove_edge(s,s)

        # Save to file
        print "Writing metis graph file %s" % (outfile)
        f = open(outfile, "wb")
        if (useweight):
            f.write("%s %s 1\n" % (g.number_of_nodes(), g.number_of_edges()));
        else:
            f.write("%s %s\n" % (g.number_of_nodes(), g.number_of_edges()));

        # Iterate over each neighbor
        if (useweight):
            for s in snodes:
                for n in g.neighbors(s):
                    f.write(" %10d %3d" % (int(n), g[s][n]['weight']))
                f.write("\n");
        else:
            for s in snodes:
                for n in g.neighbors(s):
                    f.write(" %10d" % (int(n)))
                f.write("\n");
        f.close()

        print "Done"
        return 0

if __name__ == '__main__':

    prog = Txt2MetisScript(sys.argv)
    sys.exit(prog.main())


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::flow::interface10::opencl_factory< DeviceFilter > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

flow

interface10

opencl_factory

Classes |
Public Types |
Public Member Functions |
Friends |
List of all members

tbb::flow::interface10::opencl_factory< DeviceFilter > Class Template Reference

Classes

class  	kernel

Public Types

template<typename T >

using 	async_msg_type = opencl_async_msg< T, opencl_factory< DeviceFilter >>

typedef opencl_device 	device_type

typedef kernel 	kernel_type

typedef opencl_range 	range_type

Public Member Functions

bool 	init (const opencl_device_list &device_list)

template<typename... Args>

void 	send_kernel (opencl_device device, const kernel_type &kernel, const range_type &work_size, Args &...args)

template<typename T , typename... Rest>

void 	send_data (opencl_device device, T &t, Rest &...args)

void 	send_data (opencl_device)

template<typename FinalizeFn , typename... Args>

void 	finalize (opencl_device device, FinalizeFn fn, Args &...args)

const opencl_device_list & 	devices ()

Friends

template<typename Factory >

class 	opencl_program

template<typename Factory >

class 	opencl_buffer_impl

template<typename Factory >

class 	opencl_memory

The documentation for this class was generated from the following file:

flow_graph_opencl_node.h

Copyright © 2005-2017 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
package nl.mycompany.questionaire.conf;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;

import com.vaadin.spring.annotation.EnableVaadin;

@Configuration
@Import({ RepositoryConfiguration.class , ActivitiConfiguration.class, QuestionaireConfiguration.class})
@ComponentScan({"nl.mycompany.questionaire", "nl.mycompany.core", "nl.mycompany.webapp"})
@PropertySource("classpath:application.properties")
@EnableVaadin
//to enable the aspect to be configured by spring
@EnableSpringConfigured
@EnableAspectJAutoProxy
public class ApplicationConfiguration {

}


text:
package org.jkiss.dbeaver.ext.generic.model;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCTableConstraint;
import org.jkiss.dbeaver.model.impl.struct.AbstractTableConstraintColumn;
import org.jkiss.dbeaver.model.meta.Property;

/**
 * GenericTableConstraintColumn
 */
public class GenericTableConstraintColumn extends AbstractTableConstraintColumn
{
    private JDBCTableConstraint constraint;
    private GenericTableColumn tableColumn;
    private int ordinalPosition;

    public GenericTableConstraintColumn(JDBCTableConstraint constraint, GenericTableColumn tableColumn, int ordinalPosition)
    {
        this.constraint = constraint;
        this.tableColumn = tableColumn;
        this.ordinalPosition = ordinalPosition;
    }

    public GenericTableConstraintColumn(GenericTableConstraint constraint, GenericTableConstraintColumn column)
    {
        this.constraint = constraint;
        this.tableColumn = column.tableColumn;
        this.ordinalPosition = column.ordinalPosition;
    }

    @NotNull
    @Override
    public String getName()
    {
        return tableColumn.getName();
    }

    @NotNull
    @Override
    @Property(id = "name", viewable = true, order = 1)
    public GenericTableColumn getAttribute()
    {
        return tableColumn;
    }

    @Override
    @Property(viewable = false, order = 2)
    public int getOrdinalPosition()
    {
        return ordinalPosition;
    }

//    @Property(name = "Description", viewable = true, order = 100)
    @Nullable
    @Override
    public String getDescription()
    {
        return tableColumn.getDescription();
    }

    @Override
    public JDBCTableConstraint getParentObject()
    {
        return constraint;
    }

    @NotNull
    @Override
    public GenericDataSource getDataSource()
    {
        return (GenericDataSource) constraint.getDataSource();
    }

}


text:
package io.druid.query.groupby.epinephelinae;

import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import io.druid.collections.ResourceHolder;
import io.druid.java.util.common.CloseableIterators;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.Pair;
import io.druid.java.util.common.io.Closer;
import io.druid.java.util.common.parsers.CloseableIterator;
import io.druid.query.AbstractPrioritizedCallable;
import io.druid.query.QueryInterruptedException;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.dimension.DimensionSpec;
import io.druid.query.groupby.epinephelinae.Grouper.Entry;
import io.druid.query.groupby.epinephelinae.Grouper.KeySerdeFactory;
import io.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.ColumnValueSelector;
import io.druid.segment.DimensionSelector;
import io.druid.segment.ObjectColumnSelector;
import io.druid.segment.column.ColumnCapabilities;
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * ParallelCombiner builds a combining tree which asynchronously aggregates input entries.  Each node of the combining
 * tree is a combining task executed in parallel which aggregates inputs from the child nodes.
 */
public class ParallelCombiner<KeyType>
{
  // The combining tree created by this class can have two different degrees for intermediate nodes.
  // The "leaf combine degree (LCD)" is the number of leaf nodes combined together, while the "intermediate combine
  // degree (ICD)" is the number of non-leaf nodes combined together. The below picture shows an example where LCD = 2
  // and ICD = 4.
  //
  //        o         <- non-leaf node
  //     / / \ \      <- ICD = 4
  //  o   o   o   o   <- non-leaf nodes
  // / \ / \ / \ / \  <- LCD = 2
  // o o o o o o o o  <- leaf nodes
  //
  // The reason why we need two different degrees is to optimize the number of non-leaf nodes which are run by
  // different threads at the same time. Note that the leaf nodes are sorted iterators of SpillingGroupers which
  // generally returns multiple rows of the same grouping key which in turn should be combined, while the non-leaf nodes
  // are iterators of StreamingMergeSortedGroupers and always returns a single row per grouping key. Generally, the
  // performance will get better as LCD becomes low while ICD is some value larger than LCD because the amount of work
  // each thread has to do can be properly tuned. The optimal values for LCD and ICD may vary with query and data. Here,
  // we use a simple heuristic to avoid complex optimization. That is, ICD is fixed as a user-configurable value and the
  // minimum LCD satisfying the memory restriction is searched. See findLeafCombineDegreeAndNumBuffers() for more
  // details.
  private static final int MINIMUM_LEAF_COMBINE_DEGREE = 2;

  private final Supplier<ResourceHolder<ByteBuffer>> combineBufferSupplier;
  private final AggregatorFactory[] combiningFactories;
  private final KeySerdeFactory<KeyType> combineKeySerdeFactory;
  private final ListeningExecutorService executor;
  private final Comparator<Entry<KeyType>> keyObjComparator;
  private final int concurrencyHint;
  private final int priority;
  private final long queryTimeoutAt;

  // The default value is 8 which comes from an experiment. A non-leaf node will combine up to intermediateCombineDegree
  // rows for the same grouping key.
  private final int intermediateCombineDegree;

  public ParallelCombiner(
      Supplier<ResourceHolder<ByteBuffer>> combineBufferSupplier,
      AggregatorFactory[] combiningFactories,
      KeySerdeFactory<KeyType> combineKeySerdeFactory,
      ListeningExecutorService executor,
      boolean sortHasNonGroupingFields,
      int concurrencyHint,
      int priority,
      long queryTimeoutAt,
      int intermediateCombineDegree
  )
  {
    this.combineBufferSupplier = combineBufferSupplier;
    this.combiningFactories = combiningFactories;
    this.combineKeySerdeFactory = combineKeySerdeFactory;
    this.executor = executor;
    this.keyObjComparator = combineKeySerdeFactory.objectComparator(sortHasNonGroupingFields);
    this.concurrencyHint = concurrencyHint;
    this.priority = priority;
    this.intermediateCombineDegree = intermediateCombineDegree;

    this.queryTimeoutAt = queryTimeoutAt;
  }

  /**
   * Build a combining tree for the input iterators which combine input entries asynchronously.  Each node in the tree
   * is a combining task which iterates through child iterators, aggregates the inputs from those iterators, and returns
   * an iterator for the result of aggregation.
   * <p>
   * This method is called when data is spilled and thus streaming combine is preferred to avoid too many disk accesses.
   *
   * @return an iterator of the root grouper of the combining tree
   */
  public CloseableIterator<Entry<KeyType>> combine(
      List<? extends CloseableIterator<Entry<KeyType>>> sortedIterators,
      List<String> mergedDictionary
  )
  {
    // CombineBuffer is initialized when this method is called and closed after the result iterator is done
    final ResourceHolder<ByteBuffer> combineBufferHolder = combineBufferSupplier.get();
    final ByteBuffer combineBuffer = combineBufferHolder.get();
    final int minimumRequiredBufferCapacity = StreamingMergeSortedGrouper.requiredBufferCapacity(
        combineKeySerdeFactory.factorizeWithDictionary(mergedDictionary),
        combiningFactories
    );
    // We want to maximize the parallelism while the size of buffer slice is greater than the minimum buffer size
    // required by StreamingMergeSortedGrouper. Here, we find the leafCombineDegree of the cominbing tree and the
    // required number of buffers maximizing the parallelism.
    final Pair<Integer, Integer> degreeAndNumBuffers = findLeafCombineDegreeAndNumBuffers(
        combineBuffer,
        minimumRequiredBufferCapacity,
        concurrencyHint,
        sortedIterators.size()
    );

    final int leafCombineDegree = degreeAndNumBuffers.lhs;
    final int numBuffers = degreeAndNumBuffers.rhs;
    final int sliceSize = combineBuffer.capacity() / numBuffers;

    final Supplier<ByteBuffer> bufferSupplier = createCombineBufferSupplier(combineBuffer, numBuffers, sliceSize);

    final Pair<List<CloseableIterator<Entry<KeyType>>>, List<Future>> combineIteratorAndFutures = buildCombineTree(
        sortedIterators,
        bufferSupplier,
        combiningFactories,
        leafCombineDegree,
        mergedDictionary
    );

    final CloseableIterator<Entry<KeyType>> combineIterator = Iterables.getOnlyElement(combineIteratorAndFutures.lhs);
    final List<Future> combineFutures = combineIteratorAndFutures.rhs;

    final Closer closer = Closer.create();
    closer.register(combineBufferHolder);
    closer.register(() -> checkCombineFutures(combineFutures));

    return CloseableIterators.wrap(combineIterator, closer);
  }

  private static void checkCombineFutures(List<Future> combineFutures)
  {
    for (Future future : combineFutures) {
      try {
        if (!future.isDone()) {
          // Cancel futures if close() for the iterator is called early due to some reason (e.g., test failure)
          future.cancel(true);
        } else {
          future.get();
        }
      }
      catch (InterruptedException | CancellationException e) {
        throw new QueryInterruptedException(e);
      }
      catch (ExecutionException e) {
        throw new RuntimeException(e);
      }
    }
  }

  private static Supplier<ByteBuffer> createCombineBufferSupplier(
      ByteBuffer combineBuffer,
      int numBuffers,
      int sliceSize
  )
  {
    return new Supplier<ByteBuffer>()
    {
      private int i = 0;

      @Override
      public ByteBuffer get()
      {
        if (i < numBuffers) {
          return Groupers.getSlice(combineBuffer, sliceSize, i++);
        } else {
          throw new ISE("Requested number[%d] of buffer slices exceeds the planned one[%d]", i++, numBuffers);
        }
      }
    };
  }

  /**
   * Find a minimum size of the buffer slice and corresponding leafCombineDegree and number of slices.  Note that each
   * node in the combining tree is executed by different threads.  This method assumes that combining the leaf nodes
   * requires threads as many as possible, while combining intermediate nodes is not.  See the comment on
   * {@link #MINIMUM_LEAF_COMBINE_DEGREE} for more details.
   *
   * @param combineBuffer                 entire buffer used for combining tree
   * @param requiredMinimumBufferCapacity minimum buffer capacity for {@link StreamingMergeSortedGrouper}
   * @param numAvailableThreads           number of available threads
   * @param numLeafNodes                  number of leaf nodes of combining tree
   *
   * @return a pair of leafCombineDegree and number of buffers if found.
   */
  private Pair<Integer, Integer> findLeafCombineDegreeAndNumBuffers(
      ByteBuffer combineBuffer,
      int requiredMinimumBufferCapacity,
      int numAvailableThreads,
      int numLeafNodes
  )
  {
    for (int leafCombineDegree = MINIMUM_LEAF_COMBINE_DEGREE; leafCombineDegree <= numLeafNodes; leafCombineDegree++) {
      final int requiredBufferNum = computeRequiredBufferNum(numLeafNodes, leafCombineDegree);
      if (requiredBufferNum <= numAvailableThreads) {
        final int expectedSliceSize = combineBuffer.capacity() / requiredBufferNum;
        if (expectedSliceSize >= requiredMinimumBufferCapacity) {
          return Pair.of(leafCombineDegree, requiredBufferNum);
        }
      }
    }

    throw new ISE(
        "Cannot find a proper leaf combine degree for the combining tree. "
        + "Each node of the combining tree requires a buffer of [%d] bytes. "
        + "Try increasing druid.processing.buffer.sizeBytes for larger buffer or "
        + "druid.query.groupBy.intermediateCombineDegree for a smaller tree",
        requiredMinimumBufferCapacity
    );
  }

  /**
   * Recursively compute the number of required buffers for a combining tree in a bottom-up manner.  Since each node of
   * the combining tree represents a combining task and each combining task requires one buffer, the number of required
   * buffers is the number of nodes of the combining tree.
   *
   * @param numChildNodes number of child nodes
   * @param combineDegree combine degree for the current level
   *
   * @return minimum number of buffers required for combining tree
   *
   * @see #buildCombineTree(List, Supplier, AggregatorFactory[], int, List)
   */
  private int computeRequiredBufferNum(int numChildNodes, int combineDegree)
  {
    // numChildrenForLastNode used to determine that the last node is needed for the current level.
    // Please see buildCombineTree() for more details.
    final int numChildrenForLastNode = numChildNodes % combineDegree;
    final int numCurLevelNodes = numChildNodes / combineDegree + (numChildrenForLastNode > 1 ? 1 : 0);
    final int numChildOfParentNodes = numCurLevelNodes + (numChildrenForLastNode == 1 ? 1 : 0);

    if (numChildOfParentNodes == 1) {
      return numCurLevelNodes;
    } else {
      return numCurLevelNodes +
             computeRequiredBufferNum(numChildOfParentNodes, intermediateCombineDegree);
    }
  }

  /**
   * Recursively build a combining tree in a bottom-up manner.  Each node of the tree is a task that combines input
   * iterators asynchronously.
   *
   * @param childIterators      all iterators of the child level
   * @param bufferSupplier      combining buffer supplier
   * @param combiningFactories  array of combining aggregator factories
   * @param combineDegree       combining degree for the current level
   * @param dictionary          merged dictionary
   *
   * @return a pair of a list of iterators of the current level in the combining tree and a list of futures of all
   * executed combining tasks
   */
  private Pair<List<CloseableIterator<Entry<KeyType>>>, List<Future>> buildCombineTree(
      List<? extends CloseableIterator<Entry<KeyType>>> childIterators,
      Supplier<ByteBuffer> bufferSupplier,
      AggregatorFactory[] combiningFactories,
      int combineDegree,
      List<String> dictionary
  )
  {
    final int numChildLevelIterators = childIterators.size();
    final List<CloseableIterator<Entry<KeyType>>> childIteratorsOfNextLevel = new ArrayList<>();
    final List<Future> combineFutures = new ArrayList<>();

    // The below algorithm creates the combining nodes of the current level. It first checks that the number of children
    // to be combined together is 1. If it is, the intermediate combining node for that child is not needed. Instead, it
    // can be directly connected to a node of the parent level. Here is an example of generated tree when
    // numLeafNodes = 6 and leafCombineDegree = intermediateCombineDegree = 2. See the description of
    // MINIMUM_LEAF_COMBINE_DEGREE for more details about leafCombineDegree and intermediateCombineDegree.
    //
    //      o
    //     / \
    //    o   \
    //   / \   \
    //  o   o   o
    // / \ / \ / \
    // o o o o o o
    //
    // We can expect that the aggregates can be combined as early as possible because the tree is built in a bottom-up
    // manner.

    for (int i = 0; i < numChildLevelIterators; i += combineDegree) {
      if (i < numChildLevelIterators - 1) {
        final List<? extends CloseableIterator<Entry<KeyType>>> subIterators = childIterators.subList(
            i,
            Math.min(i + combineDegree, numChildLevelIterators)
        );
        final Pair<CloseableIterator<Entry<KeyType>>, Future> iteratorAndFuture = runCombiner(
            subIterators,
            bufferSupplier.get(),
            combiningFactories,
            dictionary
        );

        childIteratorsOfNextLevel.add(iteratorAndFuture.lhs);
        combineFutures.add(iteratorAndFuture.rhs);
      } else {
        // If there remains one child, it can be directly connected to a node of the parent level.
        childIteratorsOfNextLevel.add(childIterators.get(i));
      }
    }

    if (childIteratorsOfNextLevel.size() == 1) {
      // This is the root
      return Pair.of(childIteratorsOfNextLevel, combineFutures);
    } else {
      // Build the parent level iterators
      final Pair<List<CloseableIterator<Entry<KeyType>>>, List<Future>> parentIteratorsAndFutures =
          buildCombineTree(
              childIteratorsOfNextLevel,
              bufferSupplier,
              combiningFactories,
              intermediateCombineDegree,
              dictionary
          );
      combineFutures.addAll(parentIteratorsAndFutures.rhs);
      return Pair.of(parentIteratorsAndFutures.lhs, combineFutures);
    }
  }

  private Pair<CloseableIterator<Entry<KeyType>>, Future> runCombiner(
      List<? extends CloseableIterator<Entry<KeyType>>> iterators,
      ByteBuffer combineBuffer,
      AggregatorFactory[] combiningFactories,
      List<String> dictionary
  )
  {
    final SettableColumnSelectorFactory settableColumnSelectorFactory =
        new SettableColumnSelectorFactory(combiningFactories);
    final StreamingMergeSortedGrouper<KeyType> grouper = new StreamingMergeSortedGrouper<>(
        Suppliers.ofInstance(combineBuffer),
        combineKeySerdeFactory.factorizeWithDictionary(dictionary),
        settableColumnSelectorFactory,
        combiningFactories,
        queryTimeoutAt
    );
    grouper.init(); // init() must be called before iterator(), so cannot be called inside the below callable.

    final ListenableFuture future = executor.submit(
        new AbstractPrioritizedCallable<Void>(priority)
        {
          @Override
          public Void call() throws Exception
          {
            try (
                CloseableIterator<Entry<KeyType>> mergedIterator = CloseableIterators.mergeSorted(
                    iterators,
                    keyObjComparator
                )
            ) {
              while (mergedIterator.hasNext()) {
                final Entry<KeyType> next = mergedIterator.next();

                settableColumnSelectorFactory.set(next.values);
                grouper.aggregate(next.key); // grouper always returns ok or throws an exception
                settableColumnSelectorFactory.set(null);
              }
            }
            catch (IOException e) {
              throw Throwables.propagate(e);
            }

            grouper.finish();
            return null;
          }
        }
    );

    return new Pair<>(grouper.iterator(), future);
  }

  private static class SettableColumnSelectorFactory implements ColumnSelectorFactory
  {
    private static final int UNKNOWN_COLUMN_INDEX = -1;
    private final Object2IntMap<String> columnIndexMap;

    private Object[] values;

    SettableColumnSelectorFactory(AggregatorFactory[] aggregatorFactories)
    {
      columnIndexMap = new Object2IntArrayMap<>(aggregatorFactories.length);
      columnIndexMap.defaultReturnValue(UNKNOWN_COLUMN_INDEX);
      for (int i = 0; i < aggregatorFactories.length; i++) {
        columnIndexMap.put(aggregatorFactories[i].getName(), i);
      }
    }

    public void set(Object[] values)
    {
      this.values = values;
    }

    private int checkAndGetColumnIndex(String columnName)
    {
      final int columnIndex = columnIndexMap.getInt(columnName);
      Preconditions.checkState(
          columnIndex != UNKNOWN_COLUMN_INDEX,
          "Cannot find a proper column index for column[%s]",
          columnName
      );
      return columnIndex;
    }

    @Override
    public DimensionSelector makeDimensionSelector(DimensionSpec dimensionSpec)
    {
      throw new UnsupportedOperationException();
    }

    @Override
    public ColumnValueSelector makeColumnValueSelector(String columnName)
    {
      return new ObjectColumnSelector()
      {
        @Override
        public void inspectRuntimeShape(RuntimeShapeInspector inspector)
        {
          // do nothing
        }

        @Override
        public Class classOfObject()
        {
          return Object.class;
        }

        @Override
        public Object getObject()
        {
          return values[checkAndGetColumnIndex(columnName)];
        }
      };
    }

    @Override
    public ColumnCapabilities getColumnCapabilities(String column)
    {
      throw new UnsupportedOperationException();
    }
  }
}


text:
function centroid = polyhedronCentroid(vertices, faces) %#ok<INUSD>
%POLYHEDRONCENTROID Compute the centroid of a 3D convex polyhedron.
%
%   CENTRO = polyhedronCentroid(V, F)
%   Computes the centroid (center of mass) of the polyhedron defined by
%   vertices V and faces F.
%   The polyhedron is assumed to be convex.
%
%   Example
%     % Creates a polyhedron centered on origin, and add an arbitrary
%     % translation
%     [v, f] = createDodecahedron;
%     v2 = bsxfun(@plus, v, [3 4 5]);
%     % computes the centroid, that should equal the translation vector
%     centroid = polyhedronCentroid(v2, f)
%     centroid =
%         3.0000    4.0000    5.0000
%
%
%   See also
%   meshes3d, meshVolume, meshSurfaceArea, polyhedronMeanBreadth
%

% ------
% Author: David Legland
% e-mail: david.legland@nantes.inra.fr
% Created: 2012-04-05,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

% 2015.11.13 use delaunayTriangulation instead of delaunayn (strange bug
%       with icosahedron...)

% compute set of elementary tetrahedra
DT = delaunayTriangulation(vertices);
T = DT.ConnectivityList;

% number of tetrahedra
nT  = size(T, 1);

% initialize result
centroid = zeros(1, 3);
vt = 0;

% Compute the centroid and the volume of each tetrahedron
for i = 1:nT
    % coordinates of tetrahedron vertices
    tetra = vertices(T(i, :), :);

    % centroid is the average of vertices.
    centi = mean(tetra);

    % compute volume of tetrahedron
    vol = det(tetra(1:3,:) - tetra([4 4 4],:)) / 6;

    % add weighted centroid of current tetraedron
    centroid = centroid + centi * vol;

    % compute the sum of tetraedra volumes
    vt = vt + vol;
end

% compute by sum of tetrahedron volumes
centroid = centroid / vt;


text:
<?php

namespace Core\ErrorReporter;

use SplFileObject;

class FileUtils
{
    /**
     * @param string $filePath
     * @param int $line
     * @param int $fetchLineCount
     * @return array
     */
    public static function getLines($filePath, $line, $fetchLineCount)
    {
        $lines = [];

        $startLine = $line > 0 ? $line : 0;
        $endLine = $startLine + $fetchLineCount;

        $file = new SplFileObject($filePath);
        $file->setFlags(SplFileObject::DROP_NEW_LINE);
        $file->seek($startLine);

        for ($i = $startLine; $i < $endLine; $i++) {
            $line = $file->current();

            if ($line === false) {
                break;
            }

            $lines[$i] = $line;
            $file->next();
        }

        return $lines;
    }
}