text:
/**
 * An interface to be implemented by any {@apilink Ability} that needs to free up
 * the resources it uses, e.g. disconnect from a database.
 *
 * This {@apilink Discardable.discard} method is invoked directly by the {@apilink Actor}, and indirectly by {@apilink Stage}:
 * - when {@apilink SceneFinishes}, for actors instantiated after {@apilink SceneStarts} - e.g. within a test scenario or in a "before each" hook
 * - when {@apilink TestRunFinishes}, for actors instantiated before {@apilink SceneStarts} - e.g. in a "before all" hook
 *
 * Note that events such as {@apilink SceneFinishes} and {@apilink TestRunFinishes} are emitted by Serenity/JS test runner adapters,
 * such as `@serenity-js/cucumber`, `@serenity-js/mocha`, `@serenity-js/jasmine`, and so on.
 * Consult their respective readmes to learn how to register them with your test runner of choice.
 *
 * ## Learn more
 * - {@apilink Ability}
 * - {@apilink AbilityType}
 * - {@apilink Initialisable}
 *
 * @group Abilities
 */
export interface Discardable {

    /**
     * Discards the resources associated with this ability.
     */
    discard(): Promise<void> | void;
}


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

#ifndef Patternist_ExpressionVariableReference_H
#define Patternist_ExpressionVariableReference_H

#include "qvariabledeclaration_p.h"
#include "qvariablereference_p.h"

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

namespace QPatternist
{
    /**
     * @short A reference to a variable declared with <tt>declare variable</tt> or @c let.
     *
     * It's also used by variable bindings in @c case branches of the @c typeswitch
     * expression.
     *
     * This AST node is only used up until the typeCheck() stage. Therefore it
     * has no functions for evaluation, such as evaluateSequence().
     *
     * @author Frans Englich <frans.englich@nokia.com>
     * @ingroup Patternist_expressions
     */
    class ExpressionVariableReference : public VariableReference
    {
    public:
        ExpressionVariableReference(const VariableSlotID slot,
                                    const VariableDeclaration *varDecl);

        virtual bool evaluateEBV(const DynamicContext::Ptr &context) const;
        virtual Item evaluateSingleton(const DynamicContext::Ptr &context) const;
        virtual Item::Iterator::Ptr evaluateSequence(const DynamicContext::Ptr &context) const;

        virtual Expression::Ptr typeCheck(const StaticContext::Ptr &context,
                                          const SequenceType::Ptr &reqType);
        virtual SequenceType::Ptr staticType() const;
        virtual ID id() const;
        virtual ExpressionVisitorResult::Ptr accept(const ExpressionVisitor::Ptr &visitor) const;

        inline const Expression::Ptr &sourceExpression() const;
        inline const VariableDeclaration *variableDeclaration() const;
    private:
        const VariableDeclaration *m_varDecl;
    };

    inline const Expression::Ptr &ExpressionVariableReference::sourceExpression() const
    {
        return m_varDecl->expression();
    }

    inline const VariableDeclaration *ExpressionVariableReference::variableDeclaration() const
    {
        return m_varDecl;
    }

}

QT_END_NAMESPACE

QT_END_HEADER

#endif

redpajama_set_name: RedPajamaGithub


text:
class Engine < Rails::Engine
  # Mimic old vendored plugin behavior, attachment_fu/lib is autoloaded.
  config.autoload_paths << File.expand_path("..", __FILE__)

  initializer "attachment_fu" do
    require 'tempfile'
    require 'geometry'
    require 'attachment_fu_validates_attachment'
    ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods)
    Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH)
    FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path

    # overwrite so tempfiles use the extension of the basename.
    # important for rmagick and image science
    Tempfile.class_eval do
      def make_tmpname(basename, n)
        ext = nil
        sprintf("%s%d-%d%s", basename.to_s.gsub(/\.\w+$/) { |s| ext = s; '' }, $$, n.to_i, ext)
      end
    end

  end
end


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page

class MediaList(ListResource):

    def __init__(self, version, account_sid, message_sid):
        """
        Initialize the MediaList

        :param Version version: Version that contains the resource
        :param account_sid: The SID of the Account that created this resource
        :param message_sid: The unique string that identifies the resource

        :returns: twilio.rest.api.v2010.account.message.media.MediaList
        :rtype: twilio.rest.api.v2010.account.message.media.MediaList
        """
        super(MediaList, self).__init__(version)

        # Path Solution
        self._solution = {'account_sid': account_sid, 'message_sid': message_sid, }
        self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media.json'.format(**self._solution)

    def stream(self, date_created_before=values.unset, date_created=values.unset,
               date_created_after=values.unset, limit=None, page_size=None):
        """
        Streams MediaInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param datetime date_created_before: Only include media that was created on this date
        :param datetime date_created: Only include media that was created on this date
        :param datetime date_created_after: Only include media that was created on this date
        :param int limit: Upper limit for the number of records to return. stream()
                          guarantees to never return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, stream() will attempt to read the
                              limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance]
        """
        limits = self._version.read_limits(limit, page_size)

        page = self.page(
            date_created_before=date_created_before,
            date_created=date_created,
            date_created_after=date_created_after,
            page_size=limits['page_size'],
        )

        return self._version.stream(page, limits['limit'])

    def list(self, date_created_before=values.unset, date_created=values.unset,
             date_created_after=values.unset, limit=None, page_size=None):
        """
        Lists MediaInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param datetime date_created_before: Only include media that was created on this date
        :param datetime date_created: Only include media that was created on this date
        :param datetime date_created_after: Only include media that was created on this date
        :param int limit: Upper limit for the number of records to return. list() guarantees
                          never to return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, list() will attempt to read the limit
                              with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance]
        """
        return list(self.stream(
            date_created_before=date_created_before,
            date_created=date_created,
            date_created_after=date_created_after,
            limit=limit,
            page_size=page_size,
        ))

    def page(self, date_created_before=values.unset, date_created=values.unset,
             date_created_after=values.unset, page_token=values.unset,
             page_number=values.unset, page_size=values.unset):
        """
        Retrieve a single page of MediaInstance records from the API.
        Request is executed immediately

        :param datetime date_created_before: Only include media that was created on this date
        :param datetime date_created: Only include media that was created on this date
        :param datetime date_created_after: Only include media that was created on this date
        :param str page_token: PageToken provided by the API
        :param int page_number: Page Number, this value is simply for client state
        :param int page_size: Number of records to return, defaults to 50

        :returns: Page of MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaPage
        """
        data = values.of({
            'DateCreated<': serialize.iso8601_datetime(date_created_before),
            'DateCreated': serialize.iso8601_datetime(date_created),
            'DateCreated>': serialize.iso8601_datetime(date_created_after),
            'PageToken': page_token,
            'Page': page_number,
            'PageSize': page_size,
        })

        response = self._version.page(method='GET', uri=self._uri, params=data, )

        return MediaPage(self._version, response, self._solution)

    def get_page(self, target_url):
        """
        Retrieve a specific page of MediaInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaPage
        """
        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return MediaPage(self._version, response, self._solution)

    def get(self, sid):
        """
        Constructs a MediaContext

        :param sid: The unique string that identifies this resource

        :returns: twilio.rest.api.v2010.account.message.media.MediaContext
        :rtype: twilio.rest.api.v2010.account.message.media.MediaContext
        """
        return MediaContext(
            self._version,
            account_sid=self._solution['account_sid'],
            message_sid=self._solution['message_sid'],
            sid=sid,
        )

    def __call__(self, sid):
        """
        Constructs a MediaContext

        :param sid: The unique string that identifies this resource

        :returns: twilio.rest.api.v2010.account.message.media.MediaContext
        :rtype: twilio.rest.api.v2010.account.message.media.MediaContext
        """
        return MediaContext(
            self._version,
            account_sid=self._solution['account_sid'],
            message_sid=self._solution['message_sid'],
            sid=sid,
        )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Api.V2010.MediaList>'

class MediaPage(Page):

    def __init__(self, version, response, solution):
        """
        Initialize the MediaPage

        :param Version version: Version that contains the resource
        :param Response response: Response from the API
        :param account_sid: The SID of the Account that created this resource
        :param message_sid: The unique string that identifies the resource

        :returns: twilio.rest.api.v2010.account.message.media.MediaPage
        :rtype: twilio.rest.api.v2010.account.message.media.MediaPage
        """
        super(MediaPage, self).__init__(version, response)

        # Path Solution
        self._solution = solution

    def get_instance(self, payload):
        """
        Build an instance of MediaInstance

        :param dict payload: Payload response from the API

        :returns: twilio.rest.api.v2010.account.message.media.MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
        """
        return MediaInstance(
            self._version,
            payload,
            account_sid=self._solution['account_sid'],
            message_sid=self._solution['message_sid'],
        )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Api.V2010.MediaPage>'

class MediaContext(InstanceContext):

    def __init__(self, version, account_sid, message_sid, sid):
        """
        Initialize the MediaContext

        :param Version version: Version that contains the resource
        :param account_sid: The SID of the Account that created the resource(s) to fetch
        :param message_sid: The SID of the Message resource that this Media resource belongs to
        :param sid: The unique string that identifies this resource

        :returns: twilio.rest.api.v2010.account.message.media.MediaContext
        :rtype: twilio.rest.api.v2010.account.message.media.MediaContext
        """
        super(MediaContext, self).__init__(version)

        # Path Solution
        self._solution = {'account_sid': account_sid, 'message_sid': message_sid, 'sid': sid, }
        self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json'.format(**self._solution)

    def delete(self):
        """
        Deletes the MediaInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._version.delete(method='DELETE', uri=self._uri, )

    def fetch(self):
        """
        Fetch the MediaInstance

        :returns: The fetched MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
        """
        payload = self._version.fetch(method='GET', uri=self._uri, )

        return MediaInstance(
            self._version,
            payload,
            account_sid=self._solution['account_sid'],
            message_sid=self._solution['message_sid'],
            sid=self._solution['sid'],
        )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Api.V2010.MediaContext {}>'.format(context)

class MediaInstance(InstanceResource):

    def __init__(self, version, payload, account_sid, message_sid, sid=None):
        """
        Initialize the MediaInstance

        :returns: twilio.rest.api.v2010.account.message.media.MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
        """
        super(MediaInstance, self).__init__(version)

        # Marshaled Properties
        self._properties = {
            'account_sid': payload.get('account_sid'),
            'content_type': payload.get('content_type'),
            'date_created': deserialize.rfc2822_datetime(payload.get('date_created')),
            'date_updated': deserialize.rfc2822_datetime(payload.get('date_updated')),
            'parent_sid': payload.get('parent_sid'),
            'sid': payload.get('sid'),
            'uri': payload.get('uri'),
        }

        # Context
        self._context = None
        self._solution = {
            'account_sid': account_sid,
            'message_sid': message_sid,
            'sid': sid or self._properties['sid'],
        }

    @property
    def _proxy(self):
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions.  All instance actions are proxied to the context

        :returns: MediaContext for this MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaContext
        """
        if self._context is None:
            self._context = MediaContext(
                self._version,
                account_sid=self._solution['account_sid'],
                message_sid=self._solution['message_sid'],
                sid=self._solution['sid'],
            )
        return self._context

    @property
    def account_sid(self):
        """
        :returns: The SID of the Account that created this resource
        :rtype: unicode
        """
        return self._properties['account_sid']

    @property
    def content_type(self):
        """
        :returns: The default mime-type of the media
        :rtype: unicode
        """
        return self._properties['content_type']

    @property
    def date_created(self):
        """
        :returns: The RFC 2822 date and time in GMT that this resource was created
        :rtype: datetime
        """
        return self._properties['date_created']

    @property
    def date_updated(self):
        """
        :returns: The RFC 2822 date and time in GMT that this resource was last updated
        :rtype: datetime
        """
        return self._properties['date_updated']

    @property
    def parent_sid(self):
        """
        :returns: The SID of the resource that created the media
        :rtype: unicode
        """
        return self._properties['parent_sid']

    @property
    def sid(self):
        """
        :returns: The unique string that identifies this resource
        :rtype: unicode
        """
        return self._properties['sid']

    @property
    def uri(self):
        """
        :returns: The URI of this resource, relative to `https://api.twilio.com`
        :rtype: unicode
        """
        return self._properties['uri']

    def delete(self):
        """
        Deletes the MediaInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._proxy.delete()

    def fetch(self):
        """
        Fetch the MediaInstance

        :returns: The fetched MediaInstance
        :rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
        """
        return self._proxy.fetch()

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Api.V2010.MediaInstance {}>'.format(context)


text:
package DDG::Goodie::ChineseZodiac;
# ABSTRACT: Return the Chinese zodiac animal for a given year.

use DDG::Goodie;
with 'DDG::GoodieRole::Dates';
use DateTime::Calendar::Chinese;
use DateTime::Event::Chinese qw(chinese_new_year_before chinese_new_year_after);
use utf8;

triggers any => 'chinese zodiac', 'shēngxiào', 'shengxiao', 'shēng xiào', 'sheng xiao';
zci is_cached => 0;

name 'Chinese Zodiac';
description 'Return the Chinese zodiac animal for a given year';
primary_example_queries 'chinese zodiac for 1969';
secondary_example_queries '2004 chinese zodiac animal', 'what was the chinese zodiac animal in 1992', 'what will the chinese zodiac animal be for 2056', 'last year\'s chinese zodiac';
category 'dates';
topics 'special_interest';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/ChineseZodiac.pm';
attribution github => ['http://github.com/wilkox', 'wilkox'];

my %animal_to_language = (
  'hare' => { en => 'Rabbit', zh => '兔' },
  'dragon' => { en => 'Dragon', zh => '龙' },
  'snake' => { en => 'Snake', zh => '蛇' },
  'horse' => { en => 'Horse', zh => '马' },
  'sheep' => { en => 'Goat', zh => '羊' },
  'monkey' => { en => 'Monkey', zh => '猴' },
  'fowl' => { en => 'Rooster', zh => '鸡' },
  'dog' => { en => 'Dog', zh => '狗' },
  'pig' => { en => 'Pig', zh => '猪' },
  'rat' => { en => 'Rat', zh => '鼠' },
  'ox' => { en => 'Ox', zh => '牛' },
  'tiger' => { en => 'Tiger', zh => '虎' }
);

my $chinese_zodiac_tz            = 'Asia/Shanghai';
my $descriptive_datestring_regex = descriptive_datestring_regex();
my $formatted_datestring_regex   = formatted_datestring_regex();

handle remainder => sub {

  #Figure out what date the user is interested in
  my $date_gregorian;

  if (/^$formatted_datestring_regex$/) {
    # First look for a fully specified string
    $date_gregorian = parse_formatted_datestring_to_date($_);
  } elsif (/\b(\d+)\b/) {
    # Now check for bare years, as we prefer a different start time than the role.
    $date_gregorian = DateTime->new(year  => $1, month => 6,);
  } elsif (/^($descriptive_datestring_regex)([']?[sS]?)$/) {
    # Now use the role to look for more vague date suggestions
    $date_gregorian = parse_descriptive_datestring_to_date($1);
  } elsif (/(what|which|animal|current)/) {
    #Otherwise, default to now if it seems like the user is
    # asking a question about the current zodiac animal
    $date_gregorian = DateTime->now();
  }

  #Don't want to show instant answer if user is just looking for
  # general information on the chinese zodiac
  return unless $date_gregorian;
  $date_gregorian->set_time_zone($chinese_zodiac_tz);
  #DateTime::Event::SolarTerm only supports 1900--2069, so
  # return nothing if the user provides a year outside this range
  return unless $date_gregorian->year >= 1900 && $date_gregorian->year <= 2069;

  #Find the Chinese year that aligns
  # with the query (presumed Gregorian) year
  my $year_chinese = DateTime::Calendar::Chinese->from_object(object => $date_gregorian);

  #Get the inclusive Gregorian date range for the Chinese year
  #Note that returned dates will be for the 'Asia/Shanghai'
  # time zone (China Standard Time/CST) as this is where
  # Chinese New Year is calculated
  my $year_start = chinese_new_year_before($date_gregorian)->set_time_zone($chinese_zodiac_tz);
  my $year_end = chinese_new_year_after($date_gregorian)->subtract(days => 1)->set_time_zone($chinese_zodiac_tz);

  my $animal = $year_chinese->zodiac_animal;
  my $english = $animal_to_language{$animal}{'en'};
  my $character = $animal_to_language{$animal}{'zh'};

  my $statement = 'Chinese zodiac animal for ' . date_output_string($year_start) . "–" . date_output_string($year_end);

  return answer => $english, html => wrap_html($character, $english, $statement);
};

sub wrap_html {
  my ($character, $english, $statement) = @_;
  return "

$character ($english)
$statement
";
}

1;


text:
edump
=====

An Erlang crashdump analysis library

Usage
-----

```erlang
application:start(edump).
{ok, Index} = edump_index:new([{stream, {file, "../erl_crash.dump"}}]).
```
Once an index is built you can start parsing bits of detail out of the
crash dump.

```erlang
edump_viewer:general_info(Index).
{ok, Procs} = edump_viewer:processes(Index).
PList = edump_viewer:process_list(Index).
```

By default the processes are ordered by stack heap size so to view
the details on the largest consumer of memory.

```erlang
edump_viewer:process_info(Procs, hd(lists:reverse(PList))).
```


text:
<?php

/**
 * @file
 * Definition of Drupal\tracker\Tests\TrackerTest.
 */

namespace Drupal\tracker\Tests;

use Drupal\comment\CommentInterface;
use Drupal\simpletest\WebTestBase;

/**
 * Create and delete nodes and check for their display in the tracker listings.
 *
 * @group tracker
 */
class TrackerTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('comment', 'tracker', 'history');

  /**
   * The main user for testing.
   *
   * @var object
   */
  protected $user;

  /**
   * A second user that will 'create' comments and nodes.
   *
   * @var object
   */
  protected $other_user;

  protected function setUp() {
    parent::setUp();

    $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));

    $permissions = array('access comments', 'create page content', 'post comments', 'skip comment approval');
    $this->user = $this->drupalCreateUser($permissions);
    $this->other_user = $this->drupalCreateUser($permissions);
    $this->container->get('comment.manager')->addDefaultField('node', 'page');
  }

  /**
   * Tests for the presence of nodes on the global tracker listing.
   */
  function testTrackerAll() {
    $this->drupalLogin($this->user);

    $unpublished = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'status' => 0,
    ));
    $published = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'status' => 1,
    ));

    $this->drupalGet('activity');
    $this->assertNoText($unpublished->label(), 'Unpublished node does not show up in the tracker listing.');
    $this->assertText($published->label(), 'Published node shows up in the tracker listing.');
    $this->assertLink(t('My recent content'), 0, 'User tab shows up on the global tracker page.');

    // Delete a node and ensure it no longer appears on the tracker.
    $published->delete();
    $this->drupalGet('activity');
    $this->assertNoText($published->label(), 'Deleted node does not show up in the tracker listing.');
  }

  /**
   * Tests for the presence of nodes on a user's tracker listing.
   */
  function testTrackerUser() {
    $this->drupalLogin($this->user);

    $unpublished = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'uid' => $this->user->id(),
      'status' => 0,
    ));
    $my_published = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'uid' => $this->user->id(),
      'status' => 1,
    ));
    $other_published_no_comment = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'uid' => $this->other_user->id(),
      'status' => 1,
    ));
    $other_published_my_comment = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
      'uid' => $this->other_user->id(),
      'status' => 1,
    ));
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $other_published_my_comment->id() . '/comment', $comment, t('Save'));

    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertNoText($unpublished->label(), "Unpublished nodes do not show up in the user's tracker listing.");
    $this->assertText($my_published->label(), "Published nodes show up in the user's tracker listing.");
    $this->assertNoText($other_published_no_comment->label(), "Another user's nodes do not show up in the user's tracker listing.");
    $this->assertText($other_published_my_comment->label(), "Nodes that the user has commented on appear in the user's tracker listing.");
    $this->assertLink($my_published->label());
    $this->assertNoLink($unpublished->label());
    // Verify that title and tab title have been set correctly.
    $this->assertText('Activity', 'The user activity tab has the name "Activity".');
    $this->assertTitle(t('@name | @site', array('@name' => $this->user->getUsername(), '@site' => \Drupal::config('system.site')->get('name'))), 'The user tracker page has the correct page title.');

    // Verify that unpublished comments are removed from the tracker.
    $admin_user = $this->drupalCreateUser(array('post comments', 'administer comments', 'access user profiles'));
    $this->drupalLogin($admin_user);
    $this->drupalPostForm('comment/1/edit', array('status' => CommentInterface::NOT_PUBLISHED), t('Save'));
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertNoText($other_published_my_comment->label(), 'Unpublished comments are not counted on the tracker listing.');
  }

  /**
   * Tests for the presence of the "new" flag for nodes.
   */
  function testTrackerNewNodes() {
    $this->drupalLogin($this->user);

    $edit = array(
      'title' => $this->randomMachineName(8),
    );

    $node = $this->drupalCreateNode($edit);
    $title = $edit['title'];
    $this->drupalGet('activity');
    $this->assertPattern('/' . $title . '.*new/', 'New nodes are flagged as such in the activity listing.');

    $this->drupalGet('node/' . $node->id());
    // Simulate the JavaScript on the node page to mark the node as read.
    // @todo Get rid of curlExec() once https://drupal.org/node/2074037 lands.
    $this->curlExec(array(
      CURLOPT_URL => \Drupal::url('history.read_node', ['node' => $node->id()], array('absolute' => TRUE)),
      CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
      ),
    ));
    $this->drupalGet('activity');
    $this->assertNoPattern('/' . $title . '.*new/', 'Visited nodes are not flagged as new.');

    $this->drupalLogin($this->other_user);
    $this->drupalGet('activity');
    $this->assertPattern('/' . $title . '.*new/', 'For another user, new nodes are flagged as such in the tracker listing.');

    $this->drupalGet('node/' . $node->id());
    // Simulate the JavaScript on the node page to mark the node as read.
    // @todo Get rid of curlExec() once https://drupal.org/node/2074037 lands.
    $this->curlExec(array(
      CURLOPT_URL => \Drupal::url('history.read_node', ['node' => $node->id()], array('absolute' => TRUE)),
      CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
      ),
    ));
    $this->drupalGet('activity');
    $this->assertNoPattern('/' . $title . '.*new/', 'For another user, visited nodes are not flagged as new.');
  }

  /**
   * Tests for comment counters on the tracker listing.
   */
  function testTrackerNewComments() {
    $this->drupalLogin($this->user);

    $node = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
    ));

    // Add a comment to the page.
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $node->id() . '/comment', $comment, t('Save'));
    // The new comment is automatically viewed by the current user. Simulate the
    // JavaScript that does this.
    // @todo Get rid of curlExec() once https://drupal.org/node/2074037 lands.
    $this->curlExec(array(
      CURLOPT_URL => \Drupal::url('history.read_node', ['node' => $node->id()], array('absolute' => TRUE)),
      CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
      ),
    ));

    $this->drupalLogin($this->other_user);
    $this->drupalGet('activity');
    $this->assertText('1 new', 'New comments are counted on the tracker listing pages.');
    $this->drupalGet('node/' . $node->id());

    // Add another comment as other_user.
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    // If the comment is posted in the same second as the last one then Drupal
    // can't tell the difference, so we wait one second here.
    sleep(1);
    $this->drupalPostForm('comment/reply/node/' . $node->id(). '/comment', $comment, t('Save'));

    $this->drupalLogin($this->user);
    $this->drupalGet('activity');
    $this->assertText('1 new', 'New comments are counted on the tracker listing pages.');
    $this->assertLink(t('1 new'));
  }

  /**
   * Tests for ordering on a users tracker listing when comments are posted.
   */
  function testTrackerOrderingNewComments() {
    $this->drupalLogin($this->user);

    $node_one = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
    ));

    $node_two = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(8),
    ));

    // Now get other_user to track these pieces of content.
    $this->drupalLogin($this->other_user);

    // Add a comment to the first page.
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $node_one->id() . '/comment', $comment, t('Save'));

    // If the comment is posted in the same second as the last one then Drupal
    // can't tell the difference, so we wait one second here.
    sleep(1);

    // Add a comment to the second page.
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $node_two->id() . '/comment', $comment, t('Save'));

    // We should at this point have in our tracker for other_user:
    // 1. node_two
    // 2. node_one
    // Because that's the reverse order of the posted comments.

    // Now we're going to post a comment to node_one which should jump it to the
    // top of the list.

    $this->drupalLogin($this->user);
    // If the comment is posted in the same second as the last one then Drupal
    // can't tell the difference, so we wait one second here.
    sleep(1);

    // Add a comment to the second page.
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $node_one->id() . '/comment', $comment, t('Save'));

    // Switch back to the other_user and assert that the order has swapped.
    $this->drupalLogin($this->other_user);
    $this->drupalGet('user/' . $this->other_user->id() . '/activity');
    // This is a cheeky way of asserting that the nodes are in the right order
    // on the tracker page.
    // It's almost certainly too brittle.
    $pattern = '/' . preg_quote($node_one->getTitle()) . '.+' . preg_quote($node_two->getTitle()) . '/s';
    $this->verbose($pattern);
    $this->assertPattern($pattern, 'Most recently commented on node appears at the top of tracker');
  }

  /**
   * Tests that existing nodes are indexed by cron.
   */
  function testTrackerCronIndexing() {
    $this->drupalLogin($this->user);

    // Create 3 nodes.
    $edits = array();
    $nodes = array();
    for ($i = 1; $i <= 3; $i++) {
      $edits[$i] = array(
        'title' => $this->randomMachineName(),
      );
      $nodes[$i] = $this->drupalCreateNode($edits[$i]);
    }

    // Add a comment to the last node as other user.
    $this->drupalLogin($this->other_user);
    $comment = array(
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
    );
    $this->drupalPostForm('comment/reply/node/' . $nodes[3]->id() . '/comment', $comment, t('Save'));

    // Start indexing backwards from node 3.
    \Drupal::state()->set('tracker.index_nid', 3);

    // Clear the current tracker tables and rebuild them.
    db_delete('tracker_node')
      ->execute();
    db_delete('tracker_user')
      ->execute();
    tracker_cron();

    $this->drupalLogin($this->user);

    // Fetch the user's tracker.
    $this->drupalGet('activity/' . $this->user->id());

    // Assert that all node titles are displayed.
    foreach ($nodes as $i => $node) {
      $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', array('@i' => $i)));
    }
    $this->assertText('1 new', 'One new comment is counted on the tracker listing pages.');
    $this->assertText('updated', 'Node is listed as updated');

    // Fetch the site-wide tracker.
    $this->drupalGet('activity');

    // Assert that all node titles are displayed.
    foreach ($nodes as $i => $node) {
      $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', array('@i' => $i)));
    }
    $this->assertText('1 new', 'New comment is counted on the tracker listing pages.');
  }

  /**
   * Tests that publish/unpublish works at admin/content/node.
   */
  function testTrackerAdminUnpublish() {
    \Drupal::service('module_installer')->install(array('views'));
    $admin_user = $this->drupalCreateUser(array('access content overview', 'administer nodes', 'bypass node access'));
    $this->drupalLogin($admin_user);

    $node = $this->drupalCreateNode(array(
      'title' => $this->randomMachineName(),
    ));

    // Assert that the node is displayed.
    $this->drupalGet('activity');
    $this->assertText($node->label(), 'A node is displayed on the tracker listing pages.');

    // Unpublish the node and ensure that it's no longer displayed.
    $edit = array(
      'action' => 'node_unpublish_action',
      'node_bulk_form[0]' => $node->id(),
    );
    $this->drupalPostForm('admin/content', $edit, t('Apply'));

    $this->drupalGet('activity');
    $this->assertText(t('No content available.'), 'A node is displayed on the tracker listing pages.');
  }
}


text:
  <md-toolbar class="md-primary md-hue-2">

      Projects

      <md-button class="md-fab new-button" ng-click="new()">
        <md-icon>add</md-icon>
      </md-button>

  </md-toolbar>

  <md-card flex="70" flex-offset="15" ng-show="projects.length">
    <md-list class="projects-list">
      <md-list-item
        ng-repeat="project in projects"
        class="md-2-line"
        ng-click="edit(project)"
      >
        <md-icon class="md-avatar-icon">folder</md-icon>

{{ project.name }}

Last updated {{ project.updatedAt | date: "short" }}

        <md-icon
          class="md-secondary md-icon-button"
          aria-label="Edit"
          ng-click="edit(project)"
          >edit</md-icon
        >
        <md-icon
          class="md-secondary md-icon-button"
          aria-label="Delete"
          ng-click="delete(project)"
          >delete</md-icon
        >
        <md-divider ng-if="!$last"></md-divider>
      </md-list-item>
    </md-list>
  </md-card>

    <md-button
      ng-disabled="!hasPrevious"
      class="md-primary"
      ng-click="previous()"
    >
      <md-icon>keyboard_arrow_left</md-icon>
    </md-button>

    <md-button ng-disabled="!hasNext" class="md-primary" ng-click="next()">
      <md-icon>keyboard_arrow_right</md-icon>
    </md-button>

    There are currently no projects to display.


text:
"""This module contains a set of classes that used by SQLAlchemy for
Object Relational Mapper (ORM)

"""

from distutils.version import StrictVersion
import os
import logging
import datetime
import alembic
from alembic.config import Config
from alembic import command
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, create_engine
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey, Integer, String
from sqlalchemy import Text, BOOLEAN
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext import declarative, compiler

# disabling Pylint error messages on SQLAlchemy classes and convention
# Invalid constant name.
# pylint: disable=C0103
# Too few public methods.
# pylint: disable=R0903
# Too many public methods.
# pylint: disable=R0904
# Class has no __init__ method.
# pylint: disable=W0232
# Redefining name '<name>' from outer scope.
# pylint: disable=W0621

# Minimum required version of SQLAlchemy and Alembic for the Database
# migration code to work correctly.  Specifically the naming convention feature
# that are necessary to provide predictable database constraints' names.
if StrictVersion(alembic.__version__) < StrictVersion("0.8.2"):
    raise RuntimeError("The Alembic version need to be at least 0.8.2.  "
                       "The installed version is %s" % alembic.__version__)
if StrictVersion(sa.__version__) < StrictVersion("0.9.2"):
    raise RuntimeError("The SQLAlchemy version need to be at least 0.9.2.  "
                       "The installed version is %s" % sa.__version__)

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)

# Define a generic current timestamp function to be execute on the database
# server side
class CurrentTimeStamp(sa.sql.expression.FunctionElement):
    """Define a current timestamp function name that can be use to map to
    different database dialect implementations.
    """
    # Too many ancestors (12/7)
    # pylint: disable=R0901
    type = DateTime()

@compiler.compiles(CurrentTimeStamp, 'postgresql')
def postgres_current_timestamp(element, compiler, **kw):
    """Return the Postgres or MySQL function call to get the current DB
    server time

    :param element:  The element being construct
    :param compiler:  The compiler for postgresql
    :param kw:  Any additional argument
    :return: Postgres or MySQL function name for generating current timestamp
    """
    # Unused variable
    # pylint: disable=W0613
    return "CURRENT_TIMESTAMP"

Base = declarative.declarative_base()

# Naming convention for SQLAlchemy to auto generate the constrain name to
# have a predictable name.  Important for referencing constrains by name
# (e.g. alembic downgrade script).
Base.metadata.naming_convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"}

metadata = Base.metadata

# Default session
session = sessionmaker()()

class Device(Base):
    """device table"""
    __tablename__ = 'device'

    device_id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    device_type = Column(String(64), nullable=False)
    properties = Column(JSONB)
    hostname = Column(String(256))
    ip_address = Column(String(64))
    mac_address = Column(String(64))
    profile_name = Column(String(128))
    deleted = Column(BOOLEAN, nullable=False, default=False)

class Configuration(Base):
    """configuration table"""
    __tablename__ = 'configuration'

    key = Column(String(128), primary_key=True, nullable=False)
    value = Column(String(1024))

class Log(Base):
    """log table"""
    __tablename__ = 'log'
    process = Column(String(128))
    timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now, primary_key=True)
    level = Column(Integer, nullable=False)
    device_id = Column(Integer, ForeignKey('device.device_id'))
    message = Column(Text, nullable=False)

class Profile(Base):
    """profile table"""
    __tablename__ = 'profile'

    profile_name = Column(String(128), primary_key=True)
    properties = Column(JSONB, nullable=False)

class Sku(Base):
    """sku table"""
    __tablename__ = 'sku'

    device_id = Column(Integer, ForeignKey('device.device_id', onupdate="CASCADE", ondelete="CASCADE"), nullable=False,
                       primary_key=True)
    sku_name = Column(String(256), nullable=False, primary_key=True)
    step = Column(String(128))
    hardware_type = Column(String(256))
    model_number = Column(Integer)
    sys_period = Column(DateTime, nullable=False, default=datetime.datetime.now)

class SkuHistory(Base):
    """sku_history table"""
    __tablename__ = 'sku_history'
    device_id = Column(Integer, nullable=False, primary_key=True)
    sku_name = Column(String(256), nullable=False, primary_key=True)
    step = Column(String(128))
    hardware_type = Column(String(256))
    model_number = Column(Integer)
    sys_period = Column(DateTime, nullable=False, primary_key=True)

def setup(alembic_ini="schema_migration.ini"):
    """Setup all SQLAlchemy sessions and connections

    :param db_url: The database URL as required by SQLAlchemy
    :param alembic_ini: Alembic config file
    :return: None
    """
    alembic_conf = Config(alembic_ini)
    db_url = alembic_conf.get_section_option("alembic", "sqlalchemy.url")
    print(db_url)
    if not db_url:
        db_url = os.getenv("PG_DB_URL")
    if not db_url:
        raise RuntimeError("The db_url is not in the kwarg nor in the alembic_ini file.")
    sqlalchemy_db_url = sa.engine.url.make_url(db_url)

    print("-" * 50)
    msg = ("Connecting to '%s' database on %s server at '%s'" % (
        sqlalchemy_db_url.database,
        sqlalchemy_db_url.get_dialect().name.upper(),
        sqlalchemy_db_url.host))
    print(msg)
    engine = create_engine(db_url)
    Base.metadata.bind = engine
    # Base.metadata.bind.echo = True   # Log the SQL interaction.
    msg = (engine.execute("select 'Connected to %s database'" %
                          sqlalchemy_db_url.database).scalar())
    print(msg)
    msg = ("Established connection to '%s' database" %
           sqlalchemy_db_url.database)
    print(msg)

    print("-" * 50)
    print("Starting Alembic upgrade database to latest version")
    command.upgrade(alembic_conf, "head", tag=db_url)
    print("Completed running Alembic command")
    print("-" * 50)

if __name__ == "__main__":
    import pprint
    setup()
    dummy_query = session.query(Device).limit(10)
    print("Sample list of  Device")
    print(pprint.pformat(dummy_query.all()))


text:
def dloader(url,stylenum,imgnum):
	import os, sys, requests, re
	regex=re.compile(r'^(http://.*?)\?dl\=\d{1,2}.*?$')
	urlget = url
	localpath = os.path.join('/Users/johnb/Pictures', stylenum+ '_'+imgnum+'.jpg')
	import subprocess
	subprocess.call(['wget', url, '-o',localpath])
	if regex.findall(urlget):
		regexfnd=regex.findall(urlget)
		print regexfnd,'<--REGEX-FOUND--'
		res = requests.get(urlget, stream=True, timeout=5)
		with __builtin__.open(localpath, 'wb+') as f:
		    f.write(res.content)
		    f.close()
	else:
		pass
	return

if __name__ == '__main__':
	dloader()


text:
package com.bwsw.tstreams.agents.integration

import java.util.concurrent.{CountDownLatch, TimeUnit}

import com.bwsw.tstreams.agents.consumer.Offset.Newest
import com.bwsw.tstreams.agents.consumer.{ConsumerTransaction, TransactionOperator}
import com.bwsw.tstreams.testutils.{TestStorageServer, TestUtils}
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import scala.collection.mutable.ListBuffer

/**
  * Created by Ivan Kudryavtsev on 14.04.17.
  */
class SubscriberTransactionPartitionDistributionTest extends FlatSpec with Matchers with BeforeAndAfterAll with TestUtils {
  val PARTITIONS_COUNT = 4

  lazy val srv = TestStorageServer.getNewClean()

  override def beforeAll(): Unit = {
    srv
    createNewStream(partitions = PARTITIONS_COUNT)
  }

  it should "ensure that transactions are distributed to the same partitions on producer and subscriber" in {
    val TRANSACTION_COUNT = 1000

    val accumulatorBuilder = () => (0 until PARTITIONS_COUNT).map(_ => ListBuffer[Long]()).toArray
    val producerTransactionsAccumulator = accumulatorBuilder()
    val subscriberTransactionsAccumulator = accumulatorBuilder()
    var counter = 0
    val subscriberLatch = new CountDownLatch(1)

    val producer = f.getProducer(
      name = "test_producer",
      partitions = (0 until PARTITIONS_COUNT).toSet)

    val subscriber = f.getSubscriber(name = "sv2",
      partitions = (0 until PARTITIONS_COUNT).toSet,
      offset = Newest,
      useLastOffset = false,
      callback = (consumer: TransactionOperator, transaction: ConsumerTransaction) => this.synchronized {
        subscriberTransactionsAccumulator(transaction.getPartition).append(transaction.getTransactionID)
        counter += 1
        if (counter == TRANSACTION_COUNT)
          subscriberLatch.countDown()
      })
    subscriber.start()
    (0 until TRANSACTION_COUNT).foreach(_ => {
      val t = producer.newTransaction()
      t.send("test".getBytes())
      t.checkpoint()
      producerTransactionsAccumulator(t.getPartition).append(t.getTransactionID)
    })

    subscriberLatch.await(30, TimeUnit.SECONDS) shouldBe true
    (0 until PARTITIONS_COUNT).foreach(partition =>
      subscriberTransactionsAccumulator(partition) shouldBe producerTransactionsAccumulator(partition))

    subscriber.stop()
    producer.stop()
  }

  override def afterAll(): Unit = {
    onAfterAll()
    TestStorageServer.dispose(srv)
  }
}


text:
import calendar
from bson import ObjectId
from datetime import datetime

from modularodm import fields, Q

from framework.mongo import StoredObject
from framework.guid.model import GuidStoredObject

from website.settings import DOMAIN
from website.util import web_url_for, api_url_for
from website.addons.badges.util import acquire_badge_image

class Badge(GuidStoredObject):

    redirect_mode = 'proxy'

    _id = fields.StringField(primary=True)

    creator = fields.ForeignField('badgesusersettings', backref='creator')

    is_system_badge = fields.BooleanField(default=False)

    #Open Badge protocol
    name = fields.StringField()
    description = fields.StringField()
    image = fields.StringField()
    criteria = fields.StringField()

    #TODO implement tags and alignment
    alignment = fields.DictionaryField(list=True)
    tags = fields.StringField(list=True)

    @classmethod
    def get_system_badges(cls):
        return cls.find(Q('is_system_badge', 'eq', True))

    @classmethod
    def create(cls, user_settings, badge_data, save=True):
        badge = cls()
        badge.creator = user_settings
        badge.name = badge_data['badgeName']
        badge.description = badge_data['description']
        badge.criteria = badge_data['criteria']
        badge._ensure_guid()
        badge.image = acquire_badge_image(badge_data['imageurl'], badge._id)
        if not badge.image:
            raise IOError
        if save:
            badge.save()
        return badge

    @property
    def description_short(self):
        words = self.description.split(' ')
        if len(words) < 9:
            return ' '.join(words)
        return '{}...'.format(' '.join(words[:9]))

    #TODO Auto link urls?
    @property
    def criteria_list(self):
        tpl = '
{}
'
        stpl = '
{}
'
        lines = self.criteria.split('\n')
        return tpl.format(' '.join([stpl.format(line) for line in lines if line]))  # Please dont kill me Steve

    @property
    def assertions(self):
        return self.badgeassertion__assertion

    @property
    def awarded_count(self):
        return len(self.assertions)

    @property
    def unique_awards_count(self):
        return len({assertion.node._id for assertion in self.assertions})

    @property
    def deep_url(self):
        return web_url_for('view_badge', bid=self._id)

    @property
    def url(self):
        return web_url_for('view_badge', bid=self._id)

    def make_system_badge(self, save=True):
        self.is_system_badge = True
        self.save()

    def to_json(self):
        return {
            'id': self._id,
            'name': self.name,
            'description': self.description,
            'image': self.image,
            'criteria': self.criteria,
            'alignment': self.alignment,
            'tags': self.tags,
        }

    def to_openbadge(self):
        return {
            'name': self.name,
            'description': self.description,
            'image': self.image,
            'criteria': self.criteria,
            'issuer': api_url_for('get_organization_json', _absolute=True, uid=self.creator.owner._id),
            'url': '{0}{1}/json/'.format(DOMAIN, self._id),  # web url for and GUIDs?
            'alignment': self.alignment,
            'tags': self.tags,
        }

#TODO verification hosted and signed
class BadgeAssertion(StoredObject):

    _id = fields.StringField(default=lambda: str(ObjectId()))

    #Backrefs
    badge = fields.ForeignField('badge', backref='assertion')
    node = fields.ForeignField('node', backref='awarded')
    _awarder = fields.ForeignField('badgesusersettings')

    #Custom fields
    revoked = fields.BooleanField(default=False)
    reason = fields.StringField()

    #Required
    issued_on = fields.IntegerField(required=True)

    #Optional
    evidence = fields.StringField()
    expires = fields.StringField()

    @classmethod
    def create(cls, badge, node, evidence=None, save=True, awarder=None):
        b = cls()
        b.badge = badge
        b.node = node
        b.evidence = evidence
        b.issued_on = calendar.timegm(datetime.utctimetuple(datetime.utcnow()))
        b._awarder = awarder
        if save:
            b.save()
        return b

    @property
    def issued_date(self):
        return datetime.fromtimestamp(self.issued_on).strftime('%Y/%m/%d')

    @property
    def verify(self, vtype='hosted'):
        return {
            'type': 'hosted',
            'url': api_url_for('get_assertion_json', _absolute=True, aid=self._id)
        }

    @property
    def recipient(self):
        return {
            'idenity': self.node._id,
            'type': 'osfnode',  # TODO Could be an email?
            'hashed': False
        }

    @property
    def awarder(self):
        if self.badge.is_system_badge and self._awarder:
            return self._awarder
        return self.badge.creator

    def to_json(self):
        return {
            'uid': self._id,
            'recipient': self.node._id,
            'badge': self.badge._id,
            'verify': self.verify,
            'issued_on': self.issued_date,
            'evidence': self.evidence,
            'expires': self.expires
        }

    def to_openbadge(self):
        return {
            'uid': self._id,
            'recipient': self.recipient,
            'badge': '{}{}/json/'.format(DOMAIN, self.badge._id),  # GUIDs Web url for
            'verify': self.verify,
            'issuedOn': self.issued_on,
            'evidence': self.evidence,
            'expires': self.expires
        }


text:
package zame.game.engine.data;

class Common {
	public static final String SIGNATURE = "GloomyDungeonsII";
	public static final int INITIAL_SIGNATURE_VALUE = 90657769;
	public static final short MARKER_END = -1;
	public static final int MASK_ARRAY = 0xC000;
	public static final int SHIFT_ARRAY = 14;
	public static final int MASK_TYPE = 0x3C00;
	public static final int SHIFT_TYPE = 10;
	public static final int MASK_FIELD_ID = 0x03FF;
	public static final int ARRAY_1D = 1;
	public static final int ARRAY_2D = 2;
	public static final int ARRAY_2DV = 3;
	public static final int TYPE_OBJECT = 0;
	public static final int TYPE_BYTE = 1;
	public static final int TYPE_SHORT = 2;
	public static final int TYPE_INT = 3;
	public static final int TYPE_LONG = 4;
	public static final int TYPE_FLOAT = 5;
	public static final int TYPE_DOUBLE = 6;
	public static final int TYPE_BOOLEAN = 7;
	public static final int TYPE_CHAR = 8;
	public static final int TYPE_STRING = 9;
	public static final int TYPE_NULL = 10;
}


text:
/* globals CodeTestBotAppENV */

import Ember from 'ember';
import { defineFixture } from 'ic-ajax';

defineFixture(CodeTestBotAppENV.NEW_SESSION_URL + '?redirect_uri=' + CodeTestBotAppENV.APP_HOST + '/auth/complete', {
    response: {auth_uri: 'testing_uri'},
    jqXHR: {},
    textStatus: 'success'
});

defineServerFixture('/users', {
    users: [
        { id: 1, name: 'User1', editable: true, role_id: 1 },
        { id: 2, name: 'User2', editable: false, role_id: 3 }
    ],
    roles: [
        { id: 1, name: 'Assessor' },
        { id: 3, name: 'Administrator' }
    ]
});
defineServerFixture('/users/1', {
    user: { id: 1, name: 'User1', editable: true, role_id: 1 },
    roles: [{ id: 1, name: 'Assessor' }]
});
defineServerFixture('/users/2', {
    user: { id: 2, name: 'User2', editable: false, role_id: 3 },
    roles: [{ id: 3, name: 'Administrator' }]
});

defineServerFixture('/roles/1', {
    role: { id: 1, name: 'Assessor' }
});
defineServerFixture('/roles/3', {
    role: { id: 3, name: 'Administrator' }
});

defineServerFixture('/languages', { languages: [
    { id: 1, name: 'Java' },
    { id: 2, name: 'Ruby' }
]});
defineServerFixture('/languages/1', { language: { id: 1, name: 'Java' } });
defineServerFixture('/languages/2', { language: { id: 2, name: 'Ruby' } });

defineServerFixture('/levels', { levels: [
    { id: 1, text: 'Junior' },
    { id: 2, text: 'Mid' },
    { id: 3, text: 'Senior' },
    { id: 4, text: 'Tech Lead' }
]});
defineServerFixture('/levels/1', { level: { id: 1, text: 'Junior' } });
defineServerFixture('/levels/2', { level: { id: 2, text: 'Mid' } });

defineServerFixture('/submissions', {
    submissions: [{id: 1}]
});
defineServerFixture('/submissions/1', {
    submission: {
        id: 1,
        candidate_name: 'Candi Date',
        candidate_email: 'Candidate1',
        level_id: 1,
        email_text: 'some text',
        zipfile: 'url to file',
        language_id: 1,
        source: 'LinkedIn'
    },
    levels: [
        { id: 1, text: 'Junior' }
    ],
    languages: [
        { id: 1, name: 'Java' }
    ]
});

defineServerFixture('/assessors/2', {
    assessor: { id: 2, name: 'Assessor2' }
});
defineServerFixture('/assessors/3', {
    assessor: { id: 3, name: 'Assessor3' }
});

function defineServerFixture(path, response, options) {
    options = Ember.merge({ jqXHR: {}, textStatus: 'success' }, options);
    options.response = response;

    defineFixture(CodeTestBotAppENV.SERVER_HOST + path, options);
}

export {
    defineServerFixture
};

export default {};


text:
"""
Simple Scatter Plot with Tooltips
---------------------------------

A simple example of an interactive scatter plot using the well-known iris
dataset, with tooltips that show the species name when the mouse hovers
over each point.
"""
# category: simple charts

import altair as alt
from vega_datasets import data

iris = data.iris()

alt.Chart(iris).mark_point().encode(
    x='petalWidth',
    y='petalLength',
    color='species',
    tooltip='species'
).interactive()


text:
module.exports = Backbone.Marionette.Controller.extend({
  initialize: function(app) {
    this.app = app;

    $(document).ajaxStart($.proxy(this.show, this));
    $(document).ajaxStop($.proxy(this.hide, this));
  },

  show: function() {
    $(this.app.loader.el).stop().fadeIn(200);
  },

  hide: function() {
    $(this.app.loader.el).stop().fadeOut(200);
  }
})


text:
import logging
import pytz
import attrdict as ad
import copy

import emission.core.wrapper.sensorconfig as ecws
import emission.net.usercache.formatters.common as fc

# Currently, we just reflect this back to the user, so not much editing to do
# here. Since we get the timezone from javascript guessing, though, let's just
# verify that it is correct.
def format(entry):
    formatted_entry = ad.AttrDict()

    metadata = entry.metadata
    try:
        valid_tz = pytz.timezone(entry.metadata.time_zone)
    except UnknownTimeZoneError, e:
        logging.warn("Got error %s while checking format validity" % e)
        # Default timezone in for the Bay Area, which is probably a fairly safe
        # assumption for now
        metadata.time_zone = "America/Los_Angeles"
    # adds the python datetime and fmt_time entries. important for future searches!
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    formatted_entry.data = entry.data

    return formatted_entry;


text:
<?php
$avisos = $app['controllers_factory'];
$avisos->get('/', function () use ($app) {
    //$avisos = $app['db']->fetchAssoc('SELECT * FROM  WHERE id = ?', array('112'));;

    return $app['twig']->render('avisos.html', array());
})
->bind('avisos');

$avisos->match('/{id}/json/', function ($id) use ($app) {
    $avisos = $app['db']->fetchAll('SELECT * FROM tavisos WHERE idcomunidad = ?', array($id));

    return $app->json($avisos);
})
->bind('avisos_json')
->assert('id', '\d+'); //nos aseguramos que nos pasan un decimal

return $avisos

?>


text:
package process

import (
	"os"
	"os/exec"
	"os/user"
	"strconv"
	"strings"
	"syscall"
)

// POSIX
func getTerminalMap() (map[uint64]string, error) {
	ret := make(map[uint64]string)
	var termfiles []string

	d, err := os.Open("/dev")
	if err != nil {
		return nil, err
	}
	defer d.Close()

	devnames, err := d.Readdirnames(-1)
	for _, devname := range devnames {
		if strings.HasPrefix(devname, "/dev/tty") {
			termfiles = append(termfiles, "/dev/tty/"+devname)
		}
	}

	ptsd, err := os.Open("/dev/pts")
	if err != nil {
		return nil, err
	}
	defer ptsd.Close()

	ptsnames, err := ptsd.Readdirnames(-1)
	for _, ptsname := range ptsnames {
		termfiles = append(termfiles, "/dev/pts/"+ptsname)
	}

	for _, name := range termfiles {
		stat := syscall.Stat_t{}
		if err = syscall.Stat(name, &stat); err != nil {
			return nil, err
		}
		rdev := uint64(stat.Rdev)
		ret[rdev] = strings.Replace(name, "/dev", "", -1)
	}
	return ret, nil
}

func (p *Process) SendSignal(sig syscall.Signal) error {
	sigAsStr := "INT"
	switch sig {
	case syscall.SIGSTOP:
		sigAsStr = "STOP"
	case syscall.SIGCONT:
		sigAsStr = "CONT"
	case syscall.SIGTERM:
		sigAsStr = "TERM"
	case syscall.SIGKILL:
		sigAsStr = "KILL"
	}

	cmd := exec.Command("kill", "-s", sigAsStr, strconv.Itoa(int(p.Pid)))
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		return err
	}

	return nil
}

func (p *Process) Suspend() error {
	return p.SendSignal(syscall.SIGSTOP)
}
func (p *Process) Resume() error {
	return p.SendSignal(syscall.SIGCONT)
}
func (p *Process) Terminate() error {
	return p.SendSignal(syscall.SIGTERM)
}
func (p *Process) Kill() error {
	return p.SendSignal(syscall.SIGKILL)
}
func (p *Process) Username() (string, error) {
	uids, err := p.Uids()
	if err != nil {
		return "", err
	}
	if len(uids) > 0 {
		u, err := user.LookupId(strconv.Itoa(int(uids[0])))
		if err != nil {
			return "", err
		}
		return u.Username, nil
	}
	return "", nil
}


text:
'use strict';

// do nothing.


text:
        this is main section for admin

			<api></api>

			<ce-table-access></ce-table-access>


text:
package orwir.starter.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.util.Pair;
import android.view.View;

public class OpenUtils {

    @SafeVarargs
    public static void startWithTransition(@NonNull Context context, @NonNull Intent intent, @Nullable Pair<View, String>... sharedElements) {
        if (context instanceof Activity) {
            startWithTransition(context, intent, sharedElements);
        } else {
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public static void startWithTransition(@NonNull Context context, @NonNull Intent intent, int enterAnim, int exitAnim) {
        if (context instanceof Activity) {
            startWithTransition(context, intent, enterAnim, exitAnim);
        } else {
            context.startActivity(intent);
        }
    }

    public static void startWithTransition(@NonNull Activity caller, @NonNull Intent intent, int enterAnim, int exitAnim) {
        try {
            caller.startActivity(intent, ActivityOptionsCompat.makeCustomAnimation(caller, enterAnim, exitAnim).toBundle());
        } catch (Exception e) {
            caller.startActivity(intent);
        }
    }

    /*@SafeVarargs
    public static void startWithTransition(@NonNull Activity caller, @NonNull Intent intent, @Nullable Pair<View, String>... sharedElements) {
        try {
            caller.startActivity(intent, ActivityOptionsCompat.makeSceneTransitionAnimation(caller, sharedElements).toBundle());
        } catch (Exception e) {
            caller.startActivity(intent);
        }
    }*/

    private OpenUtils() {}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using LudumDare24.Models.Doodads;

namespace LudumDare24.Models.Boards
{
    public class BoardPacker
    {
        private readonly int numberOfColumns;
        private readonly int numberOfRows;

        public BoardPacker(int numberOfColumns, int numberOfRows)
        {
            this.numberOfColumns = numberOfColumns;
            this.numberOfRows = numberOfRows;
        }

        public void Pack(IEnumerable<IDoodad> doodads, float rotation)
        {
            float cos = (float)Math.Cos(rotation);
            float sin = (float)Math.Sin(rotation);
            int acrossStart;
            int acrossEnd;
            int acrossDelta;
            int downStart;
            int downEnd;
            int downDelta;
            Func<int, int, IDoodad> doodadFetcher;
            Action<IDoodad, int> doodadMover;

            if (Math.Abs(cos) == 1)
            {
                doodadFetcher =
                    (column, row) =>
                    doodads.FirstOrDefault(doodad => doodad.Column == column && doodad.Row == row);
                if (Math.Sign(cos) > 0)
                {
                    acrossStart = 0;
                    acrossEnd = this.numberOfColumns - 1;
                    acrossDelta = 1;
                    downStart = this.numberOfRows - 1;
                    downEnd = 0;
                    downDelta = -1;
                    doodadMover = (doodad, delta) => doodad.Row += delta;
                }
                else
                {
                    acrossStart = this.numberOfColumns - 1;
                    acrossEnd = 0;
                    acrossDelta = -1;
                    downStart = 0;
                    downEnd = this.numberOfRows - 1;
                    downDelta = 1;
                    doodadMover = (doodad, delta) => doodad.Row -= delta;
                }
            }
            else
            {
                doodadFetcher =
                    (column, row) =>
                    doodads.FirstOrDefault(doodad => doodad.Column == row && doodad.Row == column);
                if (Math.Sign(sin) > 0)
                {
                    acrossStart = 0;
                    acrossEnd = this.numberOfRows - 1;
                    acrossDelta = 1;
                    downStart = this.numberOfColumns - 1;
                    downEnd = 0;
                    downDelta = -1;
                    doodadMover = (doodad, delta) => doodad.Column += delta;
                }
                else
                {
                    acrossStart = this.numberOfRows - 1;
                    acrossEnd = 0;
                    acrossDelta = -1;
                    downStart = 0;
                    downEnd = this.numberOfColumns - 1;
                    downDelta = 1;
                    doodadMover = (doodad, delta) => doodad.Column -= delta;
                }
            }

            this.PushDown(
                acrossStart,
                acrossEnd,
                acrossDelta,
                downStart,
                downEnd,
                downDelta,
                doodadFetcher,
                doodadMover);

            this.PullDown(
                acrossStart,
                acrossEnd,
                acrossDelta,
                downEnd,
                downStart,
                -downDelta,
                doodadFetcher,
                doodadMover);
        }

        private void PullDown(
            int acrossStart,
            int acrossEnd,
            int acrossDelta,
            int downStart,
            int downEnd,
            int downDelta,
            Func<int, int, IDoodad> doodadFetcher,
            Action<IDoodad, int> doodadMover)
        {
            for (int column = acrossStart; column != (acrossEnd + acrossDelta); column += acrossDelta)
            {
                int depth = 0;
                for (int row = downStart; row != (downEnd + downDelta); row += downDelta)
                {
                    IDoodad doodad = doodadFetcher(column, row);
                    if (doodad == null)
                    {
                        depth++;
                    }
                    else
                    {
                        if (depth > 0 && doodad.FallingState == FallingState.Up)
                        {
                            doodadMover(doodad, -depth);
                        }
                        else
                        {
                            depth = 0;
                        }
                    }
                }
            }
        }

        private void PushDown(
            int acrossStart,
            int acrossEnd,
            int acrossDelta,
            int downStart,
            int downEnd,
            int downDelta,
            Func<int, int, IDoodad> doodadFetcher,
            Action<IDoodad, int> doodadMover)
        {
            for (int column = acrossStart; column != (acrossEnd + acrossDelta); column += acrossDelta)
            {
                int depth = 0;
                for (int row = downStart; row != (downEnd + downDelta); row += downDelta)
                {
                    IDoodad doodad = doodadFetcher(column, row);
                    if (doodad == null)
                    {
                        depth++;
                    }
                    else
                    {
                        if (depth > 0 && doodad.FallingState == FallingState.Down)
                        {
                            doodadMover(doodad, depth);
                        }
                        else
                        {
                            depth = 0;
                        }
                    }
                }
            }
        }
    }
}


text:
package com.codemelon.graph.edge;

/**
 * Requires that an EdgeData object maintain a floating point weight value.
 * @author Marshall Farrier
 * @my.created Dec 20, 2012
 * @my.edited Dec 20, 2012
 */
public interface EdgeWeightData {
	/**
	 * Default edge weight to which edges are initialized if not otherwise specified.
	 */
	public static final double DEFAULT_EDGE_WEIGHT = 1.0;
	/**
	 * Set the weight contained in this EdgeData object
	 * @param weight value to which to set the weight
	 */
	public void setWeight(double weight);
	/**
	 * Retrieve the weight contained in this EdgeData object
	 * @return weight stored in this EdgeData object
	 */
	public double getWeight();
}


text:
module FormationHelper
end


text:
package dab.server.world.tile;

import dab.common.physics.AABB;

public class SolidTile extends Tile
{
	public SolidTile()
	{
		super();

		setName("dab:tile:solid");
		setBoundingBox(new AABB(0.5f, 0.5f, 1.0f, 1.0f));
		setSolid(true);
	}
}


text:
package org.hoteia.qalingo.web.mvc.controller;

import javax.servlet.http.HttpServletRequest;

import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.enumtype.FoUrls;
import org.hoteia.qalingo.core.pojo.RequestData;
import org.hoteia.qalingo.core.service.GeolocService;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.hoteia.qalingo.core.web.servlet.view.RedirectView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;

/**
 *
 */
@Controller("homeController")
public class HomeController extends AbstractPrehomeController {

    @Autowired
    protected GeolocService geolocService;

	@RequestMapping(FoUrls.PREHOME_URL)
	public ModelAndView displayHome(final HttpServletRequest request, final Model model) throws Exception {
		ModelAndViewThemeDevice modelAndView = new ModelAndViewThemeDevice(getCurrentVelocityPath(request), FoUrls.PREHOME.getVelocityPage());

		final String remoteAddress = requestUtil.getRemoteAddr(request);
        model.addAttribute(ModelConstants.GEOLOC_REMOTE_ADDRESS, remoteAddress);

		final Country country = geolocService.geolocAndGetCountry(remoteAddress);
        model.addAttribute(ModelConstants.GEOLOC_COUNTRY, country);

        final City city = geolocService.geolocAndGetCity(remoteAddress);
        model.addAttribute(ModelConstants.GEOLOC_CITY, city);

        overrideDefaultMainContentTitle(request, modelAndView, FoUrls.PREHOME.getKey());

        return modelAndView;
	}

	@RequestMapping(FoUrls.INDEX_URL)
	public ModelAndView displayIndex(final HttpServletRequest request, final Model model) throws Exception {
        return displayHome(request, model);
	}

    @RequestMapping("/")
    public ModelAndView displayDefaultPage(final HttpServletRequest request, final Model model) throws Exception {

        // DEFAULT HOME
        RequestData requestData = requestUtil.getRequestData(request);
        String defaultUrl = urlService.generateUrl(FoUrls.PREHOME, requestData);

        // TODO: GEOLOC AND CHOOSE THE GOOD MARKET

        return new ModelAndView(new RedirectView(defaultUrl));
    }

	/**
	 *
	 */
	@ModelAttribute
	protected void initMarketPlaces(final HttpServletRequest request, final Model model) throws Exception {
		// Markets
        RequestData requestData = requestUtil.getRequestData(request);
		model.addAttribute(ModelConstants.MARKET_PLACES_VIEW_BEAN, frontofficeViewBeanFactory.buildListViewBeanMarketPlace(requestData));
	}

}


text:
package org.infinispan.loaders.jdbc.mixed;

import org.infinispan.loaders.BaseCacheStoreFunctionalTest;
import org.infinispan.loaders.CacheStoreConfig;
import org.infinispan.loaders.jdbc.TableManipulation;
import org.infinispan.loaders.jdbc.connectionfactory.ConnectionFactoryConfig;
import org.infinispan.test.fwk.UnitTestDatabaseManager;
import org.testng.annotations.Test;

@Test(groups = "functional", testName = "loaders.jdbc.mixed.JdbcMixedCacheStoreFunctionalTest")
public class JdbcMixedCacheStoreFunctionalTest extends BaseCacheStoreFunctionalTest {

   @Override
   protected CacheStoreConfig createCacheStoreConfig() throws Exception {
      TableManipulation stringsTm = UnitTestDatabaseManager.buildStringTableManipulation();
      stringsTm.setTableNamePrefix("STRINGS_TABLE");
      TableManipulation binaryTm = UnitTestDatabaseManager.buildBinaryTableManipulation();
      binaryTm.setTableNamePrefix("BINARY_TABLE");
      ConnectionFactoryConfig cfc = UnitTestDatabaseManager.getUniqueConnectionFactoryConfig();
      JdbcMixedCacheStoreConfig jdbcCacheStoreConfig = new JdbcMixedCacheStoreConfig(cfc, binaryTm, stringsTm);
      jdbcCacheStoreConfig.setConnectionFactoryConfig(cfc);
      jdbcCacheStoreConfig.setStringsTableManipulation(stringsTm);
      jdbcCacheStoreConfig.setBinaryTableManipulation(binaryTm);
      return jdbcCacheStoreConfig;
   }

}


text:
package gosnmp

import (
	crand "crypto/rand"
	"encoding/binary"
	"fmt"
	"math/big"
	"math/rand"
	"net"
	"strconv"
	"time"
)

const (
	// maxOids is the maximum number of oids allowed in a Get()
	maxOids = 60

	// Base OID for MIB-2 defined SNMP variables
	baseOid = ".1.3.6.1.2.1"

	// Java SNMP uses 50, snmp-net uses 10
	defaultMaxRepetitions = 50
)

// LoggingDisabled is set if the Logger is nil, short circuits any 'slog' calls
var LoggingDisabled bool

// GoSNMP represents GoSNMP library state
type GoSNMP struct {

	// Target is an ipv4 address
	Target string

	// Port is a udp port
	Port uint16

	// Version is an SNMP Version
	Version SnmpVersion

	// Community is an SNMP Community string
	Community string

	// MsgFlags is an SNMPV3 MsgFlags
	MsgFlags SnmpV3MsgFlags

	// SecurityModel is an SNMPV3 Security Model
	SecurityModel SnmpV3SecurityModel

	// SecurityParameters is an SNMPV3 Security Model paramaters struct
	SecurityParameters SnmpV3SecurityParameters

	// ContextEngineID is SNMPV3 ContextEngineID in ScopedPDU
	ContextEngineID string

	// ContextName is SNMPV3 ContextName in ScopedPDU
	ContextName string

	// Timeout is the timeout for the SNMP Query
	Timeout time.Duration

	// Set the number of retries to attempt within timeout.
	Retries int

	// Conn is net connection to use, typically establised using GoSNMP.Connect()
	Conn net.Conn

	// Logger is the GoSNMP.Logger to use for debugging. If nil, debugging
	// output will be discarded (/dev/null). For verbose logging to stdout:
	// x.Logger = log.New(os.Stdout, "", 0)
	Logger Logger

	// MaxRepititions sets the GETBULK max-repetitions used by BulkWalk*
	// (default: 50)
	MaxRepetitions int

	// NonRepeaters sets the GETBULK max-repeaters used by BulkWalk*
	// (default: 0 as per RFC 1905)
	NonRepeaters int

	// Internal - used to sync requests to responses
	requestID uint32
	random    *rand.Rand

	// Internal - used to sync requests to responses - snmpv3
	msgID uint32
}

// The default connection settings
var Default = &GoSNMP{
	Port:      161,
	Community: "public",
	Version:   Version2c,
	Timeout:   time.Duration(2) * time.Second,
	Retries:   3,
}

// SnmpPDU will be used when doing SNMP Set's
type SnmpPDU struct {

	// Name is an oid in string format eg ".1.3.6.1.4.9.27"
	Name string

	// The type of the value eg Integer
	Type Asn1BER

	// The value to be set by the SNMP set
	Value interface{}
}

// Asn1BER is the type of the SNMP PDU
type Asn1BER byte

// Asn1BER's - http://www.ietf.org/rfc/rfc1442.txt
const (
	EndOfContents     Asn1BER = 0x00
	UnknownType               = 0x00 // TODO these should all be type Asn1BER, however
	Boolean                   = 0x01 // tests fail if implemented. See for example
	Integer                   = 0x02 /// http://stackoverflow.com/questions/5037610/typed-constant-declaration-list.
	BitString                 = 0x03
	OctetString               = 0x04
	Null                      = 0x05
	ObjectIdentifier          = 0x06
	ObjectDescription         = 0x07
	IPAddress                 = 0x40
	Counter32                 = 0x41
	Gauge32                   = 0x42
	TimeTicks                 = 0x43
	Opaque                    = 0x44
	NsapAddress               = 0x45
	Counter64                 = 0x46
	Uinteger32                = 0x47
	NoSuchObject              = 0x80
	NoSuchInstance            = 0x81
	EndOfMibView              = 0x82
)

//
// Public Functions (main interface)
//

// Connect initiates a connection to the target host
func (x *GoSNMP) Connect() error {
	if x.Logger == nil {
		LoggingDisabled = true
	}
	addr := net.JoinHostPort(x.Target, strconv.Itoa(int(x.Port)))
	var err error
	x.Conn, err = net.DialTimeout("udp", addr, x.Timeout)
	if err != nil {
		return fmt.Errorf("Error establishing connection to host: %s\n", err.Error())
	}
	if x.random == nil {
		x.random = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
	}
	// http://tools.ietf.org/html/rfc3412#section-6 - msgID only
	// uses the first 31 bits
	// msgID INTEGER (0..2147483647)
	x.msgID = uint32(x.random.Int31())
	// RequestID is Integer32 from SNMPV2-SMI and uses all 32 bits
	x.requestID = x.random.Uint32()

	if x.Version == Version3 {
		x.MsgFlags |= Reportable // tell the snmp server that a report PDU MUST be sent
		if x.SecurityModel == UserSecurityModel {
			secParams, ok := x.SecurityParameters.(*UsmSecurityParameters)
			if !ok || secParams == nil {
				return fmt.Errorf("&GoSNMP.SecurityModel indicates the User Security Model, but &GoSNMP.SecurityParameters is not of type &UsmSecurityParameters")
			}
			switch secParams.PrivacyProtocol {
			case AES:
				salt := make([]byte, 8)
				_, err = crand.Read(salt)
				if err != nil {
					return fmt.Errorf("Error creating a cryptographically secure salt: %s\n", err.Error())
				}
				secParams.localAESSalt = binary.BigEndian.Uint64(salt)
			case DES:
				salt := make([]byte, 4)
				_, err = crand.Read(salt)
				if err != nil {
					return fmt.Errorf("Error creating a cryptographically secure salt: %s\n", err.Error())
				}
				secParams.localDESSalt = binary.BigEndian.Uint32(salt)
			}
		}
	}

	return nil
}

func (x *GoSNMP) mkSnmpPacket(pdutype PDUType, nonRepeaters uint8, maxRepetitions uint8) *SnmpPacket {
	var newSecParams SnmpV3SecurityParameters
	if x.SecurityParameters != nil {
		newSecParams = x.SecurityParameters.Copy()
	}
	return &SnmpPacket{
		Version:            x.Version,
		Community:          x.Community,
		MsgFlags:           x.MsgFlags,
		SecurityModel:      x.SecurityModel,
		SecurityParameters: newSecParams,
		ContextEngineID:    x.ContextEngineID,
		ContextName:        x.ContextName,
		Error:              0,
		ErrorIndex:         0,
		PDUType:            pdutype,
		NonRepeaters:       nonRepeaters,
		MaxRepetitions:     maxRepetitions,
	}
}

// Get sends an SNMP GET request
func (x *GoSNMP) Get(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}
	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}
	// build up SnmpPacket
	packetOut := x.mkSnmpPacket(GetRequest, 0, 0)
	return x.send(pdus, packetOut)
}

// Set sends an SNMP SET request
func (x *GoSNMP) Set(pdus []SnmpPDU) (result *SnmpPacket, err error) {
	if pdus[0].Type != Integer || pdus[0].Type != OctetString {
		return nil, fmt.Errorf("ERR:gosnmp currently only supports SNMP SETs for Integers and OctetStrings")
	}
	// build up SnmpPacket
	packetOut := x.mkSnmpPacket(SetRequest, 0, 0)
	return x.send(pdus, packetOut)
}

// GetNext sends an SNMP GETNEXT request
func (x *GoSNMP) GetNext(oids []string) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := x.mkSnmpPacket(GetNextRequest, 0, 0)

	return x.send(pdus, packetOut)
}

// GetBulk sends an SNMP GETBULK request
func (x *GoSNMP) GetBulk(oids []string, nonRepeaters uint8, maxRepetitions uint8) (result *SnmpPacket, err error) {
	oidCount := len(oids)
	if oidCount > maxOids {
		return nil, fmt.Errorf("oid count (%d) is greater than maxOids (%d)",
			oidCount, maxOids)
	}

	// convert oids slice to pdu slice
	var pdus []SnmpPDU
	for _, oid := range oids {
		pdus = append(pdus, SnmpPDU{oid, Null, nil})
	}

	// Marshal and send the packet
	packetOut := x.mkSnmpPacket(GetBulkRequest, nonRepeaters, maxRepetitions)
	return x.send(pdus, packetOut)
}

//
// SNMP Walk functions - Analogous to net-snmp's snmpwalk commands
//

// WalkFunc is the type of the function called for each data unit visited
// by the Walk function.  If an error is returned processing stops.
type WalkFunc func(dataUnit SnmpPDU) error

// BulkWalk retrieves a subtree of values using GETBULK. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetBulk fails),
// or if walkFn returns an error.
func (x *GoSNMP) BulkWalk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetBulkRequest, rootOid, walkFn)
}

// BulkWalkAll is similar to BulkWalk but returns a filled array of all values
// rather than using a callback function to stream results.
func (x *GoSNMP) BulkWalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetBulkRequest, rootOid)
}

// Walk retrieves a subtree of values using GETNEXT - a request is made for each
// value, unlike BulkWalk which does this operation in batches. As the tree is
// walked walkFn is called for each new value. The function immediately returns
// an error if either there is an underlaying SNMP error (e.g. GetNext fails),
// or if walkFn returns an error.
func (x *GoSNMP) Walk(rootOid string, walkFn WalkFunc) error {
	return x.walk(GetNextRequest, rootOid, walkFn)
}

// WalkAll is similar to Walk but returns a filled array of all values rather
// than using a callback function to stream results.
func (x *GoSNMP) WalkAll(rootOid string) (results []SnmpPDU, err error) {
	return x.walkAll(GetNextRequest, rootOid)
}

//
// Public Functions (helpers) - in alphabetical order
//

// Partition - returns true when dividing a slice into
// partitionSize lengths, including last partition which may be smaller
// than partitionSize. This is useful when you have a large array of OIDs
// to run Get() on. See the tests for example usage.
//
// For example for a slice of 8 items to be broken into partitions of
// length 3, Partition returns true for the currentPosition having
// the following values:
//
// 0  1  2  3  4  5  6  7
//       T        T     T
//
func Partition(currentPosition, partitionSize, sliceLength int) bool {
	if currentPosition < 0 || currentPosition >= sliceLength {
		return false
	}
	if partitionSize == 1 { // redundant, but an obvious optimisation
		return true
	}
	if currentPosition%partitionSize == partitionSize-1 {
		return true
	}
	if currentPosition == sliceLength-1 {
		return true
	}
	return false
}

// ToBigInt converts SnmpPDU.Value to big.Int, or returns a zero big.Int for
// non int-like types (eg strings).
//
// This is a convenience function to make working with SnmpPDU's easier - it
// reduces the need for type assertions. A big.Int is convenient, as SNMP can
// return int32, uint32, and uint64.
func ToBigInt(value interface{}) *big.Int {
	var val int64
	switch value := value.(type) { // shadow
	case int:
		val = int64(value)
	case int8:
		val = int64(value)
	case int16:
		val = int64(value)
	case int32:
		val = int64(value)
	case int64:
		val = int64(value)
	case uint:
		val = int64(value)
	case uint8:
		val = int64(value)
	case uint16:
		val = int64(value)
	case uint32:
		val = int64(value)
	case uint64:
		return (uint64ToBigInt(value))
	case string:
		// for testing and other apps - numbers may appear as strings
		var err error
		if val, err = strconv.ParseInt(value, 10, 64); err != nil {
			return new(big.Int)
		}
	default:
		return new(big.Int)
	}
	return big.NewInt(val)
}


text:
package org.apereo.cas.adaptors.u2f.storage;

import org.apereo.cas.util.crypto.CertUtils;

import com.yubico.u2f.data.DeviceRegistration;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.annotation.DirtiesContext;

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

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link AbstractU2FDeviceRepositoryTests}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@DirtiesContext
public abstract class AbstractU2FDeviceRepositoryTests {
    private static final String CASUSER = "casuser";

    @AfterEach
    public void tearDown() throws Exception {
        val deviceRepository = getDeviceRepository();
        deviceRepository.removeAll();
    }

    @BeforeEach
    public void setUp() {
    }

    @Test
    public void verifyDeviceSaved() {
        val deviceRepository = getDeviceRepository();
        registerDevices(deviceRepository);
        var devices = deviceRepository.getRegisteredDevices(CASUSER);
        assertEquals(2, devices.size());
        deviceRepository.clean();
        devices = deviceRepository.getRegisteredDevices();
        assertFalse(devices.isEmpty());
    }

    @Test
    public void verifyDevicesDeleted() {
        val deviceRepository = getDeviceRepository();
        registerDevices(deviceRepository);
        val devices = new ArrayList<>(deviceRepository.getRegisteredDevices(CASUSER));
        assertEquals(2, devices.size());
        deleteDevice(deviceRepository, devices.get(0));
        deleteDevice(deviceRepository, devices.get(1));
        assertTrue(deviceRepository.getRegisteredDevices().isEmpty());
    }

    protected void deleteDevice(final U2FDeviceRepository deviceRepository, final U2FDeviceRegistration device) {
        deviceRepository.deleteRegisteredDevice(device);
    }

    @SneakyThrows
    protected void registerDevices(final U2FDeviceRepository deviceRepository) {
        val devices = prepareDevices(deviceRepository);
        devices.forEach(dev -> {
            deviceRepository.registerDevice(dev);
            deviceRepository.verifyRegisteredDevice(dev);
        });
        assertTrue(deviceRepository.isDeviceRegisteredFor(CASUSER));
    }

    @SneakyThrows
    protected List<U2FDeviceRegistration> prepareDevices(final U2FDeviceRepository deviceRepository) {
        val cert = CertUtils.readCertificate(new ClassPathResource("cert.crt"));
        val r1 = new DeviceRegistration("keyhandle11", "publickey1", cert, 1);
        val record1 = U2FDeviceRegistration.builder()
            .record(deviceRepository.getCipherExecutor().encode(r1.toJsonWithAttestationCert()))
            .username(CASUSER)
            .build();

        val r2 = new DeviceRegistration("keyhandle22", "publickey1", cert, 2);
        val record2 = U2FDeviceRegistration.builder()
            .record(deviceRepository.getCipherExecutor().encode(r2.toJsonWithAttestationCert()))
            .username(CASUSER)
            .build();
        return List.of(record1, record2);
    }

    protected abstract U2FDeviceRepository getDeviceRepository();
}


text:
'use strict';

angular.module('etcdControlPanel')
.controller('RootCtrl', function($rootScope, prefixUrl) {

  // Expose prefixUrl() function to all.
  $rootScope.prefixUrl = prefixUrl;

});


text:
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->
  <head>
    <meta charset="utf-8" />

    {% capture description %}{{ page.content | markdownify | raw_content | excerpt | strip_html | newline_to_br | replace: '<br />', ' ' | strip_newlines | condense_spaces | truncate: 250 }}{% endcapture %}
    <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }}</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />

    {% unless page.meta_tags == false %}
    <meta name="author" content="{{ site.name }}" />
    <meta name="description" content="{{ description }}" />

    <meta property="og:title"        content="{% if page.title %}{{ page.title }}{% else %}{{ site.name }}{% endif %}" />
    <meta property="og:description"  content="{{ description }}" />
    <meta property="st:title"        content="{% if page.title %}{{ page.title }}{% else %}{{ site.name }}{% endif %}" />
    <meta property="st:published_at" content="{% if page.date %}{{ page.date | date_to_xmlschema }}{% else %}{{ site.time | date_to_xmlschema }}{% endif %}" />
    {% endunless %}

    <link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />

    {% css_asset_tag global %}
    - /_assets/css/site.css.scss
    {% endcss_asset_tag %}

    {% javascript_asset_tag global %}
    - /_assets/js/scripts.js
    {% endjavascript_asset_tag %}

  </head>

  <body>

    {{ content }}

  </body>
</html>


text:
<page-layout [ready]="data$ | async">
  <ng-container *ngIf="data then content"></ng-container>
</page-layout>

<ng-template #content>
  <voucher-filters [data]="data" [form]="form"
    [heading]="i18n.voucher.title.search"
    [mobileHeading]="i18n.voucher.mobileTitle.search"
    [moreFilters]="(moreFilters$ | async)"
    [headingActions]="(headingActions$ | async)"
    [customFieldsInSearch]="customFieldsInSearch"></voucher-filters>
  <results-layout resultType="list" [results]="results$ | async"
    [toLink]="toLink" (update)="update($event)" [rendering$]="rendering$">

    <mobile-result *mobileResult="let row" [avatarImage]="row.type.image"
      [avatarIcon]="SvgIcon.Ticket" [amount]="row.amount"
      [amountColor]="false" [currency]="row.type.configuration.currency"
      [topLeft]="apiI18n.voucherStatus(row.status)">

        {{ row.type.name}}

    </mobile-result>

        {{ i18n.general.creationDate }}
        {{ i18n.general.expirationDate }}
        {{ i18n.general.status }}
        {{ i18n.general.type }}
        {{ i18n.transaction.amount }}
        {{ i18n.voucher.balance }}

        <ng-container *ngFor="let row of (results$ | async)?.results">

              <avatar [image]="row.type.image" [icon]="SvgIcon.Ticket">
              </avatar>

            {{ row.creationDate | date }}
            {{ row.expirationDate | date }}
            {{ apiI18n.voucherStatus(row.status) }}
            {{ row.type.name}}
             {{
              row.amount | currency:row.type.configuration.currency
              }}
             {{
              row.balance | currency:row.type.configuration.currency
              }}

        </ng-container>

  </results-layout>
</ng-template>


text:
<?php

namespace AudioManager\Adapter\Ivona;

use AudioManager\Exception\RuntimeException;

/**
 * Simple authenticator with secret key and success key for Ivona adapter
 * @package AudioManager\Adapter\Ivona
 */
class Authenticate
{

    protected $secretKey;
    protected $accessKey;
    protected $currentTime;
    protected $currentDate;
    protected $postData = [];

    /**
     * Constructor
     * @param $secretKey
     * @param $accessKey
     */
    public function __construct($secretKey, $accessKey)
    {
        $this->setSecretKey($secretKey);
        $this->setAccessKey($accessKey);
        $this->currentTime = gmdate('Ymd\THis\Z', time());
        $this->currentDate = substr($this->currentTime, 0, 8);
    }

    /**
     * Set secret key
     * @param string $secretKey
     * @return $this
     */
    protected function setSecretKey($secretKey)
    {
        $this->secretKey = $secretKey;
        return $this;
    }

    /**
     * Get secret key
     * @return string
     */
    public function getSecretKey()
    {
        return $this->secretKey;
    }

    /**
     * Set access key
     * @param string $accessKey
     * @return $this
     */
    protected function setAccessKey($accessKey)
    {
        $this->accessKey = $accessKey;
        return $this;
    }

    /**
     * Get access key
     * @return string
     */
    public function getAccessKey()
    {
        return $this->accessKey;
    }

    /**
     * Get post data
     * @return array
     */
    public function getPostData()
    {
        return $this->postData;
    }

    /**
     * Set post data
     * @param array $postData
     * @return $this
     */
    public function setPostData($postData)
    {
        $this->postData = $postData;
        return $this;
    }

    /**
     * Get authorization headers
     * @param string $serviceType
     * @return array
     */
    public function getHeader($serviceType)
    {
        return [
            'X-Amz-Date: ' . $this->currentTime,
            'Authorization: AWS4-HMAC-SHA256 Credential='
                . $this->getCredential()
                . ',SignedHeaders=host,Signature='
                . $this->createSignature($serviceType)
        ];
    }

    /**
     * Create credential for headers
     */
    protected function getCredential()
    {
        return $this->getAccessKey() . "/" . $this->currentDate . "/eu-west-1/tts/aws4_request";
    }

    /**
     * Get canonical
     * @param      $service
     * @param null $payload
     * @return string
     */
    protected function getCanonicalRequest($service, $payload = null)
    {
        $canonical =
            "POST" .
            "\n/$service" .
            "\n" .
            "\nhost:tts.eu-west-1.ivonacloud.com" .
            "\n" .
            "\nhost" .
            "\n" . hash("sha256", $payload);
        return $canonical;
    }

    /**
     * Get string to sign
     * @param $canonical
     * @return string
     */
    protected function getStringToSign($canonical)
    {
        $stringToSign = "AWS4-HMAC-SHA256" .
            "\n$this->currentTime" .
            "\n$this->currentDate/eu-west-1/tts/aws4_request" .
            "\n" . hash("sha256", $canonical);

        return $stringToSign;
    }

    /**
     * Get signature
     * @param string $stringToSign
     * @return string
     */
    protected function getSignature($stringToSign)
    {
        $dateKey = hash_hmac('sha256', $this->currentDate, "AWS4" . $this->getSecretKey(), true);
        $dateRegionKey = hash_hmac('sha256', "eu-west-1", $dateKey, true);
        $dateRegionServiceKey = hash_hmac('sha256', "tts", $dateRegionKey, true);
        $signingKey = hash_hmac('sha256', "aws4_request", $dateRegionServiceKey, true);
        $signature = hash_hmac('sha256', $stringToSign, $signingKey);

        return $signature;
    }

    /**
     * Create signature
     * @param $requestType
     * @return string
     */
    protected function createSignature($requestType)
    {
        if (empty($this->getPostData())) {
            throw new RuntimeException('Need setup post data');
        }

        $canonical = $this->getCanonicalRequest($requestType, $this->getPostData());
        $stringToSign = $this->getStringToSign($canonical);
        return $this->getSignature($stringToSign);
    }
}


text:
#ifndef fMainH
#define fMainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>
#include <Grids.hpp>
//---------------------------------------------------------------------------
class TformMain : public TForm
{
__published:	// IDE-managed Components
        TGroupBox *GroupBox1;
        TLabel *Label2;
        TEdit *edArbol;
        TLabel *Label3;
        TEdit *edError;
        TGroupBox *GroupBox2;
        TStringGrid *gridTablaVerdad;
        TGroupBox *GroupBox3;
        TListBox *listVars;
        TPanel *Panel1;
        TLabel *Label1;
        TEdit *edExpr;
        TButton *Button1;
        TButton *Button2;
        void __fastcall Button1Click(TObject *Sender);
        void __fastcall Button2Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TformMain(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TformMain *formMain;
//---------------------------------------------------------------------------
#endif


text:
package com.jamierf.maestro.api;

public enum SerialMode {
    // On the Command Port, user can send commands and receive responses.
    // TTL port/UART are connected to make a USB-to-serial adapter.
    USB_DUAL_PORT(0),

    // On the Command Port, user can send commands to Maestro and simultaneously
    // transmit bytes on the UART TX line, and user can receive bytes from the Maestro
    // and the UART RX line. TTL port does not do anything.
    USB_CHAINED(1),

    // On the UART, user can send commands and receive reponses after sending a 0xAA
    // byte to indicate the baud rate. Command Port receives bytes from the RX line.
    // TTL Port does not do anything.
    UART_DETECT_BAUD_RATE(2),

    // On the UART, user can send commands and receive reponses at a predetermined, fixed
    // baud rate. Command Port receives bytes from the RX line. TTL Port does not do anything.
    UART_FIXED_BAUD_RATE(3);

    private final byte code;

    private SerialMode(int code) {
        this.code = (byte) code;
    }

    public byte getCode() {
        return code;
    }
}