text:
module OrganisationControllerTestHelpers
  extend ActiveSupport::Concern

  module ClassMethods
    def should_display_organisation_page_elements_for(org_type)
      test "#{org_type} sets meta description" do
        organisation = create(org_type)
        create(:about_corporate_information_page, organisation: organisation, summary: 'my org description')

        get :show, id: organisation

        assert_equal 'my org description', assigns(:meta_description)
      end

      view_test "#{org_type}:shows organisation name" do
        organisation = create(org_type,
          logo_formatted_name: "unformatted name"
        )
        get :show, id: organisation
        assert_select ".organisation h1", text: "unformatted name"
      end

      view_test "#{org_type}:shows a maximum of 6 featured editions" do
        organisation = create(org_type)
        features = []
        feature_list = organisation.load_or_create_feature_list(:en)
        7.times do |i|
          edition = create(:published_news_article, first_published_at: i.days.ago)
          features << create(:feature, document: edition.document, feature_list: feature_list, ordering: i)
        end

        get :show, id: organisation

        assert_select_object features[0] do
          assert_select "img[src$='#{features[0].image.url(:s630)}'][alt=?]", features[0].alt_text
        end
        features[1...6].each do |feature|
          assert_select_object feature do
            assert_select "img[src$='#{feature.image.url(:s300)}'][alt=?]", feature.alt_text
          end
        end
        refute_select_object features.last.document.latest_edition
      end

      view_test "#{org_type}:should not display an empty featured editions section" do
        organisation = create(org_type)
        get :show, id: organisation
        refute_select "#featured-documents article"
      end

      view_test "#{org_type}:presents the contact details of the organisation using hcard" do
        organisation = create(org_type)
        organisation.contacts.create!(
          title: "Main",
          recipient: "Ministry of Pomp",
          email: "pomp@gov.uk",
          contact_form_url: "http://pomp.gov.uk/contact",
          contact_type: ContactType::General,
          street_address: "1 Smashing Place, London", postal_code: "LO1 8DN",
          contact_numbers_attributes: [
            { label: "Helpline", number: "02079460000" },
            { label: "Fax", number: "02079460001" }
          ],
          country: create(:world_location, iso2: 'GB')
        )
        organisation.add_contact_to_home_page!(organisation.contacts.first)
        get :show, id: organisation

        assert_select ".vcard" do
          assert_select ".fn", "Ministry of Pomp"
          assert_select ".adr" do
            assert_select ".street-address", "1 Smashing Place, London"
            assert_select ".postal-code", "LO1 8DN"
          end
          assert_select ".tel", /02079460000/ do
            assert_select ".type", "Helpline"
          end
          assert_select ".email", /pomp@gov\.uk/ do
            assert_select ".type", "Email"
          end
          assert_select ".contact_form_url" do
            assert_select "a[href='http://pomp.gov.uk/contact']"
          end
        end
      end

      view_test "#{org_type}:show has atom feed autodiscovery link" do
        organisation = create(org_type)

        get :show, id: organisation

        assert_select_autodiscovery_link atom_feed_url_for(organisation)
      end

      view_test "#{org_type}:show includes a link to the atom feed and featured documents" do
        organisation = create(org_type)
        feature_list = organisation.load_or_create_feature_list(:en)
        edition = create(:published_news_article, first_published_at: 1.days.ago)
        create(:feature, document: edition.document, feature_list: feature_list, ordering: 1)
        get :show, id: organisation

        assert_select "a.feed[href=?]", atom_feed_url_for(organisation)
      end

      view_test "#{org_type}:shows 3 most recently published editions associated with organisation when featuring a doc" do
        # different edition types sort on different attributes
        editions = [create(:published_news_article, first_published_at: 1.days.ago),
                  create(:published_publication, first_published_at: 2.days.ago),
                  create(:published_consultation, first_published_at: 3.days.ago),
                  create(:published_speech, first_published_at: 4.days.ago)]

        organisation = create(org_type, editions: editions)

        feature_list = create(:feature_list, featurable: organisation, locale: :en)
        create(:feature, feature_list: feature_list, document: editions[0].document)

        get :show, id: organisation

        editions[0, 3].each do |edition|
          assert_select_prefix_object edition, :recent
        end
        refute_select_prefix_object editions[3], :recent
      end

      view_test "#{org_type}:should not show most recently published editions when there are none" do
        organisation = create(org_type, editions: [])
        get :show, id: organisation

        refute_select "h1", text: "Recently updated"
      end

      view_test "#{org_type}:should show list of links to social media accounts" do
        twitter = create(:social_media_service, name: "Twitter")
        flickr = create(:social_media_service, name: "Flickr")
        twitter_account = create(:social_media_account, social_media_service: twitter, url: "https://twitter.com/#!/bisgovuk")
        flickr_account = create(:social_media_account, social_media_service: flickr, url: "http://www.flickr.com/photos/bisgovuk")
        organisation = create(org_type, social_media_accounts: [twitter_account, flickr_account])

        get :show, id: organisation

        assert_select_object twitter_account
        assert_select_object flickr_account
      end

      view_test "#{org_type}:should not show list of links to social media accounts if there are none" do
        organisation = create(org_type, social_media_accounts: [])

        get :show, id: organisation

        refute_select ".social-media-accounts"
      end

      view_test "#{org_type}:show has a link to govdelivery if one exists and featured documents" do
        organisation = create(org_type)
        feature_list = organisation.load_or_create_feature_list(:en)
        edition = create(:published_news_article, first_published_at: 1.days.ago)
        create(:feature, document: edition.document, feature_list: feature_list, ordering: 1)

        get :show, id: organisation

        assert_select ".govdelivery[href='#{new_email_signups_path(email_signup: { feed: atom_feed_url_for(organisation) })}']"
      end

      view_test "#{org_type}:show has link to published corporate information pages" do
        organisation = create(org_type)
        corporate_information_page = create(:published_corporate_information_page, organisation: organisation, corporate_information_page_type_id: CorporateInformationPageType::TermsOfReference.id)
        draft_corporate_information_page = create(:corporate_information_page, organisation: organisation, corporate_information_page_type_id: CorporateInformationPageType::ComplaintsProcedure.id)

        get :show, id: organisation

        assert_select ".corporate-information a[href='#{organisation_corporate_information_page_path(organisation, corporate_information_page.slug)}']"
        refute_select ".corporate-information a[href='#{organisation_corporate_information_page_path(organisation, draft_corporate_information_page.slug)}']"
      end
    end
  end
end


text:
/* module to create pinterest like responsive masonry grid system for angular */
;(function (angular, window, undefined) {
    "use strict";
    //defaults for plugin
    var defaults = {
        gridWidth: 300, //minumum width of a grid, this may increase to take whole space of container
        gutterSize: 10, //spacing between two grid,
        refreshOnImgLoad: true // to make a refresh on image load inside container
    };

    var single = (function () {
        var $elm = angular.element(window);
        return function (elm) {
            $elm[0] = elm;
            return $elm;
        };
    }());

    //function to check if image is loaded
    function imageLoaded(img) {
        return img.complete && (typeof img.naturalWidth === 'undefined' || img.naturalWidth !== 0);
    }

    //function to covert domlist to array
    function domToAry(list) {
        return Array.prototype.slice.call(list);
    }

    //add required css
    angular.element(document.head).append('<style>' +
        '.ag-no-transition{' +
        '-webkit-transition: none !important;' +
        'transition: none !important; visibility:hidden; opacity:0;' +
        '}' + '</style>');

    angular.module('angularGrid', []).directive('angularGrid', ['$timeout', '$window', '$q', 'angularGridInstance',
    function ($timeout, $window, $q, angularGridInstance) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var domElm = element[0],
                        win = angular.element($window),
                        agId = attrs.angularGridId,
                        modalKey = attrs.angularGrid,
                        listElms,
                        timeoutPromise,
                        cols,
                        lastRowBottom = [], //A container to store last rows bottom values
                        colWidth;

                    //get the user input options
                    var options = {
                        gridWidth: attrs.gridWidth ? parseInt(attrs.gridWidth) : defaults.gridWidth,
                        gutterSize: attrs.gutterSize ? parseInt(attrs.gutterSize) : defaults.gutterSize,
                        refreshOnImgLoad: attrs.refreshOnImgLoad == 'false' ? false : true
                    };

                    //function to get column width and number of columns
                    function getSetColWidth() {
                        var contWidth = domElm.offsetWidth;

                        cols = Math.floor(contWidth / (options.gridWidth + options.gutterSize));

                        var remainingSpace = (contWidth % (options.gridWidth + options.gutterSize)) + options.gutterSize;

                        colWidth = options.gridWidth + Math.floor(remainingSpace / cols);

                        //set width of each list
                        listElms.css({
                            width: colWidth + 'px',
                            height: 'auto'
                        });

                        //initialize listRowBottom
                        lastRowBottom.length = 0;
                        for (var i = 0; i < cols; i++) {
                            lastRowBottom.push(0);
                        }

                        return colWidth;
                    }

                    //function to reflow grids
                    function reflowGrids() {
                        //remove transition

                        //claclulate and set width of all element
                        var colWidth = getSetColWidth(),
                            i, ln;

                        //if image actual width and actual height is defined update image size so that it dosent cause reflow on image load
                        domToAry(listElms.find('img')).forEach(function (img) {
                            var $img = angular.element(img);

                            //if image is already loaded don't do anything
                            if ($img.hasClass('img-loaded')) {
                                $img.css('height', '');
                                return;
                            }

                            var actualWidth = $img.attr('actual-width') || $img.attr('data-actual-width'),
                                actualHeight = $img.attr('actual-height') || $img.attr('data-actual-height'),
                                curWidth;

                            if (actualWidth && actualHeight) {
                                curWidth = img.width;
                                height = actualHeight * curWidth / actualWidth;
                                $img.css('height', height + 'px');
                            }
                        });

                        var listElmHeights = [];

                        //get all list items new height
                        var item, $item, clone;
                        for (i = 0, ln = listElms.length; i < ln; i++) {
                            item = listElms[i];
                            $item = single(item);

                            //create clone of item to calculate proper height
                            clone = $item.clone();
                            clone.addClass('ag-no-transition');
                            clone.css('width', colWidth + 'px');
                            $item.after(clone);

                            listElmHeights.push(clone[0].offsetHeight);
                            clone.remove();
                        }

                        //set new positions
                        for (i = 0, ln = listElms.length; i < ln; i++) {
                            item = single(listElms[i]);
                            var height = listElmHeights[i],
                                top = Math.min.apply(Math, lastRowBottom),
                                col = lastRowBottom.indexOf(top);

                            //update lastRowBottom value
                            lastRowBottom[col] = top + height + options.gutterSize;

                            //set top and left of list items
                            var left = col * (colWidth + options.gutterSize);

                            item.css({
                                top: top + 'px',
                                left: left + 'px'
                            });
                        }

                        //set the height of container
                        element.css('height', Math.max.apply(Math, lastRowBottom) + 'px');
                    }

                    //function to handle asynchronous image loading
                    function handleImage() {
                        var reflowPending = false;
                        domToAry(listElms).forEach(function (listItem) {
                            var $listItem = angular.element(listItem),
                                allImg = $listItem.find('img'),
                                loadedImgPromises = [];

                            if (!allImg.length) {
                                return;
                            }

                            //add image loading class on list item
                            $listItem.addClass('img-loading');

                            domToAry(allImg).forEach(function (img) {
                                var $img = angular.element(img);
                                if (!imageLoaded(img)) {
                                    loadedImgPromises.push($q(function (resolve, reject) {
                                        $img.addClass('img-loading');
                                        img.onload = function () {
                                            if (!reflowPending && options.refreshOnImgLoad) {
                                                reflowPending = true;
                                                $timeout(function () {
                                                    reflowGrids();
                                                    reflowPending = false;
                                                }, 100);
                                            }
                                            $img.removeClass('img-loading').addClass('img-loaded');
                                            resolve();
                                        };
                                        img.onerror = reject;
                                    }));
                                } else {
                                    $img.addClass('img-loaded');
                                }
                            });

                            if (loadedImgPromises.length) {
                                $q.all(loadedImgPromises).then(function () {
                                    $listItem.removeClass('img-loading').addClass('img-loaded');
                                }, function () {
                                    $listItem.removeClass('img-loading').addClass('img-loaded');
                                });
                            } else {
                                $listItem.removeClass('img-loading').addClass('img-loaded');
                            }
                        });

                    }

                    //function to check for ng animation
                    function ngCheckAnim(){
                        var leavingElm = domToAry(listElms).filter(function(elm){
                            return single(elm).hasClass('ng-leave');
                        });
                        return $q(function(resolve){
                            if(!leavingElm.length){
                                resolve();
                            }else{
                                single(leavingElm[0]).one('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd',function(){
                                    $timeout(function () {
                                        listElms = element.children();
                                        resolve();
                                      });
                                });
                            }
                        });
                    }

                    //watch on modal key
                    scope.$watch(modalKey, function () {
                        $timeout(function () {
                            listElms = element.children();
                            ngCheckAnim().then(function(){
                                //handle images
                                handleImage();

                                $timeout(function () {
                                    //add class to element
                                    element.addClass('angular-grid');

                                    //to handle scroll appearance
                                    reflowGrids();
                                });
                            });
                        });
                    }, true);

                    //listen window resize event and reflow grids after a timeout
                    win.on('resize', function () {
                        if (timeoutPromise) {
                            $timeout.cancel(timeoutPromise);
                        }

                        timeoutPromise = $timeout(function () {
                            reflowGrids();
                        }, 100);
                    });

                    //add instance to factory if id is assigned
                    if (agId) {
                        angularGridInstance[agId] = {
                            refresh: reflowGrids
                        };
                    }
                }
            };
}])
    //a factory to store angulargrid instances which can be injected to controllers or directive
    .factory('angularGridInstance', function () {

        var angularGridInstance = {};

        return angularGridInstance;

    });
}(angular, window));

redpajama_set_name: RedPajamaGithub


text:
// This is a comment is will not return an error
#include "nothing.h"

int main(int argc, char const *argv[]) {
  /* code */
  return 0;
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo4</title>
    <script>
        function draw(id){
            var canvas = document.getElementById(id);
            var context = canvas.getContext("2d");
            context.fillStyle = "#eeeeee";
            context.fillRect(0, 0, 500, 500);
            image = new Image();
            image.src = "1.jpg";
            image.onload = function(){
                drawImage(context, image);
            }
        }
        function drawImage(context, image){
            context.drawImage(image, 0, 0,100,100);
            context.drawImage(image, 100,100,200,200,100,100,200,200);
        }
    </script>
</head>
<body onload="draw('canvas')">
<!--
    context.drawImage(img, x, y);
    context.drawImage(img, x, y, w, h);
    context.drawImage(img, sx, sy, sw,sh, dx, dy, dw, dh);
-->
<canvas id="canvas" width="1000px" height="1000px"></canvas>
</body>
</html>


text:
//: containers/ListSortSearch.java
// Sorting and searching Lists with Collections utilities.
import java.util.*;
import static net.mindview.util.Print.*;

public class ListSortSearch {
  public static void main(String[] args) {
    List<String> list =
      new ArrayList<String>(Utilities.list);
    list.addAll(Utilities.list);
    print(list);
    Collections.shuffle(list, new Random(47));
    print("Shuffled: " + list);
    // Use a ListIterator to trim off the last elements:
    ListIterator<String> it = list.listIterator(10);
    while(it.hasNext()) {
      it.next();
      it.remove();
    }
    print("Trimmed: " + list);
    Collections.sort(list);
    print("Sorted: " + list);
    String key = list.get(7);
    int index = Collections.binarySearch(list, key);
    print("Location of " + key + " is " + index +
      ", list.get(" + index + ") = " + list.get(index));
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
    print("Case-insensitive sorted: " + list);
    key = list.get(7);
    index = Collections.binarySearch(list, key,
      String.CASE_INSENSITIVE_ORDER);
    print("Location of " + key + " is " + index +
      ", list.get(" + index + ") = " + list.get(index));
  }
} /* Output:
[one, Two, three, Four, five, six, one, one, Two, three, Four, five, six, one]
Shuffled: [Four, five, one, one, Two, six, six, three, three, five, Four, Two, one, one]
Trimmed: [Four, five, one, one, Two, six, six, three, three, five]
Sorted: [Four, Two, five, five, one, one, six, six, three, three]
Location of six is 7, list.get(7) = six
Case-insensitive sorted: [five, five, Four, one, one, six, six, three, three, Two]
Location of three is 7, list.get(7) = three
*///:~


text:
package com.epishie.rehash.action;

import com.epishie.rehash.bus.RxEventBus;

public class ActionCreator {

    private final RxEventBus mActionBus;

    public ActionCreator(RxEventBus actionBus) {
        mActionBus = actionBus;
    }

    public void createGetStoriesAction(boolean refresh, int count) {
        mActionBus.post(new GetStoriesAction(refresh, count));
    }

    public void createOpenStoryAction(int id) {
        mActionBus.post(new OpenStoryAction(id));
    }

    public void createGetCommentsAction(int storyId, boolean refresh, int count) {
        mActionBus.post(new GetCommentsAction(storyId, refresh, count));

    }
}


text: package extractor


text:
"""drop tabular tables

Revision ID: 93aab0a94bed
Revises: 601adc22db51
Create Date: 2016-03-16 10:14:07.738033

"""

# revision identifiers, used by Alembic.
revision = '93aab0a94bed'
down_revision = '601adc22db51'

import logging
from alembic import op
import sqlalchemy as sa

log = logging.getLogger(__name__)

def upgrade():
    bind = op.get_bind()
    meta = sa.MetaData()
    meta.bind = bind
    meta.reflect()
    for name, table in meta.tables.items():
        if not name.startswith('tabular_'):
            continue
        log.warn("Dropping table: %r", table)
        table.drop(bind)

def downgrade():
    pass


text: Tracks for my various logs.


text:
<?php
namespace Mantisbt\Result\Issue;

class PriorityTest extends \PHPUnit_Framework_TestCase
{
    public function testProvisionThroughObject()
    {
        $obj = new \stdClass();
        $obj->id = 1;
        $obj->name = 'test';

        $priority = new Priority($obj);
        $this->assertSame($obj->id, $priority->getId());
        $this->assertSame($obj->name, $priority->getName());
    }

    public function provider()
    {
        return [
            [null, null],
            [1, 'test'],
            [null, 'test'],
            [1, null],
        ];
    }

    /**
     * @dataProvider provider
     */
    public function testProvisionThroughKeyValue($id, $name)
    {
        $priority = new Priority($id, $name);
        $this->assertSame($id, $priority->getId());
        $this->assertSame($name, $priority->getName());
    }
}


text:
// Copyright 2021 gRPC authors.
//
// Licensed under 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef GRPC_CORE_LIB_PROMISE_ARENA_PROMISE_H
#define GRPC_CORE_LIB_PROMISE_ARENA_PROMISE_H

#include <grpc/support/port_platform.h>

#include <stdlib.h>

#include <memory>
#include <utility>

#include "absl/meta/type_traits.h"

#include "src/core/lib/gprpp/construct_destruct.h"
#include "src/core/lib/promise/context.h"
#include "src/core/lib/promise/poll.h"
#include "src/core/lib/resource_quota/arena.h"

namespace grpc_core {

namespace arena_promise_detail {

using ArgType = std::aligned_storage_t<sizeof(void*)>;
template <typename T>
T*& ArgAsPtr(ArgType* arg) {
  static_assert(sizeof(ArgType) >= sizeof(T**),
                "Must have ArgType of at least one pointer size");
  return *reinterpret_cast<T**>(arg);
}

template <typename T>
struct Vtable {
  // Poll the promise, once.
  Poll<T> (*poll_once)(ArgType* arg);
  // Destroy the underlying callable object if there is one.
  // Since we don't delete (the arena owns the memory) but we may need to call a
  // destructor, we expose this for when the ArenaPromise object is destroyed.
  void (*destroy)(ArgType* arg);
};

template <typename T>
struct VtableAndArg {
  const Vtable<T>* vtable;
  ArgType arg;
};

// Implementation of Vtable for an empty object.
// Used when an empty ArenaPromise is created, or when the ArenaPromise is moved
// from. Since in either case these objects should not be polled, we simply
// crash if it is.
template <typename T>
struct Null {
  static const Vtable<T> vtable;

  static Poll<T> PollOnce(ArgType*) {
    abort();
    GPR_UNREACHABLE_CODE(return Pending{});
  }

  static void Destroy(ArgType*) {}
};

template <typename T>
const Vtable<T> Null<T>::vtable = {PollOnce, Destroy};

// Implementation of ImplInterface for a callable object.
template <typename T, typename Callable>
struct AllocatedCallable {
  static const Vtable<T> vtable;

  static Poll<T> PollOnce(ArgType* arg) {
    return poll_cast<T>((*ArgAsPtr<Callable>(arg))());
  }

  static void Destroy(ArgType* arg) { Destruct(ArgAsPtr<Callable>(arg)); }
};

template <typename T, typename Callable>
const Vtable<T> AllocatedCallable<T, Callable>::vtable = {PollOnce, Destroy};

// Implementation of ImplInterface for a small callable object (one that fits
// within the ArgType arg)
template <typename T, typename Callable>
struct Inlined {
  static const Vtable<T> vtable;

  static Poll<T> PollOnce(ArgType* arg) {
    return poll_cast<T>((*reinterpret_cast<Callable*>(arg))());
  }

  static void Destroy(ArgType* arg) {
    Destruct(reinterpret_cast<Callable*>(arg));
  }
};

template <typename T, typename Callable>
const Vtable<T> Inlined<T, Callable>::vtable = {PollOnce, Destroy};

// If a callable object is empty we can substitute any instance of that callable
// for the one we call (for how could we tell the difference)?
// Since this corresponds to a lambda with no fields, and we expect these to be
// reasonably common, we can elide the arena allocation entirely and simply poll
// a global shared instance.
// (this comes up often when the promise only accesses context data from the
// containing activity).
template <typename T, typename Callable>
struct SharedCallable {
  static const Vtable<T> vtable;

  static Poll<T> PollOnce(ArgType* arg) {
    return (*reinterpret_cast<Callable*>(arg))();
  }
};

template <typename T, typename Callable>
const Vtable<T> SharedCallable<T, Callable>::vtable = {PollOnce,
                                                       Null<T>::Destroy};

// Redirector type: given a callable type, expose a Make() function that creates
// the appropriate underlying implementation.
template <typename T, typename Callable, typename Ignored = void>
struct ChooseImplForCallable;

template <typename T, typename Callable>
struct ChooseImplForCallable<
    T, Callable,
    absl::enable_if_t<!std::is_empty<Callable>::value &&
                      (sizeof(Callable) > sizeof(ArgType))>> {
  static void Make(Callable&& callable, VtableAndArg<T>* out) {
    out->vtable = &AllocatedCallable<T, Callable>::vtable;
    ArgAsPtr<Callable>(&out->arg) = GetContext<Arena>()->template New<Callable>(
        std::forward<Callable>(callable));
  }
};

template <typename T, typename Callable>
struct ChooseImplForCallable<
    T, Callable,
    absl::enable_if_t<!std::is_empty<Callable>::value &&
                      (sizeof(Callable) <= sizeof(ArgType))>> {
  static void Make(Callable&& callable, VtableAndArg<T>* out) {
    out->vtable = &Inlined<T, Callable>::vtable;
    Construct(reinterpret_cast<Callable*>(&out->arg),
              std::forward<Callable>(callable));
  }
};

template <typename T, typename Callable>
struct ChooseImplForCallable<
    T, Callable, absl::enable_if_t<std::is_empty<Callable>::value>> {
  static void Make(Callable&&, VtableAndArg<T>* out) {
    out->vtable = &SharedCallable<T, Callable>::vtable;
  }
};

// Wrap ChooseImplForCallable with a friend approachable syntax.
template <typename T, typename Callable>
void MakeImplForCallable(Callable&& callable, VtableAndArg<T>* out) {
  ChooseImplForCallable<T, Callable>::Make(std::forward<Callable>(callable),
                                           out);
}

}  // namespace arena_promise_detail

// A promise for which the state memory is allocated from an arena.
template <typename T>
class ArenaPromise {
 public:
  // Construct an empty, uncallable, invalid ArenaPromise.
  ArenaPromise() = default;

  // Construct an ArenaPromise that will call the given callable when polled.
  template <typename Callable,
            typename Ignored =
                absl::enable_if_t<!std::is_same<Callable, ArenaPromise>::value>>
  // NOLINTNEXTLINE(google-explicit-constructor)
  ArenaPromise(Callable&& callable) {
    arena_promise_detail::MakeImplForCallable(std::forward<Callable>(callable),
                                              &vtable_and_arg_);
  }

  // ArenaPromise is not copyable.
  ArenaPromise(const ArenaPromise&) = delete;
  ArenaPromise& operator=(const ArenaPromise&) = delete;
  // ArenaPromise is movable.
  ArenaPromise(ArenaPromise&& other) noexcept
      : vtable_and_arg_(other.vtable_and_arg_) {
    other.vtable_and_arg_.vtable = &arena_promise_detail::Null<T>::vtable;
  }
  ArenaPromise& operator=(ArenaPromise&& other) noexcept {
    vtable_and_arg_.vtable->destroy(&vtable_and_arg_.arg);
    vtable_and_arg_ = other.vtable_and_arg_;
    other.vtable_and_arg_.vtable = &arena_promise_detail::Null<T>::vtable;
    return *this;
  }

  // Destruction => call Destroy on the underlying impl object.
  ~ArenaPromise() { vtable_and_arg_.vtable->destroy(&vtable_and_arg_.arg); }

  // Expose the promise interface: a call operator that returns Poll<T>.
  Poll<T> operator()() {
    return vtable_and_arg_.vtable->poll_once(&vtable_and_arg_.arg);
  }

  bool has_value() const {
    return vtable_and_arg_.vtable != &arena_promise_detail::Null<T>::vtable;
  }

 private:
  // Underlying impl object.
  arena_promise_detail::VtableAndArg<T> vtable_and_arg_ = {
      &arena_promise_detail::Null<T>::vtable, {}};
};

}  // namespace grpc_core

#endif /* GRPC_CORE_LIB_PROMISE_ARENA_PROMISE_H */


text: The Lohit Tamil font is from the Fedora Project.


text:
using EasyZMq.Configuration;
using EasyZMq.Serialization;
using NetMQ;

namespace EasyZMq.Sockets.Subscriber
{
    public static class SubscriberSocketConfigurerExtension
    {
        public static ISubscriberSocket AsSubscriber(this EasyZMqConfigurer configurer, string topic)
        {
            var serializer = configurer.Serializer;
            var addressBinder = configurer.AddressBinder;
            var loggerFactory = configurer.LoggerFactory;
            var messageDispatcher = configurer.MessageDispatcher;

            var socket = new NetMQ.Sockets.SubscriberSocket();
            socket.Subscribe(topic);

            return new SubscriberSocket(serializer, addressBinder, loggerFactory, messageDispatcher, socket);
        }

        public static IDynamicSubscriberSocket AsDynamicSubscriber(this EasyZMqConfigurer configurer, string topic)
        {
            var serializer = new TypeUnawareJsonSerializer();
            var addressBinder = configurer.AddressBinder;
            var loggerFactory = configurer.LoggerFactory;
            var messageDispatcher = configurer.MessageDispatcher;

            var socket = new NetMQ.Sockets.SubscriberSocket();
            socket.Subscribe(topic);

            return new SubscriberSocket(serializer, addressBinder, loggerFactory, messageDispatcher, socket);
        }
    }
}


text:
import sys
import time
import getopt
import math

def get():
    """Parses the commandline parameters for:
        - termination method
        - termination value
        - population size
        - modelfile for optimization
        - migration interval
        - migration size
        - mutation probability
        - mutation eta (1.0: high spread; 4.0: low spread)
        - crossover probability
        - crossover eta (2.0: high spread; 5.0: low spread)
        - output file
        - modelfile

    :returns: a tuple (term_meth, term_val, pop, outputfile, modelfile,
            mig_int, mig_size, mut_prob, mut_eta, xover_prob, xover_eta)
    """
    usage_string = "usage: python3 <algorithm>.py --term-method\
<generations|time|makespan> -t <term_value> -p <population per core>\
--mi <migration intervall> --ms <migration size> --mp <mutation probability>\
--me <mutation eta>\ xp <crossover probability> --xe <crossover eta>\
-o <outputfile> <modelfile>"

    # read the given parameters
    try:
        options, files = getopt.getopt(
                sys.argv[1:],
                "ht:p:o:",
                ["help", "population=", "mi=", "ms=", "mp=", "output",
                 "me=", "xp=", "xe=", "term-method=", "term-value="])
    except getopt.GetoptError:
        print(usage_string)
        sys.exit(1)

    term_value = 10
    term_method = 'generations'
    pop = 100
    migr_i = 5
    migr_s = 5
    mut_pb = 0.01
    mut_eta = 1.5
    xover_pb = 1.0
    xover_eta = 5.0
    output = 'experiment'

    f_model = './JSPEval/xml/example.xml'
    for opt, arg in options:
        if opt in ("-h", "--help"):
            print(usage_string)
            sys.exit()
        elif opt in ('-t', '--term-value'):
            term_value = float(arg)
        elif opt in ('-o', '--output'):
            output = arg
        elif opt in ('--term-method'):
            term_method = arg
            if term_method not in ('generations', 'time', 'makespan'):
                print('termination method unknown using: generations')
                term_method = 'generations'
        elif opt in ('-p', '--population'):
            pop = int(arg)
        elif opt == "--mi":
            migr_i = int(arg)
        elif opt == "--ms":
            migr_s = int(arg)
        elif opt == "--mp":
            mut_pb = float(arg)
        elif opt == "--me":
            mut_eta = float(arg)
        elif opt == "--xp":
            xover_pb = float(arg)
        elif opt == "--xe":
            xover_eta = float(arg)

    # calculate the endtime
    if term_method == 'time':
        term_value = term_value * 60 + time.time()

    if len(files) > 0:
        f_model = files[0]

    if not pop % 4 == 0:
        raise ValueError('The population size has to be divisible by 4 \
for the selection to work.')

    if not migr_s <= pop:
        raise ValueError('migration size cannot exceed population.')

    if not migr_i > 0:
        raise ValueError('migration interval has to be positive.')

    print('Algorithm using:\ntermination method: {}\ntermination value: {}\
    population: {}\nmodelfile: {}'.format(
        term_method,
        term_value,
        pop,
        f_model))
    print('migration size: {}\nmigration interval: {}'
          .format(migr_s, migr_i))
    print('mutation prob: {}\nmutation eta: {}'
          .format(mut_pb, mut_eta))
    print('crossover prob: {}\ncrossover eta: {}'
          .format(xover_pb, xover_eta))

    return (term_method, term_value, pop, output, f_model, migr_i,
            migr_s, mut_pb, mut_eta, xover_pb, xover_eta)

def calculate_topology(nodes):
    """Calculates the optimal (most connections) 2D topology for a number of nodes.

    :nodes: the number of nodes to calculate the topology for
    :returns: a tuple (width, height) of the resulting topology

    """
    root = int(math.sqrt(nodes))

    for i in range(root, 1, -1):
        if nodes % i == 0:
            return (i, int(nodes/i))

    return (1, nodes)


text:
[![Code Climate](https://codeclimate.com/github/bailiff/bailiff.png)](https://codeclimate.com/github/bailiff/bailiff)
[![Build Status](https://travis-ci.org/bailiff/bailiff.png?branch=feature/code_quality_assurance)](https://travis-ci.org/bailiff/bailiff)

ROADMAP: [bailiff/bailiff/wiki/ROADMAP](https://github.com/bailiff/bailiff/wiki/ROADMAP)

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'bailiff'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install bailiff

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( http://github.com/bailiff/bailiff/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
/* The Intents module contains a list of the possible intents that might be returned by the API */

/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^ConversationResponse$" }] */
/* global Animations: true, Api: true, Panel: true */

var ConversationResponse = (function () {
  'use strict';

  return {
    init: init,
    responseHandler: responseHandler
  };

  function init() {
    setupResponseHandling();
  }

  function actionFunctions(action) {
    if(action.cmd === 'music_on') {
      Panel.playMusic(action.arg);
    } else if(action.cmd === 'wipers_on') {// turn on commands
      Animations.wipersOn('lo');
    } else if(action.cmd === 'lights_on') {
      Animations.lightsOn();
    } else if(action.cmd === 'AC_on') {
      Panel.ac('lo');
    } else if(action.cmd === 'heater_on') {
      Panel.heat('lo');
    } else if(action.cmd === 'fan_on') {
      Panel.ac('lo');
    } else if(action.cmd === 'music_off') {//turn off commands
      Panel.setWatsonPanelToDefault();
    } else if(action.cmd === 'wipers_off') {
      Animations.wipersOff();
    } else if(action.cmd === 'lights_off') {
      Animations.lightsOff();
    } else if(action.cmd === 'AC_off') {
      Panel.setWatsonPanelToDefault();
    } else if(action.cmd === 'heater_off') {
      Panel.setWatsonPanelToDefault();
    } else if(action.cmd === 'fan_off') {
      Panel.setWatsonPanelToDefault();
    } else if(action.cmd === 'music_up') {//turn up commands
      Panel.playMusic('general');
    } else if(action.cmd === 'wipers_up') {
      Animations.wipersOn('hi');
    }  else if(action.cmd === 'AC_up') {
      Panel.ac('hi');
    } else if(action.cmd === 'heater_up') {
      Panel.heat('hi');
    } else if(action.cmd === 'fan_up') {
      Panel.ac('hi');
    } else if(action.cmd === 'music_down') {//turn down commands
      Panel.playMusic('general');
    } else if(action.cmd === 'wipers_down') {
      Animations.wipersOn('lo');
    }  else if(action.cmd === 'AC_down') {
      Panel.ac('lo');
    } else if(action.cmd === 'heater_down') {
      Panel.heat('lo');
    } else if(action.cmd === 'fan_down') {
      Panel.ac('lo');
    } else if(action.cmd === 'gas') {// amenity
      Panel.mapGas();
    } else if(action.cmd === 'restaurant') {
      Panel.mapFoodCuisine();
    } else if(action.cmd === 'restroom') {
      Panel.mapRestrooms();
    }
  }

  // Create a callback when a new Watson response is received to handle Watson's response
  function setupResponseHandling() {
    var currentResponsePayloadSetter = Api.setWatsonPayload;
    Api.setWatsonPayload = function (payload) {
      currentResponsePayloadSetter.call(Api, payload);
      responseHandler(payload);
    };
  }

  // Called when a Watson response is received, manages the behavior of the app based
  // on the user intent that was determined by Watson
  function responseHandler(data) {

    let action = data.output.action;

    if (data && !data.output.error) {
      // Check if message is handled by retrieve and rank and there is no message set
      if (action && !data.output.text) {
        // TODO add EIR link
        data.output.text = ['I am not able to answer that. You can try asking the'
        + ' Information Retrieval with Discovery App'];

        Api.setWatsonPayload(data);
        return;
      }

      if (action) {
        let actionArray = getActions(action);
        if (actionArray) {
          for (let i in actionArray) {
            if (actionArray.hasOwnProperty(i)) {
              actionFunctions(actionArray[i]);
            }
          }
        }
      }
    }
  }

  function getActions(action) {
    let res = {};

    let cnt = 0;

    for (let key in action) {
      if (action.hasOwnProperty(key)) {
        res[cnt] = {
          cmd: key,
          arg: action[key]
        };
        cnt++;
      }
    }
    return res;
  }
}());


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Agric. Colon. 10:504. 1916 "<I>bonneti</I>"

#### Original name
null

### Remarks
null


text:
"use strict";

// See: http://www.cs.unm.edu/~angel/COURSERA/CODE/EXAMPLES/

var canvas;
var gl;

var maxNumTriangles = 200;
var maxNumVertices = 3 * maxNumTriangles;
var index = 0;

var t1, t2, t3, t4; // temporary variables

var cIndex = 0;

var colors = [
    vec4(0.0, 0.0, 0.0, 0.6), // unused placeholder for RANDOM
    vec4(0.0, 0.0, 0.0, 0.6), // black
    vec4(1.0, 0.0, 0.0, 0.6), // red
    vec4(1.0, 1.0, 0.0, 0.6), // yellow
    vec4(0.0, 1.0, 0.0, 0.6), // green
    vec4(0.0, 0.0, 1.0, 0.6), // blue
    vec4(1.0, 0.0, 1.0, 0.6), // magenta
    vec4(0.0, 1.0, 1.0, 0.6) // cyan
];

var vBuffer;
var cBuffer;

window.onload = function() {
    // Step 1: Get the HTML canvas and set it up as a Web GL context.
    canvas = document.getElementById("gl-canvas");
    gl = WebGLUtils.setupWebGL(canvas, {
        // alpha: false
    });
    if (!gl) {
        alert("WebGL isn't available");
    }

    gl.viewport(0, 0, canvas.width, canvas.height);
    gl.clearColor(0.9, 0.9, 0.9, 1.0); // set the background color in rgba format (each value ranges from 0.0 to 1.0)

    enableAlphaBlending();

    //  Load shaders and initialize attribute buffers
    var program = initShaders(gl, "vertex-shader", "fragment-shader");
    gl.useProgram(program);

    // vBuffer => vertex buffer?
    vBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, 4 * 2 * maxNumVertices, gl.STATIC_DRAW);

    var vPosition = gl.getAttribLocation(program, "vPosition"); // vBuffer <=> vPosition
    gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0); // 2 FLOATs
    gl.enableVertexAttribArray(vPosition);

    // cBuffer => color buffer?
    cBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, cBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, 4 * 4 * maxNumVertices, gl.STATIC_DRAW);

    var vColor = gl.getAttribLocation(program, "vColor"); // cBuffer <=> vColor
    gl.vertexAttribPointer(vColor, 4, gl.FLOAT, false, 0, 0); // 4 FLOATs
    gl.enableVertexAttribArray(vColor);

    var m = document.getElementById("menu");
    m.addEventListener("click", function() {
        cIndex = m.selectedIndex;
    });

    canvas.addEventListener("mousedown", onMouseDown);
    canvas.addEventListener("mouseup", onMouseUp);

    render();
}

function enableAlphaBlending() {
    // Enable Alpha
    // See: http://delphic.me.uk/webglalpha.html
    gl.enable(gl.BLEND);
    gl.blendEquation(gl.FUNC_ADD);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}

// Save the mouseDown location.
function onMouseDown(event) {
    var canvasX = event.clientX - canvas.offsetLeft; // jQuery would handle this more cleanly
    var canvasY = event.clientY - canvas.offsetTop;  // jQuery would handle this more cleanly
    var x1 = 2 * (canvasX / canvas.width) - 1; // [-1, +1]
    var y1 = 2 * ((canvas.height - canvasY) / canvas.height) - 1;
    t1 = vec2(x1, y1);
    console.log(t1); // it's just an array of two numbers
}

// Compute 4 vertices from our mouseDown and mouseUp locations
function onMouseUp(event) {
    gl.bindBuffer(gl.ARRAY_BUFFER, vBuffer); // Let's work on the vBuffer now!
    var canvasX = event.clientX - canvas.offsetLeft; // jQuery would handle this more cleanly
    var canvasY = event.clientY - canvas.offsetTop;  // jQuery would handle this more cleanly
    var x2 = 2 * (canvasX / canvas.width) - 1;
    var y2 = 2 * ((canvas.height - canvasY) / canvas.height) - 1;

    // t1 is the first vertex! (we saved it in onMouseDown)
    t2 = vec2(x2, y2);
    t3 = vec2(t1[0], t2[1]); // compute another vertex from the t1.x, t2.y
    t4 = vec2(t2[0], t1[1]); // compute another vertex from the t2.x, t1.y

    // flatten(v) converts the incoming vector or matrix into a Float32Array, which is used by WebGL

    gl.bufferSubData(gl.ARRAY_BUFFER, 8 * (index + 0), flatten(t1));
    gl.bufferSubData(gl.ARRAY_BUFFER, 8 * (index + 1), flatten(t3));
    gl.bufferSubData(gl.ARRAY_BUFFER, 8 * (index + 2), flatten(t2));
    gl.bufferSubData(gl.ARRAY_BUFFER, 8 * (index + 3), flatten(t4));

    // color the triangles
    gl.bindBuffer(gl.ARRAY_BUFFER, cBuffer); // Let's work on the cBuffer now!
    index += 4;

    var color;
    if (cIndex === 0) {
        color = vec4(Math.random(), Math.random(), Math.random(), 0.6);
    } else {
        color = colors[cIndex];
    }

    t1 = vec4(Math.random(), Math.random(), Math.random(), 0.6);

    gl.bufferSubData(gl.ARRAY_BUFFER, 16 * (index - 4), flatten(t1)); // top left corner
    gl.bufferSubData(gl.ARRAY_BUFFER, 16 * (index - 3), flatten(color)); // lower left corner
    gl.bufferSubData(gl.ARRAY_BUFFER, 16 * (index - 2), flatten(color)); // lower right corner
    gl.bufferSubData(gl.ARRAY_BUFFER, 16 * (index - 1), flatten(color)); // top right corner
}

//
function render() {
    // clear the buffer that is used for writing colors (i.e., the pixels)
    // clear the entire context using our background color now!
    gl.clear(gl.COLOR_BUFFER_BIT);

    for (var i = 0; i < index; i += 4) {
        gl.drawArrays(gl.TRIANGLE_FAN, i, 4);
        // gl.drawArrays(gl.TRIANGLES, i, 4);
        // gl.drawArrays(gl.LINE_LOOP, i, 4);
        // gl.drawArrays(gl.LINES, i, 4);
        // See this website for all the various drawing modes:
        // http://www.informit.com/articles/article.aspx?p=2111395&seqNum=2
    }

    requestAnimFrame(render); // call render again as soon as possible!
    // Note that the actual API is called window.requestAnimationFrame()
    // Here, the professor uses requestAnimFrame() which is a "polyfill" function
    // provided by Common/webgl-utils.js. That function will fall back to using
    // setInterval if the user is using an old browser where RAF is not available.
}


text:
package etcd

import (
	"context"
	"time"

	"openpitrix.io/openpitrix/pkg/logger"
)

type callback func() error

func (etcd *Etcd) Dlock(ctx context.Context, key string, cb callback) error {
	logger.Debug(ctx, "Create dlock with key [%s]", key)
	mutex, err := etcd.NewMutex(key)
	if err != nil {
		logger.Critical(ctx, "Dlock lock error, failed to create mutex: %+v", err)
		return err
	}
	err = mutex.Lock(ctx)
	if err != nil {
		logger.Critical(ctx, "Dlock lock error, failed to lock mutex: %+v", err)
		return err
	}
	defer mutex.Unlock(ctx)
	err = cb()
	return err
}

func (etcd *Etcd) DlockWithTimeout(key string, timeout time.Duration, cb callback) error {
	ctxWithTimeout, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	return etcd.Dlock(ctxWithTimeout, key, cb)
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 15: 336 (1982)

#### Original name
Laetisaria agaves Burds. & Gilb., 1982

### Remarks
null


text:
import networkx as nx
import graph_tool as gt

def get_prop_type(value, key=None):
    """
    Performs typing and value conversion for the graph_tool PropertyMap class.
    If a key is provided, it also ensures the key is in a format that can be
    used with the PropertyMap. Returns a tuple, (type name, value, key)
    """
    # Deal with the value
    if isinstance(value, bool):
        tname = 'bool'

    elif isinstance(value, int):
        tname = 'float'
        value = float(value)

    elif isinstance(value, float):
        tname = 'float'

    elif isinstance(value, dict):
        tname = 'object'

    else:
        tname = 'string'
        value = str(value)

    return tname, value, key

def nx2gt(nxG):
    """
    Converts a networkx graph to a graph-tool graph.
    """
    # Phase 0: Create a directed or undirected graph-tool Graph
    gtG = gt.Graph(directed=nxG.is_directed())

    # Add the Graph properties as "internal properties"
    for key, value in nxG.graph.items():
        # Convert the value and key into a type for graph-tool
        tname, value, key = get_prop_type(value, key)

        prop = gtG.new_graph_property(tname) # Create the PropertyMap
        gtG.graph_properties[key] = prop     # Set the PropertyMap
        gtG.graph_properties[key] = value    # Set the actual value

    # Phase 1: Add the vertex and edge property maps
    # Go through all nodes and edges and add seen properties
    # Add the node properties first
    nprops = set() # cache keys to only add properties once
    for node, data in nxG.nodes(data=True):

        # Go through all the properties if not seen and add them.
        for key, val in data.items():
            if key in nprops: continue # Skip properties already added

            # Convert the value and key into a type for graph-tool
            tname, _, key  = get_prop_type(val, key)

            prop = gtG.new_vertex_property(tname) # Create the PropertyMap
            gtG.vertex_properties[key] = prop     # Set the PropertyMap

            # Add the key to the already seen properties
            nprops.add(key)

    # Also add the node id: in NetworkX a node can be any hashable type, but
    # in graph-tool node are defined as indices. So we capture any strings
    # in a special PropertyMap called 'id' -- modify as needed!
    gtG.vertex_properties['id'] = gtG.new_vertex_property('string')

    # Add the edge properties second
    eprops = set() # cache keys to only add properties once
    for src, dst, data in nxG.edges(data=True):

        # Go through all the edge properties if not seen and add them.
        for key, val in data.items():
            if key in eprops: continue # Skip properties already added

            # Convert the value and key into a type for graph-tool
            tname, _, key = get_prop_type(val, key)

            prop = gtG.new_edge_property(tname) # Create the PropertyMap
            gtG.edge_properties[key] = prop     # Set the PropertyMap

            # Add the key to the already seen properties
            eprops.add(key)

    # Phase 2: Actually add all the nodes and vertices with their properties
    # Add the nodes
    vertices = {} # vertex mapping for tracking edges later
    for node, data in nxG.nodes(data=True):

        # Create the vertex and annotate for our edges later
        v = gtG.add_vertex()
        vertices[node] = v

        # Set the vertex properties, not forgetting the id property
        data['id'] = str(node)
        for key, value in data.items():
            gtG.vp[key][v] = value # vp is short for vertex_properties

    # Add the edges
    for src, dst, data in nxG.edges(data=True):

        # Look up the vertex structs from our vertices mapping and add edge.
        e = gtG.add_edge(vertices[src], vertices[dst])

        # Add the edge properties
        for key, value in data.items():
            gtG.ep[key][e] = value # ep is short for edge_properties

    # Done, finally!
    return gtG


text:
/**
 * Directions that can be used when setting sticky positioning.
 * @docs-private
 */
import {Direction} from '@angular/cdk/bidi';

export type StickyDirection = 'top' | 'bottom' | 'left' | 'right';

/**
 * List of all possible directions that can be used for sticky positioning.
 * @docs-private
 */
export const STICKY_DIRECTIONS: StickyDirection[] = ['top', 'bottom', 'left', 'right'];

/**
 * Applies and removes sticky positioning styles to the `CdkTable` rows and columns cells.
 * @docs-private
 */
export class StickyStyler {
  /**
   * @param _isNativeHtmlTable Whether the sticky logic should be based on a table
   *     that uses the native `<table>` element.
   * @param _stickCellCss The CSS class that will be applied to every row/cell that has
   *     sticky positioning applied.
   * @param direction The directionality context of the table (ltr/rtl); affects column positioning
   *     by reversing left/right positions.
   * @param _isBrowser Whether the table is currently being rendered on the server or the client.
   */
  constructor(private _isNativeHtmlTable: boolean,
              private _stickCellCss: string,
              public direction: Direction,
              private _isBrowser = true) { }

  /**
   * Clears the sticky positioning styles from the row and its cells by resetting the `position`
   * style, setting the zIndex to 0, and unsetting each provided sticky direction.
   * @param rows The list of rows that should be cleared from sticking in the provided directions
   * @param stickyDirections The directions that should no longer be set as sticky on the rows.
   */
  clearStickyPositioning(rows: HTMLElement[], stickyDirections: StickyDirection[]) {
    for (const row of rows) {
      // If the row isn't an element (e.g. if it's an `ng-container`),
      // it won't have inline styles or `children` so we skip it.
      if (row.nodeType !== row.ELEMENT_NODE) {
        continue;
      }

      this._removeStickyStyle(row, stickyDirections);

      for (let i = 0; i < row.children.length; i++) {
        const cell = row.children[i] as HTMLElement;
        this._removeStickyStyle(cell, stickyDirections);
      }
    }
  }

  /**
   * Applies sticky left and right positions to the cells of each row according to the sticky
   * states of the rendered column definitions.
   * @param rows The rows that should have its set of cells stuck according to the sticky states.
   * @param stickyStartStates A list of boolean states where each state represents whether the cell
   *     in this index position should be stuck to the start of the row.
   * @param stickyEndStates A list of boolean states where each state represents whether the cell
   *     in this index position should be stuck to the end of the row.
   */
  updateStickyColumns(
      rows: HTMLElement[], stickyStartStates: boolean[], stickyEndStates: boolean[]) {
    const hasStickyColumns =
        stickyStartStates.some(state => state) || stickyEndStates.some(state => state);
    if (!rows.length || !hasStickyColumns || !this._isBrowser) {
      return;
    }

    const firstRow = rows[0];
    const numCells = firstRow.children.length;
    const cellWidths: number[] = this._getCellWidths(firstRow);

    const startPositions = this._getStickyStartColumnPositions(cellWidths, stickyStartStates);
    const endPositions = this._getStickyEndColumnPositions(cellWidths, stickyEndStates);
    const isRtl = this.direction === 'rtl';

    for (const row of rows) {
      for (let i = 0; i < numCells; i++) {
        const cell = row.children[i] as HTMLElement;
        if (stickyStartStates[i]) {
          this._addStickyStyle(cell, isRtl ? 'right' : 'left', startPositions[i]);
        }

        if (stickyEndStates[i]) {
          this._addStickyStyle(cell, isRtl ? 'left' : 'right', endPositions[i]);
        }
      }
    }
  }

  /**
   * Applies sticky positioning to the row's cells if using the native table layout, and to the
   * row itself otherwise.
   * @param rowsToStick The list of rows that should be stuck according to their corresponding
   *     sticky state and to the provided top or bottom position.
   * @param stickyStates A list of boolean states where each state represents whether the row
   *     should be stuck in the particular top or bottom position.
   * @param position The position direction in which the row should be stuck if that row should be
   *     sticky.
   *
   */
  stickRows(rowsToStick: HTMLElement[], stickyStates: boolean[], position: 'top' | 'bottom') {
    // Since we can't measure the rows on the server, we can't stick the rows properly.
    if (!this._isBrowser) {
      return;
    }

    // If positioning the rows to the bottom, reverse their order when evaluating the sticky
    // position such that the last row stuck will be "bottom: 0px" and so on.
    const rows = position === 'bottom' ? rowsToStick.reverse() : rowsToStick;

    let stickyHeight = 0;
    for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
      if (!stickyStates[rowIndex]) {
        continue;
      }

      const row = rows[rowIndex];
      if (this._isNativeHtmlTable) {
        for (let j = 0; j < row.children.length; j++) {
          const cell = row.children[j] as HTMLElement;
          this._addStickyStyle(cell, position, stickyHeight);
        }
      } else {
        // Flex does not respect the stick positioning on the cells, needs to be applied to the row.
        // If this is applied on a native table, Safari causes the header to fly in wrong direction.
        this._addStickyStyle(row, position, stickyHeight);
      }

      if (rowIndex === rows.length - 1) {
        // prevent unnecessary reflow from getBoundingClientRect()
        return;
      }
      stickyHeight += row.getBoundingClientRect().height;
    }
  }

  /**
   * When using the native table in Safari, sticky footer cells do not stick. The only way to stick
   * footer rows is to apply sticky styling to the tfoot container. This should only be done if
   * all footer rows are sticky. If not all footer rows are sticky, remove sticky positioning from
   * the tfoot element.
   */
  updateStickyFooterContainer(tableElement: Element, stickyStates: boolean[]) {
    if (!this._isNativeHtmlTable) {
      return;
    }

    const tfoot = tableElement.querySelector('tfoot')!;
    if (stickyStates.some(state => !state)) {
      this._removeStickyStyle(tfoot, ['bottom']);
    } else {
      this._addStickyStyle(tfoot, 'bottom', 0);
    }
  }

  /**
   * Removes the sticky style on the element by removing the sticky cell CSS class, re-evaluating
   * the zIndex, removing each of the provided sticky directions, and removing the
   * sticky position if there are no more directions.
   */
  _removeStickyStyle(element: HTMLElement, stickyDirections: StickyDirection[]) {
    for (const dir of stickyDirections) {
      element.style[dir] = '';
    }
    element.style.zIndex = this._getCalculatedZIndex(element);

    // If the element no longer has any more sticky directions, remove sticky positioning and
    // the sticky CSS class.
    const hasDirection = STICKY_DIRECTIONS.some(dir => !!element.style[dir]);
    if (!hasDirection) {
      element.style.position = '';
      element.classList.remove(this._stickCellCss);
    }
  }

  /**
   * Adds the sticky styling to the element by adding the sticky style class, changing position
   * to be sticky (and -webkit-sticky), setting the appropriate zIndex, and adding a sticky
   * direction and value.
   */
  _addStickyStyle(element: HTMLElement, dir: StickyDirection, dirValue: number) {
    element.classList.add(this._stickCellCss);
    element.style[dir] = `${dirValue}px`;
    element.style.cssText += 'position: -webkit-sticky; position: sticky; ';
    element.style.zIndex = this._getCalculatedZIndex(element);
  }

  /**
   * Calculate what the z-index should be for the element, depending on what directions (top,
   * bottom, left, right) have been set. It should be true that elements with a top direction
   * should have the highest index since these are elements like a table header. If any of those
   * elements are also sticky in another direction, then they should appear above other elements
   * that are only sticky top (e.g. a sticky column on a sticky header). Bottom-sticky elements
   * (e.g. footer rows) should then be next in the ordering such that they are below the header
   * but above any non-sticky elements. Finally, left/right sticky elements (e.g. sticky columns)
   * should minimally increment so that they are above non-sticky elements but below top and bottom
   * elements.
   */
  _getCalculatedZIndex(element: HTMLElement): string {
    const zIndexIncrements = {
      top: 100,
      bottom: 10,
      left: 1,
      right: 1,
    };

    let zIndex = 0;
    for (const dir of STICKY_DIRECTIONS) {
      if (element.style[dir]) {
        zIndex += zIndexIncrements[dir];
      }
    }

    return zIndex ? `${zIndex}` : '';
  }

  /** Gets the widths for each cell in the provided row. */
  _getCellWidths(row: HTMLElement): number[] {
    const cellWidths: number[] = [];
    const firstRowCells = row.children;
    for (let i = 0; i < firstRowCells.length; i++) {
      let cell: HTMLElement = firstRowCells[i] as HTMLElement;
      cellWidths.push(cell.getBoundingClientRect().width);
    }

    return cellWidths;
  }

  /**
   * Determines the left and right positions of each sticky column cell, which will be the
   * accumulation of all sticky column cell widths to the left and right, respectively.
   * Non-sticky cells do not need to have a value set since their positions will not be applied.
   */
  _getStickyStartColumnPositions(widths: number[], stickyStates: boolean[]): number[] {
    const positions: number[] = [];
    let nextPosition = 0;

    for (let i = 0; i < widths.length; i++) {
      if (stickyStates[i]) {
        positions[i] = nextPosition;
        nextPosition += widths[i];
      }
    }

    return positions;
  }

  /**
   * Determines the left and right positions of each sticky column cell, which will be the
   * accumulation of all sticky column cell widths to the left and right, respectively.
   * Non-sticky cells do not need to have a value set since their positions will not be applied.
   */
  _getStickyEndColumnPositions(widths: number[], stickyStates: boolean[]): number[] {
    const positions: number[] = [];
    let nextPosition = 0;

    for (let i = widths.length; i > 0; i--) {
      if (stickyStates[i]) {
        positions[i] = nextPosition;
        nextPosition += widths[i];
      }
    }

    return positions;
  }
}


text:
#ifndef PBL_CPP_TRAITS_YESNO_H
#define PBL_CPP_TRAITS_YESNO_H

namespace cpp11
{
namespace detail
{
typedef char (& yes)[1];
typedef char (& no)[2];
}
}

#endif // PBL_CPP_TRAITS_YESNO_H


text:
package org.openstack.api.restful.ceilometer.v2.elements

import java.sql.Timestamp
import java.util.Date

import org.openstack.api.restful.elements.Link
/**
 * ceilometer Resource representation
 * @author Antonio Murgia
 * @version 22/10/14
 */
case class Resource(first_sample_timestamp : Option[Timestamp],
                    last_sample_timestamp : Option[Timestamp],
                    links : Seq[Link],
                    metadata : Map[String,String],
                    project_id : Option[String],
                    resource_id : String,
                    source : String,
                    user_id : Option[String]) {
  require(project_id != null)
  require(resource_id != null)
  require(resource_id.nonEmpty)
  require(source != null)
  require(source.nonEmpty)
}
/**
Type:	datetime
UTC date & time not later than the first sample known for this resource

last_sample_timestamp
Type:	datetime
UTC date & time not earlier than the last sample known for this resource

links
Type:	list(Link)
A list containing a self link and associated meter links

metadata
Type:	dict(unicode: unicode)
Arbitrary metadata associated with the resource

project_id
Type:	unicode
The ID of the owning project or tenant

resource_id
Type:	unicode
The unique identifier for the resource

source
Type:	unicode
The source where the resource come from

user_id
Type:	unicode
The ID of the user who created the resource or updated it last
  **/


text:
package com.phloc.commons.xml.dom;

import javax.annotation.Nonnull;

import com.phloc.commons.annotations.Nonempty;
import com.phloc.commons.id.IHasID;

/**
 * Represents different DOM features.<br>
 * See http://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMFeatures
 *
 * @author Philip Helger
 */
public enum EXMLDOMFeature implements IHasID <String>
{
  DOM_FEATURE_CORE ("Core"),
  DOM_FEATURE_XML ("XML"),
  DOM_FEATURE_EVENTS ("Events"),
  DOM_FEATURE_UI_EVENTS ("UIEvents"),
  DOM_FEATURE_MOUSE_EVENTS ("MouseEvents"),
  DOM_FEATURE_TEXT_EVENTS ("TextEvents"),
  DOM_FEATURE_KEYBOARD_EVENTS ("KeyboardEvents"),
  DOM_FEATURE_MUTATION_EVENTS ("MutationEvents"),
  DOM_FEATURE_MUTATION_NAME_EVENTS ("MutationNameEvents"),
  DOM_FEATURE_HTML_EVENTS ("HTMLEvents"),
  DOM_FEATURE_LS ("LS"),
  DOM_FEATURE_LS_ASYNC ("LS-Async"),
  DOM_FEATURE_VALIDATION ("Validation"),
  DOM_FEATURE_XPATH ("XPath");

  private final String m_sID;

  private EXMLDOMFeature (@Nonnull @Nonempty final String sID)
  {
    m_sID = sID;
  }

  @Nonnull
  @Nonempty
  public String getID ()
  {
    return m_sID;
  }

  @Nonnull
  @Nonempty
  public String getPlusFeature ()
  {
    return '+' + m_sID;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xsi:schemaLocation="
        http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

	<container qualifier="wildfly8.2" default="true">
		<configuration>
			<!--
			<property name="jbossHome">target/jboss-as-7.1.1.Final</property>
			<property name="javaVmArguments">-Xms1024m -Xmx1027m -XX:MaxPermSize=512m</property>
			-->

			<!-- use these uncommented javaVmArguments to allow remote debugging on 8787 from Eclipse  -->
			<!-- <property name="javaVmArguments">-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y -Xms1024m -Xmx1027m -XX:MaxPermSize=512m</property> -->
		</configuration>
	</container>

	<extension qualifier="persistence">
		<property name="defaultDataSource">java:jboss/datasources/personalapi-ds</property>
	</extension>

</arquillian>


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="YupItsZac\FreeGeoBundle\Entity\Regions" table="regions">
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="coordinatesWkt" type="text" column="coordinates_wkt" length="16777215" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="isoAlpha2" type="string" column="iso_alpha2" length="2" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="name" type="string" column="name" length="44" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="nameAlt" type="string" column="name_alt" length="129" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="typeEn" type="string" column="type_en" length="27" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="codeHasc" type="string" column="code_hasc" length="8" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="region" type="string" column="region" length="43" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="regionCod" type="string" column="region_cod" length="15" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="postal" type="string" column="postal" length="3" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="countryIsoAlpha3" type="string" column="country_iso_alpha3" length="3" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="country" type="string" column="country" length="36" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="gnId" type="integer" column="gn_id" nullable="true">
      <options>
        <option name="unsigned"/>
      </options>
    </field>
    <field name="gnName" type="string" column="gn_name" length="72" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="gnA1Code" type="string" column="gn_a1_code" length="10" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
    <field name="regionSub" type="string" column="region_sub" length="41" nullable="true">
      <options>
        <option name="fixed"/>
      </options>
    </field>
  </entity>
</doctrine-mapping>


text:
require 'bcrypt'

class User
  include Mongoid::Document
  before_create :encrypt_password
  after_create  {self.tokens.create}

  field       :email,         type: String
  field       :password_hash, type: String
  field       :password_salt, type: String
  has_many    :bombs
  embeds_many :tokens

  attr_accessor :password

  validates :email, uniqueness: true
  validates :email, presence: true

  def self.authenticate email, password
    user = where(email: email).first
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  def self.authenticate_token token
    where(:'tokens.token' => token).first if token.is_a? String
  end

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret password, password_salt
    end
  end
end


text:
import hashlib
import struct
import sys

import test_env

from recipe_engine.internal.autoroll_impl.commit_list import \
  BackwardsRoll, CommitMetadata, CommitList, UnknownCommit
from PB.recipe_engine.recipes_cfg import RepoSpec

class BaseCommitTest(test_env.RecipeEngineUnitTest):
  def __init__(self, *args, **kwargs):
    super(BaseCommitTest, self).__init__(*args, **kwargs)
    self.cm_counter = 0
    self.cm_timestamp = 0

  def setUp(self):
    super(BaseCommitTest, self).setUp()
    self.cm_counter = 0
    self.cm_timestamp = 1501807893

  def cm(self, repo='repo', deps=(), revision=None,
         author_email='author@example.com', commit_timestamp=None,
         message_lines=('message', 'lines'), roll_candidate=False):

    spec = RepoSpec(
      api_version=2,
      repo_name=repo,
      canonical_repo_url='https://git.example.com/%s.git' % repo,
    )
    for commit in deps:
      repo = commit.spec.repo_name
      spec.deps[repo].url = commit.spec.canonical_repo_url
      spec.deps[repo].revision = commit.revision

    if revision is None:
      revision = hashlib.sha1(struct.pack('!Q', self.cm_counter)).hexdigest()
      self.cm_counter += 1

    if commit_timestamp is None:
      # Increase the commit timestamp by a non-fixed, yet deterministic, amount
      # so that commit timestamps are monotonically increasing.
      commit_timestamp = self.cm_timestamp
      self.cm_timestamp += 60 * (int(revision[:2], 16)+1)

    return CommitMetadata(revision, author_email, commit_timestamp,
                          message_lines, spec, roll_candidate)

  def cl(self, count):
    return CommitList([self.cm() for _ in range(count)])

class TestCommitList(BaseCommitTest):
  def test_empty(self):
    with self.assertRaisesRegexp(AssertionError, 'is empty'):
      CommitList('fake-repo', 'fake-branch', [])

  def test_single(self):
    c = self.cm()
    cl = CommitList('fake-repo', 'fake-branch', [c])
    self.assertEqual(len(cl), 1)
    cursor = cl.cursor()
    self.assertEqual(cursor.current, c)
    self.assertEqual(cursor.next_roll_candidate, None)

  def test_five(self):
    cs = [self.cm() for _ in range(5)]
    cl = CommitList('fake-repo', 'fake-branch', cs)
    self.assertEqual(len(cl), 5)

    cursor = cl.cursor()
    self.assertEqual(cursor.current, cs[0])

    cursor.advance_to(cs[1].revision)
    self.assertEqual(cursor.current, cs[1])

    self.assertEqual(cl.lookup(cs[0].revision), cs[0])

    with self.assertRaises(UnknownCommit):
      cursor.advance_to('not_a_known_commit')
    self.assertEqual(cursor.current, cs[1])

    cursor.advance_to(cs[4].revision)
    self.assertEqual(cursor.current, cs[4])

    with self.assertRaises(BackwardsRoll):
      cursor.advance_to(cs[3].revision)
    self.assertEqual(cursor.current, cs[4])

  def test_dist(self):
    cs = [self.cm() for _ in range(5)]
    cl = CommitList('fake-repo', 'fake-branch', cs)

    # 1 revision
    self.assertEqual(cl.dist(cs[0].revision), 0)
    self.assertEqual(cl.dist(cs[4].revision), 4)
    self.assertIsNone(cl.dist('unknown-revision'))

    # 2 revisions
    self.assertEqual(cl.dist(cs[0].revision, cs[4].revision), 4)
    self.assertEqual(cl.dist(cs[1].revision, cs[3].revision), 2)
    self.assertIsNone(cl.dist(cs[4].revision, cs[0].revision))
    self.assertIsNone(cl.dist(cs[0].revision, 'unknown-revision'))
    with self.assertRaises(UnknownCommit):
      cl.dist('unknown-revision', cs[4].revision)

  def test_compatibility(self):
    cs1 = [self.cm('1') for _ in range(5)]
    cs2 = [
        self.cm('2', [cs1[3]]),  # simulates an out-of-order dependency (revert)
        self.cm('2', [cs1[0]]),
        self.cm('2', [cs1[0]]),
        self.cm('2', [cs1[1]]),
        self.cm('2', [cs1[3]]),
        self.cm('2'),  # simulates a dep being removed
        self.cm('2', [cs1[3]]),  # simulates a dep being added
    ]
    cs3 = [self.cm('3') for _ in range(3)]

    cl1 = CommitList('fake-repo-1', 'fake-branch', cs1)
    cl2 = CommitList('fake-repo-2', 'fake-branch', cs2)
    cl3 = CommitList('fake-repo-3', 'fake-branch', cs3)

    self.assertTrue(cl2.is_compatible(cs2[0].revision, {'1': cs1[3].revision}))
    self.assertFalse(cl2.is_compatible(cs2[0].revision, {'1': cs1[0].revision}))

    self.assertTrue(cl2.is_compatible(cs2[0].revision, {'3': cs3[0].revision}))
    self.assertTrue(cl3.is_compatible(cs3[0].revision, {'2': cs2[0].revision}))

    self.assertEqual(
        cl2.compatible_commits({
            '1': cs1[3].revision,
            '3': cs3[0].revision
        }), [cs2[0], cs2[4], cs2[5], cs2[6]])

if __name__ == '__main__':
  sys.exit(test_env.main())


text:
"""Manage Treadmill allocations.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import logging

import click
import six

from treadmill import cli
from treadmill import restclient
from treadmill import context
from treadmill import admin

_DEFAULT_PRIORITY = 1

_LOGGER = logging.getLogger(__name__)

def _display_tenant(restapi, tenant):
    """Display allocations for the given tenant."""
    tenant_url = '/tenant/%s' % tenant
    alloc_url = '/allocation/%s' % tenant

    tenant_obj = restclient.get(restapi, tenant_url).json()
    allocations_obj = restclient.get(restapi, alloc_url).json()

    tenant_obj['allocations'] = allocations_obj

    tenant_formatter = cli.make_formatter('tenant')
    cli.out(tenant_formatter(tenant_obj))

def _check_reserve_usage(empty, memory, cpu, disk):
    """Checks params constraints for reserve verb."""
    if empty:
        if memory:
            raise click.UsageError('Cannot combine --empty and --memory')
        if cpu:
            raise click.UsageError('Cannot combine --empty and --cpu')
        if disk:
            raise click.UsageError('Cannot combine --empty and --disk')

def _check_tenant_exists(restapi, allocation):
    """Check if tenant exist."""
    tenant_url = '/tenant/{}'.format(allocation)

    # Check if tenant exists.
    try:
        restclient.get(restapi, tenant_url).json()
    except restclient.NotFoundError:
        raise click.UsageError(
            'Allocation not found, '
            'run allocation configure {} --systems ...'.format(allocation))

def _make_allocation(restapi, allocation, env):
    """Ensure allocation exists for given environment."""
    # Make sure allocation exists for given environment.
    alloc_url = '/allocation/{}/{}'.format(allocation, env)
    try:
        restclient.post(restapi, alloc_url, payload={'environment': env})
    except restclient.AlreadyExistsError:
        pass

def init():
    """Return top level command handler."""

    alloc_formatter = cli.make_formatter('tenant')
    ctx = {}

    @click.group(name='allocation')
    @click.option('--api', required=False, help='API url to use.',
                  envvar='TREADMILL_RESTAPI')
    def allocation_grp(api):
        """Manage Treadmill allocations.

        Allocation is a group of applications that share same capacity.
        Each allocation is partitioned by environment and cell. Given
        allocation, cell and environment, users reserve capacity for their
        apps.

        Allocations form a hierarchy, so that when reservation is underused,
        extra capacity is offered to sibling apps first (by environment), and
        then up the tree for applications in parent allocations.
        """
        if api:
            ctx['api'] = api

    @allocation_grp.command(name='list')
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    def _list():
        """List allocations."""
        restapi = context.GLOBAL.admin_api(ctx.get('api'))
        response = restclient.get(restapi, '/tenant/')
        cli.out(alloc_formatter(response.json()))

    @allocation_grp.command()
    @click.option('-s', '--systems', help='System ID', type=cli.LIST)
    @click.argument('allocation', required=True)
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    def configure(allocation, systems):
        """Configure allocation.

        Allocation name is global, and is associated with list of systems.
        """
        restapi = context.GLOBAL.admin_api(ctx.get('api'))
        url = '/tenant/{}'.format(allocation)

        if systems:

            # If tenant exists, update it with new systems. If update fails
            # with resource does not exist error, try creating tenants from
            # parent to child, those that do not exist will be created with
            # provided systems.
            try:
                existing = restclient.get(restapi, url).json()
                all_systems = set(existing['systems'])
                all_systems.update(six.moves.map(int, systems))
                restclient.put(
                    restapi,
                    url,
                    payload={'systems': list(all_systems)}
                )
            except restclient.NotFoundError:
                # Create parent tenants recursively.
                #
                # If parent does not exist, it will be created with the systems
                # specified.
                parts = allocation.split(':')
                for idx in range(1, len(parts) + 1):
                    url = '/tenant/{}'.format(':'.join(parts[:idx]))

                    try:
                        existing = restclient.get(restapi, url).json()
                    except restclient.NotFoundError:
                        restclient.post(
                            restapi,
                            url,
                            payload={'systems': six.moves.map(int, systems)})

        _display_tenant(restapi, allocation)

    @allocation_grp.command()
    @click.option('-e', '--env', help='Environment.', required=True)
    @click.option('-c', '--cell', help='Treadmill cell', required=True)
    @click.option('-p', '--partition', help='Allocation partition')
    @click.option('-r', '--rank', help='Allocation rank', type=int)
    @click.option('--rank-adjustment', help='Rank adjustment', type=int)
    @click.option('--max-utilization', help='Maximum utilization', type=float)
    @click.option('--empty', help='Make empty (zero capacity) reservation.',
                  is_flag=True, default=False)
    @click.option('--memory', help='Memory demand.',
                  metavar='G|M',
                  callback=cli.validate_memory)
    @click.option('--cpu', help='CPU demand, %.',
                  metavar='XX%',
                  callback=cli.validate_cpu)
    @click.option('--disk', help='Disk demand.',
                  metavar='G|M',
                  callback=cli.validate_disk)
    @click.argument('allocation', required=True)
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    # pylint: disable=R0912
    def reserve(allocation, env, cell, partition,
                rank, rank_adjustment, max_utilization, empty,
                memory, cpu, disk):
        """Reserve capacity on the cell for given environment."""
        _check_reserve_usage(empty, memory, cpu, disk)

        restapi = context.GLOBAL.admin_api(ctx.get('api'))

        _check_tenant_exists(restapi, allocation)
        _make_allocation(restapi, allocation, env)

        data = {}
        if empty:
            data['memory'] = '0M'
            data['disk'] = '0M'
            data['cpu'] = '0%'

        if memory:
            data['memory'] = memory
        if cpu:
            data['cpu'] = cpu
        if disk:
            data['disk'] = disk

        if rank is not None:
            data['rank'] = rank
        if rank_adjustment is not None:
            data['rank_adjustment'] = rank_adjustment
        if max_utilization is not None:
            data['max_utilization'] = max_utilization
        if partition:
            data['partition'] = partition

        if data:
            reservation_url = '/allocation/{}/{}/reservation/{}'.format(
                allocation, env, cell
            )

            try:
                existing = restclient.get(restapi, reservation_url).json()
                # TODO: need cleaner way of deleting attributes that are not
                #       valid for update. It is a hack.
                for attr in existing.keys():
                    if (attr not in
                            ['memory', 'cpu', 'disk', 'partition']):
                        del existing[attr]

                existing.update(data)
                restclient.put(restapi, reservation_url, payload=existing)

            except restclient.NotFoundError:
                # some attributes need default values when creating
                if not partition:
                    data['partition'] = admin.DEFAULT_PARTITION

                restclient.post(restapi, reservation_url, payload=data)

        _display_tenant(restapi, allocation)

    @allocation_grp.command()
    @click.option('-e', '--env', help='Environment.', required=True)
    @click.option('-c', '--cell', help='Treadmill cell', required=True)
    @click.option('--pattern', help='Application pattern.', required=True)
    @click.option('--priority', help='Assignment priority.', type=int)
    @click.option('--delete', help='Delete assignment.',
                  is_flag=True, default=False)
    @click.argument('allocation', required=True)
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    def assign(allocation, env, cell, pattern, priority, delete):
        """Assign application pattern:priority to the allocation.

        Application pattern must start with <PROID>. and is a glob expression.

        Environments of the proid and one specified in command line using
        --env option must match.

        Once scheduled, Treadmill scheduler will match application against all
        available patterns and assign application to a reserved capacity.

        All application assigned to a capacity are ordered by priority from
        high to low.
        """
        restapi = context.GLOBAL.admin_api(ctx.get('api'))

        _check_tenant_exists(restapi, allocation)
        _make_allocation(restapi, allocation, env)

        reservation_url = '/allocation/{}/{}/reservation/{}'.format(
            allocation, env, cell
        )

        try:
            restclient.get(restapi, reservation_url)
        except restclient.NotFoundError:
            # TODO: default partition should be resolved in API, not in CLI.
            restclient.post(restapi, reservation_url,
                            payload={'memory': '0M',
                                     'disk': '0M',
                                     'cpu': '0%',
                                     'partition': admin.DEFAULT_PARTITION})

        url = '/allocation/{}/{}/assignment/{}/{}'.format(
            allocation, env, cell, pattern
        )

        if delete:
            restclient.delete(restapi, url)
        else:
            default_prio = None
            existing = restclient.get(restapi, url).json()
            for assignment in existing:
                if assignment['pattern'] == pattern:
                    default_prio = assignment['priority']
            if default_prio is None:
                default_prio = _DEFAULT_PRIORITY

            data = {'priority': priority if priority else default_prio}
            restclient.put(restapi, url, payload=data)

        _display_tenant(restapi, allocation)

    @allocation_grp.command()
    @click.argument('item', required=True)
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    def delete(item):
        """Delete a tenant/allocation/reservation."""
        restapi = context.GLOBAL.admin_api(ctx.get('api'))

        path = item.split('/')
        if len(path) == 1:
            # delete a tenant
            url = '/tenant/%s' % item
            restclient.delete(restapi, url)
        elif len(path) == 2:
            # delete an allocation
            url = '/allocation/%s' % item
            restclient.delete(restapi, url)
        elif len(path) == 3:
            # delete a reservation
            url = '/allocation/%s/%s/reservation/%s' % (path[0],
                                                        path[1],
                                                        path[2])
            restclient.delete(restapi, url)
        else:
            # error
            click.echo('Wrong format: %s' % item, err=True)

    del assign
    del reserve
    del configure
    del _list
    del delete

    return allocation_grp


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BlockedDomain extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'blocked_domains';

    use RecordsActivity;

    /**
     *   The attributes that are mass assignable.
     *
     *   @var array
     */
    protected $fillable = [
        'domain', 'channel', 'description',
    ];
}


text:
package org.jbpm.designer.service;

import org.guvnor.common.services.shared.metadata.model.Overview;
import org.jboss.errai.common.client.api.annotations.Portable;

@Portable
public class DesignerContent {

    private Overview overview;

    public DesignerContent() {
    }

    public DesignerContent(Overview overview) {
        this.overview = overview;
    }

    public Overview getOverview() {
        return overview;
    }

    public void setOverview(Overview overview) {
        this.overview = overview;
    }
}


text:
"""Multi-electrode arrays."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import os
import os.path as op
import itertools

import numpy as np

from ..utils._types import _as_array
from ..utils._misc import _read_python

#------------------------------------------------------------------------------
# PRB file utilities
#------------------------------------------------------------------------------

def _edges_to_adjacency_list(edges):
    """Convert a list of edges into an adjacency list."""
    adj = {}
    for i, j in edges:
        if i in adj:
            ni = adj[i]
        else:
            ni = adj[i] = set()
        if j in adj:
            nj = adj[j]
        else:
            nj = adj[j] = set()
        ni.add(j)
        nj.add(i)
    return adj

def _probe_positions(probe, group):
    """Return the positions of a probe channel group."""
    positions = probe['channel_groups'][group]['geometry']
    channels = _probe_channels(probe, group)
    return np.array([positions[channel] for channel in channels])

def _probe_channels(probe, group):
    """Return the list of channels in a channel group.

    The order is kept.

    """
    return probe['channel_groups'][group]['channels']

def _probe_all_channels(probe):
    """Return the list of channels in the probe."""
    cgs = probe['channel_groups'].values()
    cg_channels = [cg['channels'] for cg in cgs]
    return sorted(set(itertools.chain(*cg_channels)))

def _probe_adjacency_list(probe):
    """Return an adjacency list of a whole probe."""
    cgs = probe['channel_groups'].values()
    graphs = [cg['graph'] for cg in cgs]
    edges = list(itertools.chain(*graphs))
    adjacency_list = _edges_to_adjacency_list(edges)
    return adjacency_list

def _channels_per_group(probe):
    groups = probe['channel_groups'].keys()
    return {group: probe['channel_groups'][group]['channels']
            for group in groups}

def load_probe(name):
    """Load one of the built-in probes."""
    if op.exists(name):
        # The argument can be either a path to a PRB file.
        path = name
    else:
        # Or the name of a built-in probe.
        curdir = op.realpath(op.dirname(__file__))
        path = op.join(curdir, 'probes/{}.prb'.format(name))
    if not op.exists(path):
        raise IOError("The probe `{}` cannot be found.".format(name))
    return _read_python(path)

def list_probes():
    """Return the list of built-in probes."""
    curdir = op.realpath(op.dirname(__file__))
    return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
            if fn.endswith('.prb')]

#------------------------------------------------------------------------------
# MEA class
#------------------------------------------------------------------------------

class MEA(object):
    """A Multi-Electrode Array.

    There are two modes:

    * No probe specified: one single channel group, positions and adjacency
      list specified directly.
    * Probe specified: one can change the current channel_group.

    """

    def __init__(self,
                 channels=None,
                 positions=None,
                 adjacency=None,
                 probe=None,
                 ):
        self._probe = probe
        self._channels = channels
        if positions is not None:
            assert self.n_channels == positions.shape[0]
        self._positions = positions
        # This is a mapping {channel: list of neighbors}.
        if adjacency is None and probe is not None:
            adjacency = _probe_adjacency_list(probe)
            self.channels_per_group = _channels_per_group(probe)
        self._adjacency = adjacency

    def _check_positions(self, positions):
        if positions is None:
            return
        positions = _as_array(positions)
        if self.n_channels is None:
            self.n_channels = positions.shape[0]
        if positions.shape[0] != self.n_channels:
            raise ValueError("'positions' "
                             "(shape {0:s})".format(str(positions.shape)) +
                             " and 'n_channels' "
                             "({0:d})".format(self.n_channels) +
                             " do not match.")

    @property
    def positions(self):
        """Channel positions in the current channel group."""
        return self._positions

    @positions.setter
    def positions(self, value):
        self._check_positions(value)
        self._positions = value

    @property
    def channels(self):
        """Channel ids in the current channel group."""
        return self._channels

    @property
    def n_channels(self):
        """Number of channels in the current channel group."""
        return len(self._channels) if self._channels is not None else 0

    @property
    def adjacency(self):
        """Adjacency graph in the current channel group."""
        return self._adjacency

    @adjacency.setter
    def adjacency(self, value):
        self._adjacency = value

    def change_channel_group(self, group):
        """Change the current channel group."""
        assert self._probe is not None
        self._channels = _probe_channels(self._probe, group)
        self._positions = _probe_positions(self._probe, group)

#------------------------------------------------------------------------------
# Common probes
#------------------------------------------------------------------------------

def linear_positions(n_channels):
    """Linear channel positions along the vertical axis."""
    return np.c_[np.zeros(n_channels),
                 np.linspace(0., 1., n_channels)]

def staggered_positions(n_channels):
    """Generate channel positions for a staggered probe."""
    i = np.arange(n_channels - 1)
    x, y = (-1) ** i * (5 + i), 10 * (i + 1)
    pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
    return pos


text:
"""
Module for moving files around for the preprocessor.
"""

import glob
import os
import shutil
import myio.myio as myio
import preprocessing.prep_global as prep_global
import chef_global.debug as debug
import chef_global.config as config

def _append_all_recipe_files():
    """
    Takes each file in the config.DATA_DIRECTORY folder and
    appends them onto a single recipe file which will then
    contain plain English recipes all in one file.
    @return: void
    """
    if not os.path.isdir(config.DATA_DIRECTORY):
        raise ValueError("config.DATA_DIRECTORY not set.")
    else:
        files = glob.glob(config.DATA_DIRECTORY + "/*.xml")
        myio.join_all_files(files, config.RECIPE_FILE_PATH)

def _copy_master_to_data_location():
    """
    Copies the master directory files over the data
    directory. Deletes any files in the data directory
    before copying.
    @return: void
    """
    debug.debug_print("_copy_master_to_data_location called, making assertions...")
    debug.assert_value_is_set(config.MASTER_DATA_DIRECTORY,
                        "config.MASTER_DATA_DIRECTORY")
    debug.assert_value_is_set(config.DATA_DIRECTORY,
                        "config.DATA_DIRECTORY")

    print("Deleting old data files...")
    prep_global._apply_func_to_each_data_file(os.remove)

    print("Copying data files from " + str(config.MASTER_DATA_DIRECTORY) +
            " to " + str(config.DATA_DIRECTORY))
    # Collect files to copy
    list_of_file_names = [os.path.join(config.MASTER_DATA_DIRECTORY, file_name) for
                          file_name in os.listdir(config.MASTER_DATA_DIRECTORY)]

    for f in list_of_file_names:
        f_name = os.path.split(f)[-1]
        if f_name != "zuni.xml":
            # Don't include zuni - it is super weird
            debug.debug_print("Copying " + f_name + " to new directory...")
            shutil.copyfile(f, os.path.join(config.DATA_DIRECTORY, f_name))


text:
package functions.math.special;

import java.math.BigDecimal;
import java.util.List;

import main.Environment;
import datatypes.Atom;
import datatypes.Expression;
import datatypes.Function;

public class Sqrt extends Function {

	@Override
	public Expression invoke(List<Expression> args, Environment e) {
		argcheck(1, args);
		double d=((BigDecimal)args.get(0).eval(e).value()).doubleValue();
		return new Atom(new BigDecimal(Math.sqrt(d)));
	}

}


text:
using CroquetAustralia.Domain.Data;
using CroquetAustralia.Domain.UnitTests.TestHelpers;
using CroquetAustralia.TestHelpers;

namespace CroquetAustralia.Domain.Specifications.TestHelpers
{
    public class Given
    {
        public Given()
        {
            DummyTournament = ServiceProvider.Instance.Get<DummyTournament>();
        }

        public DummyTournament DummyTournament { get; set; }
        public Tournament Tournament { get; set; }
    }
}


text:
be-dialog
================

See the [component page](http://BasicElements.github.io/be-dialog) for more information.