text:
.. Copyright (c) 2009 Ars Aperta, Itaapy, Pierlis, Talend.

   Authors: Hervé Cauwelier <herve@itaapy.com>
            Luis Belmar-Letelier <luis@itaapy.com>
            David Versmisse <david.versmisse@itaapy.com>

   This file is part of Lpod (see: http://lpod-project.org).
   Lpod is free software; you can redistribute it and/or modify it under
   the terms of either:

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

   b) the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0

#################
Metadata Cookbook
#################

.. contents::
   :local:

To illustrate metadata introspection, let's open an existing document::

    >>> from urllib2 import urlopen
    >>> f = urlopen('http://ftp.lpod-project.org/example.odt')
    >>> from lpod.document import odf_get_document
    >>> document = odf_get_document(f)

Metadata are accessible through the `meta` part::

    >>> meta = document.get_meta()

You then get access to various getters and setters.

The getters return Python types and the respective setters take the same
Python type as a parameter.

Accessing properties
====================

The API has the form `get_xxx` and `set_xxx(value)`.

Example of getting the title::

    >>> meta.get_title()
    Example Document for the Cookbook
    >>> type(meta.get_title())
    <type 'unicode'>

Example of setting the title::

    >>> meta.set_title(u"First Example of a Long Series")

Notice that LpOD doesn't increment editing cycles nor statistics when saving
the document.

Properties helpers
==================

For the metadata using dates or durations, lpOD provides datatypes that
decode from and serialize back to strings.

Example for dates::

    >>> from lpod.datatype import DateTime
    >>> modification_date = DateTime.decode('2009-11-17T12:02:49')
    >>> type(modification_date)
    <type 'datetime.datetime'>
    >>> metadata.set_modification_date(modification_date)

Example for durations::

    >>> from lpod.datatype import Duration
    >>> duration = Duration.decode('PT00H03M02S')
    >>> type(duration)
    <type 'datetime.timedelta'>
    >>> meta.set_editing_duration(duration)

Of course you can use the datetime and timedelta constructors instead.

User-defined metadata
=====================

The ODF specification reserved place for free-form metadata for the user to
fill in.

They are loaded as a dict::

    >>> meta.get_user_defined_metadata()::
    {}

You are allowed to store the following Python types: str, unicode, bool, int,
float, Decimal, date, datetime, timedelta::

    >>> meta.set_user_defined_metadata(u"lpOD Version", 'v0.7-67-g24c08f4')
    >>> meta.get_user_defined_metadata()
    {u'lpOD Version': u'v0.7-67-g24c08f4'}

Strings are always decoded as unicode, numeric values are always decoded as
Decimal (as they offer the best precision).

For the whole list of metadata, consult the :doc:`lpod.meta module
<autodocs/meta>`.

Saving Metadata
===============

We can't write the document over HTTP::

  >>> document.save('/tmp/metadata.odt')


text:
package feign.example.wikipedia;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import feign.Feign;
import feign.Logger;
import feign.Param;
import feign.RequestLine;
import feign.gson.GsonDecoder;

public class WikipediaExample {

  static ResponseAdapter<Page> pagesAdapter = new ResponseAdapter<Page>() {

    @Override
    protected String query() {
      return "pages";
    }

    @Override
    protected Page build(JsonReader reader) throws IOException {
      Page page = new Page();
      while (reader.hasNext()) {
        String key = reader.nextName();
        if (key.equals("pageid")) {
          page.id = reader.nextLong();
        } else if (key.equals("title")) {
          page.title = reader.nextString();
        } else {
          reader.skipValue();
        }
      }
      return page;
    }
  };

  public static void main(String... args) throws InterruptedException {
    Gson gson = new GsonBuilder()
        .registerTypeAdapter(new TypeToken<Response<Page>>() {
        }.getType(), pagesAdapter)
        .create();

    Wikipedia wikipedia = Feign.builder()
        .decoder(new GsonDecoder(gson))
        .logger(new Logger.ErrorLogger())
        .logLevel(Logger.Level.BASIC)
        .target(Wikipedia.class, "https://en.wikipedia.org");

    System.out.println("Let's search for PTAL!");
    Iterator<Page> pages = lazySearch(wikipedia, "PTAL");
    while (pages.hasNext()) {
      System.out.println(pages.next().title);
    }
  }

  /**
   * this will lazily continue searches, making new http calls as necessary.
   *
   * @param wikipedia used to search
   * @param query     see {@link Wikipedia#search(String)}.
   */
  static Iterator<Page> lazySearch(final Wikipedia wikipedia, final String query) {
    final Response<Page> first = wikipedia.search(query);
    if (first.nextOffset == null) {
      return first.iterator();
    }
    return new Iterator<Page>() {
      Iterator<Page> current = first.iterator();
      Long nextOffset = first.nextOffset;

      @Override
      public boolean hasNext() {
        while (!current.hasNext() && nextOffset != null) {
          System.out.println("Wow.. even more results than " + nextOffset);
          Response<Page> nextPage = wikipedia.resumeSearch(query, nextOffset);
          current = nextPage.iterator();
          nextOffset = nextPage.nextOffset;
        }
        return current.hasNext();
      }

      @Override
      public Page next() {
        return current.next();
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }

  public static interface Wikipedia {

    @RequestLine("GET /w/api.php?action=query&continue=&generator=search&prop=info&format=json&gsrsearch={search}")
    Response<Page> search(@Param("search") String search);

    @RequestLine("GET /w/api.php?action=query&continue=&generator=search&prop=info&format=json&gsrsearch={search}&gsroffset={offset}")
    Response<Page> resumeSearch(@Param("search") String search, @Param("offset") long offset);
  }

  static class Page {

    long id;
    String title;
  }

  public static class Response<X> extends ArrayList<X> {

    /**
     * when present, the position to resume the list.
     */
    Long nextOffset;
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;

namespace Microsoft.CodeAnalysis.Wrapping.ChainedExpression
{
    ///
    /// Finds and wraps 'chained' expressions.  For the purpose of this feature, a chained
    /// expression is built out of 'chunks' where each chunk is of the form
    ///
    ///
    ///     . name (arglist) remainder
    ///
    ///
    /// So, if there are two or more of these like:
    ///
    ///
    ///     . name1 (arglist1) remainder1 . name2 (arglist2) remainder2
    ///
    ///
    /// Then this will be wrapped such that the dots align like so:
    ///
    ///
    ///     . name1 (arglist1) remainder1
    ///     . name2 (arglist2) remainder2
    ///
    ///
    /// Note: for the sake of simplicity, (arglist) is used both for the argument list of
    /// an InvocationExpression and an ElementAccessExpression.
    ///
    /// 'remainder' is all the postfix expression that can follow <c>. name (arglist)</c>.  i.e.
    /// member-access expressions, conditional-access expressions, etc.  Effectively, anything
    /// the language allows at this point as long as it doesn't start another 'chunk' itself.
    ///
    /// This approach gives an intuitive wrapping algorithm that matches the common way
    /// many wrap dotted invocations, while also effectively not limiting the wrapper to
    /// only simple forms like <c>.a(...).b(...).c(...)</c>.
    ///
    internal abstract partial class AbstractChainedExpressionWrapper<
        TNameSyntax,
        TBaseArgumentListSyntax> : AbstractSyntaxWrapper
        where TNameSyntax : SyntaxNode
        where TBaseArgumentListSyntax : SyntaxNode
    {
        private readonly ISyntaxFacts _syntaxFacts;
        private readonly int _dotToken;
        private readonly int _questionToken;

        protected AbstractChainedExpressionWrapper(
            Indentation.IIndentationService indentationService,
            ISyntaxFacts syntaxFacts) : base(indentationService)
        {
            _syntaxFacts = syntaxFacts;
            _dotToken = syntaxFacts.SyntaxKinds.DotToken;
            _questionToken = syntaxFacts.SyntaxKinds.QuestionToken;
        }

        ///
        /// Gets the language specific trivia that should be inserted before an operator if the
        /// user wants to wrap the operator to the next line.  For C# this is a simple newline-trivia.
        /// For VB, this will be a line-continuation char (<c>_</c>), followed by a newline.
        ///
        protected abstract SyntaxTriviaList GetNewLineBeforeOperatorTrivia(SyntaxTriviaList newLine);

        public sealed override async Task<ICodeActionComputer> TryCreateComputerAsync(
            Document document, int position, SyntaxNode node, CancellationToken cancellationToken)
        {
            // We have to be on a chain part.  If not, there's nothing to do here at all.
            if (!IsDecomposableChainPart(node))
            {
                return null;
            }

            // Has to be the topmost chain part.  If we're not on the topmost, then just
            // bail out here.  Our caller will continue walking upwards until it hits the
            // topmost node.
            if (IsDecomposableChainPart(node.Parent))
            {
                return null;
            }

            // We're at the top of something that looks like it could be part of a chained
            // expression.  Break it into the individual chunks.  We need to have at least
            // two chunks or this to be worth wrapping.
            //
            // i.e. if we only have <c>this.Goo(...)</c> there's nothing to wrap.  However, we can
            // wrap when we have <c>this.Goo(...).Bar(...)</c>.
            var chunks = GetChainChunks(node);
            if (chunks.Length <= 1)
            {
                return null;
            }

            // If any of these chunk parts are unformattable, then we don't want to offer anything
            // here as we may make formatting worse for this construct.
            foreach (var chunk in chunks)
            {
                var unformattable = await ContainsUnformattableContentAsync(
                    document, chunk, cancellationToken).ConfigureAwait(false);
                if (unformattable)
                {
                    return null;
                }
            }

            // Looks good.  Create the action computer which will actually determine
            // the set of wrapping options to provide.
            var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            return new CallExpressionCodeActionComputer(
                this, document, sourceText, options, chunks, cancellationToken);
        }

        private ImmutableArray<ImmutableArray<SyntaxNodeOrToken>> GetChainChunks(SyntaxNode node)
        {
            // First, just take the topmost chain node and break into the individual
            // nodes and tokens we want to treat as individual elements.  i.e. an
            // element that would be kept together.  For example, the arg-list of an
            // invocation is an element we do not want to ever break-up/wrap.
            using var _1 = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(out var pieces);
            Decompose(node, pieces);

            // Now that we have the pieces, find 'chunks' similar to the form:
            //
            //      . Name (...) Remainder...
            //
            // These will be the chunks that are wrapped and aligned on that dot.
            //
            // Here 'remainder' is everything up to the next <c>. Name (...)</c> chunk.

            using var _2 = ArrayBuilder<ImmutableArray<SyntaxNodeOrToken>>.GetInstance(out var chunks);
            BreakPiecesIntoChunks(pieces, chunks);
            return chunks.ToImmutable();
        }

        private void BreakPiecesIntoChunks(
            ArrayBuilder<SyntaxNodeOrToken> pieces,
            ArrayBuilder<ImmutableArray<SyntaxNodeOrToken>> chunks)
        {
            // Have to look for the first chunk after the first piece.  i.e. if the pieces
            // starts with <c>.Foo().Bar().Baz()</c> then the chunks would be <c>.Bar()</c>
            // and <c>.Baz()</c>.
            //
            // However, if we had <c>this.Foo().Bar().Baz()</c> then the chunks would be
            // <c>.Foo()</c> <c>.Bar()</c> and <c>.Baz()</c>.
            //
            // Note: the only way to get the <c>.Foo().Bar().Baz()</c> case today is in VB in
            // a 'with' statement.  if we have that, we don't want to wrap it into:
            //
            //
            //  with ...
            //      .Foo()
            //      .Bar()
            //      .Baz()
            //
            //
            // Instead, we want to create
            //
            //
            //  with ...
            //      .Foo().Bar()
            //            .Baz()
            //
            var currentChunkStart = FindNextChunkStart(pieces, firstChunk: true, index: 1);
            if (currentChunkStart < 0)
            {
                return;
            }

            while (true)
            {
                // Look for the next chunk starting after the current chunk we're on.
                var nextChunkStart = FindNextChunkStart(pieces, firstChunk: false, index: currentChunkStart + 1);
                if (nextChunkStart < 0)
                {
                    // No next chunk after the current one.  The current chunk just
                    // extends to the end of the pieces.
                    chunks.Add(GetSubRange(pieces, currentChunkStart, end: pieces.Count));
                    return;
                }

                // Had a chunk after this one.  Record the current chunk, move to the start
                // of the next one, and then keep going.
                chunks.Add(GetSubRange(pieces, currentChunkStart, end: nextChunkStart));
                currentChunkStart = nextChunkStart;
            }
        }

        ///
        /// Looks for the next sequence of <c>. Name (ArgList)</c>.  Note, except for the first
        /// chunk, this cannot be of the form <c>? . Name (ArgList)</c> as we do not want to
        /// wrap before a dot in a <c>?.</c> form.  This doesn't matter for the first chunk as
        /// we won't be wrapping that one.
        ///
        private int FindNextChunkStart(
            ArrayBuilder<SyntaxNodeOrToken> pieces, bool firstChunk, int index)
        {
            for (var i = index; i < pieces.Count; i++)
            {
                if (IsToken(_dotToken, pieces, i) &&
                    IsNode<TNameSyntax>(pieces, i + 1) &&
                    IsNode<TBaseArgumentListSyntax>(pieces, i + 2))
                {
                    if (firstChunk ||
                        !IsToken(_questionToken, pieces, i - 1))
                    {
                        return i;
                    }
                }
            }

            // Couldn't find the start of another chunk.
            return -1;
        }

        private static bool IsNode<TNode>(ArrayBuilder<SyntaxNodeOrToken> pieces, int index)
            => index < pieces.Count &&
               pieces[index] is var piece &&
               piece.IsNode &&
               piece.AsNode() is TNode;

        private static bool IsToken(int tokenKind, ArrayBuilder<SyntaxNodeOrToken> pieces, int index)
            => index < pieces.Count &&
               pieces[index] is var piece &&
               piece.IsToken &&
               piece.AsToken().RawKind == tokenKind;

        private static ImmutableArray<SyntaxNodeOrToken> GetSubRange(
            ArrayBuilder<SyntaxNodeOrToken> pieces, int start, int end)
        {
            using var resultDisposer = ArrayBuilder<SyntaxNodeOrToken>.GetInstance(end - start, out var result);
            for (var i = start; i < end; i++)
            {
                result.Add(pieces[i]);
            }

            return result.ToImmutable();
        }

        private bool IsDecomposableChainPart(SyntaxNode node)
        {
            // This is the effective set of language constructs that can 'chain'
            // off of a call <c>.M(...)</c>.  They are:
            //
            // 1. <c>.Name</c> or <c>->Name</c>.        i.e. <c>.M(...).Name</c>
            // 2. <c>(...)</c>.                         i.e. <c>.M(...)(...)</c>
            // 3. <c>[...]</c>.                         i.e. <c>.M(...)[...]</c>
            // 4. <c>++</c>, </c>--</c>, </c>!</c>.     i.e. <c>.M(...)++</c>
            // 5. <c>?</c>.                             i.e. <c>.M(...)?. ...</c> or <c>.M(...)?[...]</c>
            //      '5' handles both the ConditionalAccess and MemberBinding cases below.

            if (node != null)
            {
                return _syntaxFacts.IsAnyMemberAccessExpression(node)
                       || _syntaxFacts.IsInvocationExpression(node)
                       || _syntaxFacts.IsElementAccessExpression(node)
                       || _syntaxFacts.IsPostfixUnaryExpression(node)
                       || _syntaxFacts.IsConditionalAccessExpression(node)
                       || _syntaxFacts.IsMemberBindingExpression(node);
            }

            return false;
        }

        ///
        /// Recursively walks down <paramref name="node"/> decomposing it into the individual
        /// tokens and nodes we want to look for chunks in.
        ///
        private void Decompose(SyntaxNode node, ArrayBuilder<SyntaxNodeOrToken> pieces)
        {
            // Ignore null nodes, they are never relevant when building up the sequence of
            // pieces in this chained expression.
            if (node is null)
            {
                return;
            }

            // We've hit some node that can't be decomposed further (like an argument list,
            // or name node).  Just add directly to the pieces list.
            if (!IsDecomposableChainPart(node))
            {
                pieces.Add(node);
                return;
            }

            // For everything else that is a chain part, just decompose into its constituent
            // parts and add to the pieces array.
            foreach (var child in node.ChildNodesAndTokens())
            {
                if (child.IsNode)
                {
                    Decompose(child.AsNode(), pieces);
                }
                else
                {
                    pieces.Add(child.AsToken());
                }
            }
        }
    }
}


text:
<?php

namespace App\Policies;

use App\Models\Recommendation;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Auth;

class RecommendationPolicy
{
    use HandlesAuthorization;

    public function before($user, $ability)
    {
        return $user->isAdmin();
    }

    /**
     * Determine whether the user can view the recommendation.
     *
     * @param \App\Models\User           $user
     * @param \App\Models\Recommendation $recommendation
     *
     * @return mixed
     */
    public function view(User $user, Recommendation $recommendation)
    {
        //
    }

    /**
     * Determine whether the user can create recommendations.
     *
     * @param \App\Models\User $user
     *
     * @return mixed
     */
    public function create(User $user)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can update the recommendation.
     *
     * @param \App\Models\User           $user
     * @param \App\Models\Recommendation $recommendation
     *
     * @return mixed
     */
    public function update(User $user, Recommendation $recommendation)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can delete the recommendation.
     *
     * @param \App\Models\User           $user
     * @param \App\Models\Recommendation $recommendation
     *
     * @return mixed
     */
    public function delete(User $user, Recommendation $recommendation)
    {
        //
    }
}


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import tHelper from "ember-i18n/helper";

moduleForComponent('global-search', 'Integration | Component | global search', {
  integration: true,
  beforeEach: function() {
    this.container.lookup('service:i18n').set('locale', 'en');
    this.registry.register('helper:t', tHelper);
  }
});

test('it renders', function(assert) {
  assert.expect(1);

  this.render(hbs`{{global-search}}`);

  assert.equal(this.$().text().trim(), '');
});


text:
require 'net/http'

# Tinifies a URL. That is, take a long URL and makes it shorter using an API
# for a service like TinyURL.
class Tinifier
  # TODO Refine this regular expression, or find one that someone smarter has already come up with.
  @@url_matcher = /(https?)[\w\.\/\+\@\#\$\%\&\=\?\|\:\-\~\[\]]+[\w\/\+\@\#\$\%\&\=\?\|\:\-\~\[\]]/

  @@apis = {
      :tinyurl => "http://tinyurl.com/api-create.php?url=%s",
      :snipurl => "http://snipr.com/site/snip?r=simple&link=%s",
      :is_gd   => "http://is.gd/api.php?longurl=%s",
      :bitly   => "http://api.bit.ly/shorten?version=2.0.1&longUrl=%s&login=%s&apiKey=%s&format=text"
    }

  @@default_api = :tinyurl

  cattr_accessor :url_matcher, :apis, :default_api, :api_user, :api_key

  def initialize(api=Tinifier.default_api)
    @api = api
  end

  # Tinifies a single URL using the specified API. Returns the short URL,
  # or the original URL if the API call fails.
  def tinify_url(long_url, api=nil, &block)
    tinify_url!(long_url, api, &block) rescue long_url
  end

  # Tinifies a single URL, raising an error if the URL could not be
  # tinified.
  def tinify_url!(long_url, api=nil, &block)
    api ||= @api

    if block_given?
      block.call(long_url)
    else
      api_template = Tinifier.apis[api]
      raise "Unknown API specified: #{api}" if api_template.nil?

      uri = URI.parse(api_template % [long_url, self.class.api_user, self.class.api_key])
      response = Net::HTTP.get_response(uri)

      if response.class == Net::HTTPOK
        short_url = response.body
        logger.debug "Tinified #{long_url} => #{short_url}" if logger
        return short_url
      else
        raise "Failed to tinify #{long_url} via #{api}"
      end
    end
  end

  # Turns all urls found in +text+ string into tinified urls. Calls out
  # to tinyurl API to replace the url. If a block is given, each url is
  # yielded and the result replaces the url.
  #
  # tinify_urls('Visit http://www.mylongurl.com for more details.')
  # tinify_urls('Visit http://www.mylongurl.com for more details.') { |url| MyUrlTinifier.tinify(url) }
  def tinify_urls(text, api=nil, &block)
    text.gsub(Tinifier.url_matcher) do |url|
      tinify_url(url, api, &block)
    end
  end

  def tinify_urls!(text, api=nil, &block)
    text.gsub(Tinifier.url_matcher) do |url|
      tinify_url!(url, api, &block)
    end
  end

  protected

    def logger
      RAILS_DEFAULT_LOGGER if defined?(RAILS_DEFAULT_LOGGER)
    end

end


text:
dm.ImageButton = dm.Button.clone().newSlots({
	type: "dm.ImageButton",
	imageUrl: null,
	imageView: null
}).setSlots({
	init: function()
	{
		dm.Button.init.call(this);

		this.setWidth(3);
		this.setHeight(3);

		var iv = dm.ImageView.clone();
		iv.setDelegate(this);
		iv.setDelegatePrefix("imageView");
		iv.setWidth(3);
		iv.setHeight(3);
		iv.resizeToFill();
		this.setImageView(iv);
		this.addSubview(iv);
	},

	setImageUrl: function(imageUrl)
	{
		this.imageView().setUrl(imageUrl);
	},

	imageViewLoaded: function()
	{
		this.delegatePerform("loaded");
	},

	imageViewLoadFailed: function()
	{
		this.delegatePerform("loadFailed");
	},

	sizeToFit: function()
	{
		this.setSize(this.imageView().naturalSize());
		this.imageView().setSize(this.imageView().naturalSize());
		return this;
	}
});


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.4/federation/docs/api-reference/README.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# API Reference

Federation API server supports the following group versions:

* federation/v1beta1: [operations](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/federation/v1beta1/operations.html), [model definitions](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/federation/v1beta1/definitions.html)
* v1: [operations](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/v1/operations.html), [model definitions](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/v1/definitions.html)
* extensions/v1beta1: [operations](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/extensions/v1beta1/operations.html), [model definitions](https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/federation/docs/api-reference/extensions/v1beta1/definitions.html)

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/federation/docs/api-reference/README.md?pixel)]()


text:
namespace vsmc {

/// \brief Particle::weight_set_type subtype using OpenMP
/// \ingroup SMP
template <typename BaseState>
class WeightSetOMP : public traits::WeightSetTypeTrait<BaseState>::type
{
    typedef typename traits::WeightSetTypeTrait<BaseState>::type base;

    public :

    typedef typename traits::OMPSizeTypeTrait<
        typename traits::SizeTypeTrait<base>::type>::type size_type;

    explicit WeightSetOMP (size_type N) : base(N) {}

    protected :

    void log_weight2weight ()
    {
        using std::exp;

        const size_type N = static_cast<size_type>(this->size());
        double *weight = this->weight_ptr();
        const double *log_weight = this->log_weight_ptr();
#pragma omp parallel for default(shared)
        for (size_type i = 0; i < N; ++i)
            weight[i] = exp(log_weight[i]);
    }

    void weight2log_weight ()
    {
        using std::log;

        const size_type N = static_cast<size_type>(this->size());
        const double *weight = this->weight_ptr();
        double *log_weight = this->log_weight_ptr();
#pragma omp parallel for default(shared)
        for (size_type i = 0; i < N; ++i)
            log_weight[i] = log(weight[i]);
    }
}; // class WeightSetOMP

/// \brief Calculating normalizing constant ratio using OpenMP
/// \ingroup SMP
class NormalizingConstantOMP : public NormalizingConstant
{
    typedef traits::OMPSizeTypeTrait<std::size_t>::type size_type;

    public :

    NormalizingConstantOMP (std::size_t N) : NormalizingConstant(N) {}

    protected:

    void vd_exp (std::size_t N, double *inc_weight) const
    {
        using std::exp;

        size_type NN = static_cast<size_type>(N);
#pragma omp parallel for default(shared)
        for (size_type i = 0; i < NN; ++i)
            inc_weight[i] = exp(inc_weight[i]);
    }
}; // class NormalizingConstantOMP

/// \brief Particle::value_type subtype using OpenMP
/// \ingroup SMP
template <typename BaseState>
class StateOMP : public BaseState
{
    public :

    typedef typename traits::OMPSizeTypeTrait<
        typename traits::SizeTypeTrait<BaseState>::type>::type size_type;

    explicit StateOMP (size_type N) : BaseState(N) {}

    size_type size () const {return static_cast<size_type>(BaseState::size());}

    template <typename IntType>
    void copy (size_type N, const IntType *copy_from)
    {
        VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(OMP);

#pragma omp parallel for default(shared)
        for (size_type to = 0; to < N; ++to)
            this->copy_particle(copy_from[to], to);
    }
}; // class StateOMP

/// \brief Sampler<T>::init_type subtype using OpenMP
/// \ingroup SMP
template <typename T, typename Derived>
class InitializeOMP : public InitializeBase<T, Derived>
{
    public :

    std::size_t operator() (Particle<T> &particle, void *param)
    {
        typedef typename traits::OMPSizeTypeTrait<
            typename Particle<T>::size_type>::type size_type;
        const size_type N = static_cast<size_type>(particle.size());
        this->initialize_param(particle, param);
        this->pre_processor(particle);
        std::size_t accept = 0;
#pragma omp parallel for reduction(+ : accept) default(shared)
        for (size_type i = 0; i < N; ++i)
            accept += this->initialize_state(SingleParticle<T>(i, &particle));
        this->post_processor(particle);

        return accept;
    }

    protected :

    VSMC_DEFINE_SMP_IMPL_COPY_BASE(OMP, Initialize)
}; // class InitializeOMP

/// \brief Sampler<T>::move_type subtype using OpenMP
/// \ingroup SMP
template <typename T, typename Derived>
class MoveOMP : public MoveBase<T, Derived>
{
    public :

    std::size_t operator() (std::size_t iter, Particle<T> &particle)
    {
        typedef typename traits::OMPSizeTypeTrait<
            typename Particle<T>::size_type>::type size_type;
        const size_type N = static_cast<size_type>(particle.size());
        this->pre_processor(iter, particle);
        std::size_t accept = 0;
#pragma omp parallel for reduction(+ : accept) default(shared)
        for (size_type i = 0; i < N; ++i)
            accept += this->move_state(iter, SingleParticle<T>(i, &particle));
        this->post_processor(iter, particle);

        return accept;
    }

    protected :

    VSMC_DEFINE_SMP_IMPL_COPY_BASE(OMP, Move)
}; // class MoveOMP

/// \brief Monitor<T>::eval_type subtype using OpenMP
/// \ingroup SMP
template <typename T, typename Derived>
class MonitorEvalOMP : public MonitorEvalBase<T, Derived>
{
    public :

    void operator() (std::size_t iter, std::size_t dim,
            const Particle<T> &particle, double *res)
    {
        typedef typename traits::OMPSizeTypeTrait<
            typename Particle<T>::size_type>::type size_type;
        const size_type N = static_cast<size_type>(particle.size());
        this->pre_processor(iter, particle);
#pragma omp parallel for default(shared)
        for (size_type i = 0; i < N; ++i)
            this->monitor_state(iter, dim,
                    ConstSingleParticle<T>(i, &particle), res + i * dim);
        this->post_processor(iter, particle);
    }

    protected :

    VSMC_DEFINE_SMP_IMPL_COPY_BASE(OMP, MonitorEval)
}; // class MonitorEvalOMP

/// \brief Path<T>::eval_type subtype using OpenMP
/// \ingroup SMP
template <typename T, typename Derived>
class PathEvalOMP : public PathEvalBase<T, Derived>
{
    public :

    double operator() (std::size_t iter, const Particle<T> &particle,
            double *res)
    {
        typedef typename traits::OMPSizeTypeTrait<
            typename Particle<T>::size_type>::type size_type;
        const size_type N = static_cast<size_type>(particle.size());
        this->pre_processor(iter, particle);
#pragma omp parallel for default(shared)
        for (size_type i = 0; i < N; ++i)
            res[i] = this->path_state(iter,
                    ConstSingleParticle<T>(i, &particle));
        this->post_processor(iter, particle);

        return this->path_grid(iter, particle);
    }

    protected :

    VSMC_DEFINE_SMP_IMPL_COPY_BASE(OMP, PathEval)
}; // class PathEvalOMP

} // namespace vsmc

#endif // VSMC_SMP_BACKEND_OMP_HPP


text:
var seneca = require('../..')()

function saveload( seneca ) {

  var product = seneca.make('product')
  product.name = 'apple'
  product.price = 100

  product.save$(function( err, product ) {
    if( err ) return console.error( err )
    console.log( 'saved: '+product )

    // product.id was generated for us
    product.load$({id:product.id},function( err, product ) {
      if( err ) return console.error( err )
      console.log( 'loaded: '+product )
    })
  })

}

saveload(seneca)

seneca.ready( function(err,seneca){
  if( err ) return console.error( 'ERROR:'+err )

  //saveload(seneca)

  var product = seneca.make('product')
  product.name = 'apple'
  product.price = 100

  seneca.act(
    { role:'entity', cmd:'save', ent:product},
    function( err, product ) {
      if( err ) return console.error( err )
      console.log( 'saved: '+product )

      seneca.act(
        { role:'entity', cmd:'load', q:{id:product.id}, qent:product},
        function( err, product ) {
          if( err ) return console.error( err )
          console.log( 'loaded: '+product )
        })
    })
})


text:
package org.apache.hadoop.crypto;

import java.io.Closeable;
import java.security.GeneralSecurityException;
import java.util.List;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.util.PerformanceAdvisory;
import org.apache.hadoop.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_KEY;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_DEFAULT;

/**
 * Crypto codec class, encapsulates encryptor/decryptor pair.
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public abstract class CryptoCodec implements Configurable, Closeable {
  public static Logger LOG = LoggerFactory.getLogger(CryptoCodec.class);

  /**
   * Get crypto codec for specified algorithm/mode/padding.
   *
   * @param conf
   *          the configuration
   * @param cipherSuite
   *          algorithm/mode/padding
   * @return CryptoCodec the codec object. Null value will be returned if no
   *         crypto codec classes with cipher suite configured.
   */
  public static CryptoCodec getInstance(Configuration conf,
      CipherSuite cipherSuite) {
    List<Class<? extends CryptoCodec>> klasses = getCodecClasses(
        conf, cipherSuite);
    if (klasses == null) {
      return null;
    }
    CryptoCodec codec = null;
    for (Class<? extends CryptoCodec> klass : klasses) {
      try {
        CryptoCodec c = ReflectionUtils.newInstance(klass, conf);
        if (c.getCipherSuite().getName().equals(cipherSuite.getName())) {
          if (codec == null) {
            PerformanceAdvisory.LOG.debug("Using crypto codec {}.",
                klass.getName());
            codec = c;
          }
        } else {
          PerformanceAdvisory.LOG.debug(
              "Crypto codec {} doesn't meet the cipher suite {}.",
              klass.getName(), cipherSuite.getName());
        }
      } catch (Exception e) {
        PerformanceAdvisory.LOG.debug("Crypto codec {} is not available.",
            klass.getName());
      }
    }

    return codec;
  }

  /**
   * Get crypto codec for algorithm/mode/padding in config value
   * hadoop.security.crypto.cipher.suite
   *
   * @param conf
   *          the configuration
   * @return CryptoCodec the codec object Null value will be returned if no
   *         crypto codec classes with cipher suite configured.
   */
  public static CryptoCodec getInstance(Configuration conf) {
    String name = conf.get(HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_KEY,
        HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_DEFAULT);
    return getInstance(conf, CipherSuite.convert(name));
  }

  private static List<Class<? extends CryptoCodec>> getCodecClasses(
      Configuration conf, CipherSuite cipherSuite) {
    List<Class<? extends CryptoCodec>> result = Lists.newArrayList();
    String configName = HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX +
        cipherSuite.getConfigSuffix();
    String codecString;
    if (configName.equals(CommonConfigurationKeysPublic
        .HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_AES_CTR_NOPADDING_KEY)) {
      codecString = conf.get(configName, CommonConfigurationKeysPublic
          .HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_AES_CTR_NOPADDING_DEFAULT);
    } else {
      codecString = conf.get(configName);
    }
    if (codecString == null) {
      PerformanceAdvisory.LOG.debug(
          "No crypto codec classes with cipher suite configured.");
      return null;
    }
    for (String c : Splitter.on(',').trimResults().omitEmptyStrings().
        split(codecString)) {
      try {
        Class<?> cls = conf.getClassByName(c);
        result.add(cls.asSubclass(CryptoCodec.class));
      } catch (ClassCastException e) {
        PerformanceAdvisory.LOG.debug("Class {} is not a CryptoCodec.", c);
      } catch (ClassNotFoundException e) {
        PerformanceAdvisory.LOG.debug("Crypto codec {} not found.", c);
      }
    }

    return result;
  }

  /**
   * @return the CipherSuite for this codec.
   */
  public abstract CipherSuite getCipherSuite();

  /**
   * Create a {@link org.apache.hadoop.crypto.Encryptor}.
   * @return Encryptor the encryptor
   */
  public abstract Encryptor createEncryptor() throws GeneralSecurityException;

  /**
   * Create a {@link org.apache.hadoop.crypto.Decryptor}.
   * @return Decryptor the decryptor
   */
  public abstract Decryptor createDecryptor() throws GeneralSecurityException;

  /**
   * This interface is only for Counter (CTR) mode. Generally the Encryptor
   * or Decryptor calculates the IV and maintain encryption context internally.
   * For example a {@link javax.crypto.Cipher} will maintain its encryption
   * context internally when we do encryption/decryption using the
   * Cipher#update interface.
   *

   * Encryption/Decryption is not always on the entire file. For example,
   * in Hadoop, a node may only decrypt a portion of a file (i.e. a split).
   * In these situations, the counter is derived from the file position.
   *

   * The IV can be calculated by combining the initial IV and the counter with
   * a lossless operation (concatenation, addition, or XOR).
   * See http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_
   * .28CTR.29
   *
   * @param initIV initial IV
   * @param counter counter for input stream position
   * @param IV the IV for input stream position
   */
  public abstract void calculateIV(byte[] initIV, long counter, byte[] IV);

  /**
   * Generate a number of secure, random bytes suitable for cryptographic use.
   * This method needs to be thread-safe.
   *
   * @param bytes byte array to populate with random data
   */
  public abstract void generateSecureRandom(byte[] bytes);
}


text:
package com.gofish.sentiment.newscrawler;

import com.gofish.sentiment.newscrawler.NewsCrawlerService;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.Vertx;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.function.Function;
import io.vertx.serviceproxy.ProxyHelper;
import io.vertx.serviceproxy.ServiceException;
import io.vertx.serviceproxy.ServiceExceptionMessageCodec;
import com.gofish.sentiment.newscrawler.NewsCrawlerService;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;

/*
  Generated Proxy code - DO NOT EDIT
  @author Roger the Robot
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class NewsCrawlerServiceVertxEBProxy implements NewsCrawlerService {

  private Vertx _vertx;
  private String _address;
  private DeliveryOptions _options;
  private boolean closed;

  public NewsCrawlerServiceVertxEBProxy(Vertx vertx, String address) {
    this(vertx, address, null);
  }

  public NewsCrawlerServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) {
    this._vertx = vertx;
    this._address = address;
    this._options = options;
    try {
      this._vertx.eventBus().registerDefaultCodec(ServiceException.class,
          new ServiceExceptionMessageCodec());
    } catch (IllegalStateException ex) {}
  }

  public void crawlQuery(String query, Handler<AsyncResult<JsonObject>> resultHandler) {
    if (closed) {
      resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
      return;
    }
    JsonObject _json = new JsonObject();
    _json.put("query", query);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "crawlQuery");
    _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
      if (res.failed()) {
        resultHandler.handle(Future.failedFuture(res.cause()));
      } else {
        resultHandler.handle(Future.succeededFuture(res.result().body()));
      }
    });
  }

  public void getTimeout(Handler<AsyncResult<Long>> timeoutHandler) {
    if (closed) {
      timeoutHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
      return;
    }
    JsonObject _json = new JsonObject();
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "getTimeout");
    _vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
      if (res.failed()) {
        timeoutHandler.handle(Future.failedFuture(res.cause()));
      } else {
        timeoutHandler.handle(Future.succeededFuture(res.result().body()));
      }
    });
  }

  public void setTimeout(Long delay) {
    if (closed) {
      throw new IllegalStateException("Proxy is closed");
    }
    JsonObject _json = new JsonObject();
    _json.put("delay", delay);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "setTimeout");
    _vertx.eventBus().send(_address, _json, _deliveryOptions);
  }

  private List<Character> convertToListChar(JsonArray arr) {
    List<Character> list = new ArrayList<>();
    for (Object obj: arr) {
      Integer jobj = (Integer)obj;
      list.add((char)(int)jobj);
    }
    return list;
  }

  private Set<Character> convertToSetChar(JsonArray arr) {
    Set<Character> set = new HashSet<>();
    for (Object obj: arr) {
      Integer jobj = (Integer)obj;
      set.add((char)(int)jobj);
    }
    return set;
  }

  private <T> Map<String, T> convertMap(Map map) {
    if (map.isEmpty()) {
      return (Map<String, T>) map;
    }

    Object elem = map.values().stream().findFirst().get();
    if (!(elem instanceof Map) && !(elem instanceof List)) {
      return (Map<String, T>) map;
    } else {
      Function<Object, T> converter;
      if (elem instanceof List) {
        converter = object -> (T) new JsonArray((List) object);
      } else {
        converter = object -> (T) new JsonObject((Map) object);
      }
      return ((Map<String, T>) map).entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getKey, converter::apply));
    }
  }
  private <T> List<T> convertList(List list) {
    if (list.isEmpty()) {
          return (List<T>) list;
        }

    Object elem = list.get(0);
    if (!(elem instanceof Map) && !(elem instanceof List)) {
      return (List<T>) list;
    } else {
      Function<Object, T> converter;
      if (elem instanceof List) {
        converter = object -> (T) new JsonArray((List) object);
      } else {
        converter = object -> (T) new JsonObject((Map) object);
      }
      return (List<T>) list.stream().map(converter).collect(Collectors.toList());
    }
  }
  private <T> Set<T> convertSet(List list) {
    return new HashSet<T>(convertList(list));
  }
}


text:
package pl.bartosz.sokolik.app;

import pl.bartosz.sokolik.persistence.AbstractDataBase;
import pl.bartosz.sokolik.persistence.DataBase;
import pl.bartosz.sokolik.utils.*;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * Class with control loop which is responsible for choosing option in main menu
 * and calling proper method.
 */
public class Control {

    private AccountInfo account;
    private AddData addData;
    private FileFilter fileFilter;
    private AbstractDataBase database;
    private Scanner input;

    /**
     * Initializes newly created Control object.
     */
    public Control() {
        database = DataBase.getInstance();
        addData = new AddData();
        account = new AccountInfo();
        fileFilter = new FileFilter();
        input = new Scanner(System.in);
    }

    /**
     * Method called after choosing ADD_INCOME option.
     * Responsible for adding Income to database.
     */
    private void addIncome() {
        database.insertIncome(addData.createBudget(input));
    }

    /**
     * Method called after choosing ADD_EXPENSE option.
     * Responsible for adding Expense to database.
     */
    private void addExpense() {
        database.insertExpense(addData.createBudget(input));
    }

    /**
     * Method called after choosing PRINT_INCOME option.
     * Responsible for printing incomes stored in database.
     */
    private void printIncome() {
        database.selectIncomes();
        account.printIncome(database);
    }

    /**
     * Method called after choosing PRINT_EXPENSE option.
     * Responsible for printing expenses stored in database.
     */
    private void printExpense() {
        database.selectExpenses();
        account.printExpense(database);
    }

    /**
     * Method called after choosing RESUME_ACCOUNT option.
     * Responsible for printing account summary.
     */
    private void resumeAccount() {
        database.selectIncomes();
        database.selectExpenses();
        account.resumeIncome(database);
        account.resumeExpense(database);
        account.countBalance(database);
    }

    /**
     * Method called after choosing FILTER_INCOME_CAT option.
     * Responsible for filtering incomes by category.
     */
    private void filterIncomeByCategory() {
        fileFilter.filterIncomeByCategory(database, input);
        database.getBudget().clear();
    }

    /**
     * Method called after choosing FILTER_EXPENSE_CAT option.
     * Responsible for filtering expenses by category.
     */
    private void filterExpenseByCategory() {
        fileFilter.filterExpenseByCategory(database, input);
        database.getBudget().clear();
    }

    /**
     * Method called after choosing FILTER_INCOME_AMO option.
     * Responsible for filtering incomes by amount.
     */
    private void filterIncomeByAmount() {
        fileFilter.filterIncomeByAmount(database, input);
        database.getBudget().clear();
    }

    /**
     * Method called after choosing FILTER_EXPENSE_AMO option.
     * Responsible for filtering expenses by amount.
     */
    private void filterExpenseByAmount() {
        fileFilter.filterExpenseByAmount(database, input);
        database.getBudget().clear();
    }

    /**
     * Method called after choosing FILTER_INCOME_DAT option.
     * Responsible for filtering incomes by date.
     */
    private void filterIncomeByDate() {
        fileFilter.filterIncomeByDate(database, input);
        database.getBudget().clear();
    }

    /**
     * Method called after choosing FILTER_EXPENSE_DAT option.
     * Responsible for filtering expenses by date.
     */
    private void filterExpenseByDate() {
        fileFilter.filterExpenseByDate(database, input);
        database.getBudget().clear();
    }

    /**
     * Helper method responsible for printing main menu options
     */
    private void printOptions() {
        System.out.println("Wybierz opcję:");
        for (Options opt : Options.values()) {
            System.out.println(opt);
        }
    }

    /**
     * Main control loop. Option is chosen with Scanner class. Then proper method in switch-case is called
     */
    public void ControlLoop() {
        Options option = null;
        printOptions();
        while (option != Options.EXIT) {
            try {
                option = Options.createOption(addData.getOption(input));
                switch (option) {
                    case ADD_INCOME:
                        addIncome();
                        break;
                    case ADD_EXPENSE:
                        addExpense();
                        break;
                    case PRINT_INCOME:
                        printIncome();
                        break;
                    case PRINT_EXPENSE:
                        printExpense();
                        break;
                    case RESUME_ACCOUNT:
                        resumeAccount();
                        break;
                    case FILTER_INCOME_CAT:
                        filterIncomeByCategory();
                        break;
                    case FILTER_INCOME_AMO:
                        filterIncomeByAmount();
                        break;
                    case FILTER_INCOME_DAT:
                        filterIncomeByDate();
                        break;
                    case FILTER_EXPENSE_CAT:
                        filterExpenseByCategory();
                        break;
                    case FILTER_EXPENSE_AMO:
                        filterExpenseByAmount();
                        break;
                    case FILTER_EXPENSE_DAT:
                        filterExpenseByDate();
                        break;
                    case EXIT:
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                System.err.println("Nie ma takiej opcji. Wybierz ponownie.");
            } catch (InputMismatchException e){
                System.err.println("Nie ma takiej opcji. Wybierz ponownie.");
                input.nextLine();
            } finally {
                printOptions();
            }
        }
        input.close();
    }
}


text:
package org.locationtech.geowave.core.cli.operations;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.geowave.core.cli.annotations.GeowaveOperation;
import org.locationtech.geowave.core.cli.api.Command;
import org.locationtech.geowave.core.cli.api.DefaultOperation;
import org.locationtech.geowave.core.cli.api.Operation;
import org.locationtech.geowave.core.cli.api.OperationParams;
import org.locationtech.geowave.core.cli.parser.CommandLineOperationParams;
import org.locationtech.geowave.core.cli.prefix.JCommanderPrefixTranslator;
import org.locationtech.geowave.core.cli.prefix.JCommanderTranslationMap;
import org.locationtech.geowave.core.cli.spi.OperationEntry;
import org.locationtech.geowave.core.cli.spi.OperationRegistry;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameters;

@GeowaveOperation(name = "help", parentOperation = GeowaveTopLevelSection.class)
@Parameters(commandDescription = "Get descriptions of arguments for " + "any GeoWave command")
public class HelpCommand extends DefaultOperation implements Command {

  @Override
  public boolean prepare(final OperationParams inputParams) {
    super.prepare(inputParams);

    final CommandLineOperationParams params = (CommandLineOperationParams) inputParams;
    params.setValidate(false);
    params.setAllowUnknown(true);
    // Prepared successfully.
    return true;
  }

  @Override
  public void execute(final OperationParams inputParams) {
    final CommandLineOperationParams params = (CommandLineOperationParams) inputParams;

    final List<String> nameArray = new ArrayList<>();
    final OperationRegistry registry = OperationRegistry.getInstance();

    StringBuilder builder = new StringBuilder();

    Operation lastOperation = null;
    for (final Map.Entry<String, Operation> entry : params.getOperationMap().entrySet()) {
      if (entry.getValue() == this) {
        continue;
      }
      nameArray.add(entry.getKey());
      lastOperation = entry.getValue();
    }

    if (lastOperation == null) {
      lastOperation = registry.getOperation(GeowaveTopLevelSection.class).createInstance();
    }
    if (lastOperation != null) {
      final String usage = lastOperation.usage();
      if (usage != null) {
        System.out.println(usage);
      } else {
        // This is done because if we don't, then JCommander will
        // consider the given parameters as the Default parameters.
        // It's also done so that we can parse prefix annotations
        // and special delegate processing.
        final JCommanderPrefixTranslator translator = new JCommanderPrefixTranslator();

        translator.addObject(lastOperation);
        final JCommanderTranslationMap map = translator.translate();
        map.createFacadeObjects();

        // Copy default parameters over for help display.
        map.transformToFacade();

        // Execute a prepare

        // Add processed objects
        final JCommander jc = new JCommander();
        for (final Object obj : map.getObjects()) {
          jc.addObject(obj);
        }

        final String programName = StringUtils.join(nameArray, " ");
        jc.setProgramName(programName);
        jc.usage(builder);

        // Trim excess newlines.
        final String operations = builder.toString().trim();
        builder = new StringBuilder();
        builder.append(operations);
        builder.append("\n\n");

        // Add sub-commands
        final OperationEntry lastEntry = registry.getOperation(lastOperation.getClass());
        // Cast to list so we can sort it based on operation name.
        final List<OperationEntry> children = new ArrayList<>(lastEntry.getChildren());
        Collections.sort(children, getOperationComparator());
        if (children.size() > 0) {
          builder.append("  Commands:\n");
          for (final OperationEntry childEntry : children) {

            // Get description annotation
            final Parameters p = childEntry.getOperationClass().getAnnotation(Parameters.class);

            // If not hidden, then output it.
            if ((p == null) || !p.hidden()) {
              builder.append(String.format("    %s%n", childEntry.getOperationName()));
              if (p != null) {
                final String description = p.commandDescription();
                builder.append(String.format("      %s%n", description));
              } else {
                builder.append("      <no description>\n");
              }
              builder.append("\n");
            }
          }
        }

        // Trim excess newlines.
        final String output = builder.toString().trim();

        System.out.println(output);
      }
    }
  }

  /**
   * This will sort operations based on their name. Just looks prettier on output.
   *
   * @return
   */
  private Comparator<OperationEntry> getOperationComparator() {
    return new Comparator<OperationEntry>() {
      @Override
      public int compare(final OperationEntry o1, final OperationEntry o2) {
        return o1.getOperationName().compareTo(o2.getOperationName());
      }
    };
  }
}


text:
<?php

namespace SensioLabs\Deptrac\Formatter;

use SensioLabs\AstRunner\Event\AstFileAnalyzedEvent;
use SensioLabs\AstRunner\Event\AstFileSyntaxErrorEvent;
use SensioLabs\AstRunner\Event\PostCreateAstMapEvent;
use SensioLabs\AstRunner\Event\PreCreateAstMapEvent;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class ConsoleFormatter
{
    /** @var EventDispatcherInterface */
    protected $dispatcher;

    /** @var OutputInterface */
    protected $output;

    /**
     * ConsoleFormatter constructor.
     *
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct(
        EventDispatcherInterface $dispatcher,
        OutputInterface $output
    ) {
        $this->dispatcher = $dispatcher;
        $this->output = $output;

        $dispatcher->addListener(PreCreateAstMapEvent::class, array($this, 'onPreCreateAstMapEvent'));
        $dispatcher->addListener(PostCreateAstMapEvent::class, array($this, 'onPostCreateAstMapEvent'));
        $dispatcher->addListener(AstFileAnalyzedEvent::class, array($this, 'onAstFileAnalyzedEvent'));
        $dispatcher->addListener(AstFileSyntaxErrorEvent::class, array($this, 'onAstFileSyntaxErrorEvent'));
    }

    public function onPreCreateAstMapEvent(PreCreateAstMapEvent $preCreateAstMapEvent)
    {
        $this->output->writeln(sprintf(
            'Start to create an AstMap for <info>%u</info> Files.',
            $preCreateAstMapEvent->getExpectedFileCount()
        ));
    }

    public function onPostCreateAstMapEvent(PostCreateAstMapEvent $postCreateAstMapEvent)
    {
        $this->output->writeln("\nAstMap created.");
    }

    public function onAstFileAnalyzedEvent(AstFileAnalyzedEvent $analyzedEvent)
    {
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
            $this->output->writeln(sprintf('Parsing File %s', $analyzedEvent->getFile()->getRelativePathname()));
        } else {
            $this->output->write('.');
        }
    }

    public function onAstFileSyntaxErrorEvent(AstFileSyntaxErrorEvent $astFileSyntaxErrorEvent)
    {
        $this->output->writeln(sprintf(
            "\nSyntax Error on File %s\n<error>%s</error>\n",
            $astFileSyntaxErrorEvent->getFile()->getRelativePathname(),
            $astFileSyntaxErrorEvent->getSyntaxError()
        ));
    }
}