text:
'use strict';

var path = require('path');
var prefix = require('global-prefix');
var isWindows = require('is-windows');
var gm;

function getPath() {
  if (isWindows()) {
    return path.resolve(prefix, 'node_modules');
  }
  return path.resolve(prefix, 'lib/node_modules');
}

/**
 * Expose `global-modules` path
 */

Object.defineProperty(module, 'exports', {
  enumerable: true,
  get: function() {
    return gm || (gm = getPath());
  }
});

redpajama_set_name: RedPajamaGithub


text:
def top_level_reducer(owner, child):
    return owner

def bot_level_reducer(owner, child):
    return child

def addition_reducer(owner, child):
    return owner + child

def mult_reducer(owner, child):
    return owner * child


text:
<md-card layout-align="center center">
    Data Confidence
    Validates Data Integrity
    <md-card-content layout="column" flex layout-align="center center" class="kpi-content" style="width:100%;">

            <nvd3 flex options="vm.chartOptions" data="vm.chartData" api="vm.chartApi"></nvd3>

                0}">{{vm.dataMap.Healthy.count}}
                Healthy

                0}">{{vm.dataMap.Unhealthy.count}}
                Unhealthy

            <md-progress-circular md-mode="indeterminate" md-diameter="60"></md-progress-circular>

    </md-card-content>
</md-card>


text:
#pragma once
#ifndef CORE_WEBVIEW_HPP
#define CORE_WEBVIEW_HPP

#include "SharedDefines.hpp"

#include <QApplication>
#include <QPointer>

#include <QEvent>
#include <QKeyEvent>

#include <QOpenGLWidget>
#include <QWidget>
#include <QLabel>

#include <QWebEngine/WebView.hpp>
#include <QWebEngine/WebPage.hpp>

#include "Web/LoadRequest.hpp"

#include "Application.hpp"

namespace Sn {

class WebPage;
class WebHitTestResult;

class SIELO_SHAREDLIB WebView: public Engine::WebView {
Q_OBJECT

public:
	static bool isUrlValide(const QUrl& url);
	static QUrl searchUrl(const QString& searchText);
	static QList<int> zoomLevels();

	WebView(QWidget* parent = nullptr);
	~WebView();

	QIcon icon(bool allowNull = false) const;

	QString title() const;
	bool isTitleEmpty() const;

	WebPage* page() const;
	void setPage(WebPage* page);

	void load(const QUrl& url);
	void load(const LoadRequest& request);
	bool isLoading() const;
	bool wasLoaded() const { return m_firstLoad; }

	int loadingProgress() const;

	bool backgroundActivity() const { return m_backgroundActivity; }

	int zoomLevel() const;
	void setZoomLevel(int level);

	QPointF mapToViewport(const QPointF& pos) const;

	void restoreHistory(const QByteArray& data);

	void addNotification(QWidget* notification);

	virtual QWidget* overlayWidget() = 0;

	bool isTransparent() const;

signals:
	void pageChanged(WebPage* page);
	void pageRendering();
	void viewportResized(QSize);
	void privacyChanged(bool);
	void zoomLevelChanged(int);
	void showNotification(QWidget*);
	void backgroundActivityChanged(bool);

public slots:
	void zoomIn();
	void zoomOut();
	void zoomReset();

	void editUndo() { triggerPageAction(Engine::WebPage::Undo); }
	void editRedo() { triggerPageAction(Engine::WebPage::Redo); }
	void editCopy() { triggerPageAction(Engine::WebPage::Copy); }
	void editCut() { triggerPageAction(Engine::WebPage::Cut); }
	void editPast() { triggerPageAction(Engine::WebPage::Paste); }
	void editSelectAll() { triggerPageAction(Engine::WebPage::SelectAll); }
	void editDelet()
	{
		QKeyEvent event{QEvent::KeyPress, Qt::Key_Delete, Qt::NoModifier};
		QApplication::sendEvent(this, &event);
	}
	void reloadBypassCache() { triggerPageAction(Engine::WebPage::ReloadAndBypassCache); }

	void back();
	void forward();

	void showSource();
	virtual void openUrlInNewTab(const QUrl& url, Application::NewTabType position);

	virtual void closeView() = 0;
	virtual void loadInNewTab(const LoadRequest& request, Application::NewTabType position) = 0;

	virtual bool isFullScreen() = 0;
	virtual void requestFullScreen(bool enable) = 0;

protected slots:
	void sLoadStarted();
	void sLoadProgress(int progress);
	void sLoadFinished(bool ok);
	void sUrlChanged(const QUrl& url);
	void sTitleChanged(const QString& title);
	void sIconChanged();

	void openUrlInNewWindow();
	void copyLinkToClipboard();
	void copyImageToClipboard();
	void savePageAs();
	void dlLinkToDisk();
	void dlImageToDisk();
	void dlMediaToDisk();
	void openActionUrl();
	void showSiteInformation();
	void searchSelectedText();
	void searchSelectedTextInBgTab();
	void bookmarkLink();
	void openUrlInSelectedTab();
	void openUrlInBgTab();

protected:
	void showEvent(QShowEvent* event) override;
	void resizeEvent(QResizeEvent* event);
	void contextMenuEvent(QContextMenuEvent* event);

	virtual void newWheelEvent(QWheelEvent* event);
	virtual void newMousePressEvent(QMouseEvent* event);
	virtual void newMouseReleaseEvent(QMouseEvent* event);
	virtual void newMouseMoveEvent(QMouseEvent* event);
	virtual void newKeyPressEvent(QKeyEvent* event);
	virtual void newKeyReleaseEvent(QKeyEvent* event);
	virtual void newContextMenuEvent(QContextMenuEvent* event);

	void loadRequest(const LoadRequest& request);
	void applyZoom();

	void createContextMenu(QMenu* menu, WebHitTestResult& hitTest);
	void createPageContextMenu(QMenu* menu);
	void createLinkContextMenu(QMenu* menu, const WebHitTestResult& hitTest);
	void createImageContextMenu(QMenu* menu, const WebHitTestResult& hitTest);
	void createSelectedTextContextMenu(QMenu* menu, const WebHitTestResult& hitTest);
	void createMediaContextMenu(QMenu* menu, const WebHitTestResult& hitTest);

private slots:
	//TODO: Manage forms (for password for example)

	void toggleMediaPause() { triggerPageAction(Engine::WebPage::ToggleMediaPlayPause); }
	void toggleMediaMute() { triggerPageAction(Engine::WebPage::ToggleMediaMute); }

private:
	// Actually, this class is more for add shortcuts
	void initActions();

	void updateLabel(const QString& zoomLevel);

	int m_currentZoomLevel{};
	int m_progress{100};
	bool m_backgroundActivity{false};
	bool m_firstLoad{false};

	QUrl m_clickedUrl{};
	QPointF m_clickedPos{};

	QLabel* m_zoomLabel{nullptr};
	QTimer* m_zoomTimer{nullptr};

	WebPage* m_page{nullptr};
};
}

#endif //CORE_WEBVIEW_HPP


text:
import EffectId from '../../../resources/effect_id';
import TimerBar from '../../../resources/timerbar';
import TimerBox from '../../../resources/timerbox';
import { JobDetail } from '../../../types/event';
import { ResourceBox } from '../bars';
import { ComboTracker } from '../combo_tracker';
import { kAbility } from '../constants';
import { computeBackgroundColorFrom } from '../utils';

import { BaseComponent, ComponentInterface } from './base';

export class NINComponent extends BaseComponent {
  ninki: ResourceBox;
  hutonBox: TimerBox;
  trickAttack: TimerBox;
  bunshin: TimerBox;
  ninjutsu: TimerBox;
  comboTimer: TimerBar;
  tid1 = 0;
  mudraTriggerCd = true;

  constructor(o: ComponentInterface) {
    super(o);

    this.ninki = this.bars.addResourceBox({
      classList: ['nin-color-ninki'],
    });
    this.hutonBox = this.bars.addProcBox({
      id: 'nin-procs-huton',
      fgColor: 'nin-color-huton',
      threshold: 20,
    });
    this.trickAttack = this.bars.addProcBox({
      id: 'nin-procs-trickattack',
      fgColor: 'nin-color-trickattack',
    });
    this.bunshin = this.bars.addProcBox({
      id: 'nin-procs-bunshin',
      fgColor: 'nin-color-bunshin',
    });
    this.ninjutsu = this.bars.addProcBox({
      id: 'nin-procs-ninjutsu',
      fgColor: 'nin-color-ninjutsu',
    });

    this.comboTimer = this.bars.addTimerBar({
      id: 'nin-timers-combo',
      fgColor: 'combo-color',
    });

    this.reset();
  }

  override onYouGainEffect(id: string): void {
    switch (id) {
      // Ninjutsu's cooldown begins to countdown at the first mudra.
      case EffectId.Mudra: {
        if (!this.mudraTriggerCd)
          return;
        if (this.ninjutsu.duration === null)
          this.ninjutsu.duration = 0;
        const old = this.ninjutsu.duration - this.ninjutsu.elapsed;
        if (old > 0)
          this.ninjutsu.duration = old + 20;
        else
          this.ninjutsu.duration = 20 - 0.5;

        this.mudraTriggerCd = false;
        break;
      }
      case EffectId.Kassatsu:
        this.mudraTriggerCd = false;
        break;
    }
  }
  // On each mudra, Mudra effect will be gain once,
  // use mudraTriggerCd to tell that whether bars mudra trigger cooldown.
  override onYouLoseEffect(id: string): void {
    if (id === EffectId.Mudra)
      this.mudraTriggerCd = true;
    if (id === EffectId.Kassatsu)
      this.mudraTriggerCd = true;
  }

  override onUseAbility(id: string): void {
    switch (id) {
      case kAbility.Bunshin:
        this.bunshin.duration = 90;
        break;
      case kAbility.Hide:
        this.ninjutsu.duration = 0;
        break;
      case kAbility.TrickAttack: {
        this.trickAttack.duration = 15;
        this.trickAttack.threshold = 1000;
        this.trickAttack.fg = computeBackgroundColorFrom(
          this.trickAttack,
          'nin-color-trickattack.active',
        );
        this.tid1 = window.setTimeout(() => {
          this.trickAttack.duration = 45;
          this.trickAttack.threshold = this.player.gcdSkill * 4;
          this.trickAttack.fg = computeBackgroundColorFrom(
            this.trickAttack,
            'nin-color-trickattack',
          );
        }, 15000);
        break;
      }
    }
  }

  override onStatChange({ gcdSkill }: { gcdSkill: number }): void {
    this.trickAttack.valuescale = gcdSkill;
    this.bunshin.valuescale = gcdSkill;
    this.bunshin.threshold = gcdSkill * 8;
    this.ninjutsu.valuescale = gcdSkill;
    this.ninjutsu.threshold = gcdSkill * 2;
  }

  override onJobDetailUpdate(jobDetail: JobDetail['NIN']): void {
    if (jobDetail.hutonMilliseconds > 0) {
      if (!this.player.speedBuffs.huton)
        this.player.speedBuffs.huton = true;
    } else if (this.player.speedBuffs.huton) {
      this.player.speedBuffs.huton = false;
    }
    this.ninki.innerText = jobDetail.ninkiAmount.toString();
    this.ninki.parentNode.classList.remove('high', 'low');
    if (jobDetail.ninkiAmount < 50)
      this.ninki.parentNode.classList.add('low');
    else if (jobDetail.ninkiAmount >= 90)
      this.ninki.parentNode.classList.add('high');
    if (this.hutonBox.duration === null)
      this.hutonBox.duration = 0;
    const oldSeconds = this.hutonBox.duration - this.hutonBox.elapsed;
    const seconds = jobDetail.hutonMilliseconds / 1000.0;
    if (!this.hutonBox.duration || seconds > oldSeconds)
      this.hutonBox.duration = seconds;
  }
  override onCombo(skill: string, combo: ComboTracker): void {
    this.comboTimer.duration = 0;
    if (combo.isFinalSkill)
      return;
    if (skill)
      this.comboTimer.duration = this.comboDuration;
  }

  override reset(): void {
    this.bunshin.duration = 0;
    this.mudraTriggerCd = true;
    this.ninjutsu.duration = 0;
    this.trickAttack.duration = 0;
    this.trickAttack.threshold = this.player.gcdSkill * 4;
    this.trickAttack.fg = computeBackgroundColorFrom(
      this.trickAttack,
      'nin-color-trickattack',
    );
    this.hutonBox.duration = 0;
    this.comboTimer.duration = 0;
    window.clearTimeout(this.tid1);
  }
}


text:
# Dockerfile for building Ansible image for Debian 9 (stretch), with as few additional software as possible.

FROM debian:stretch
ENV LC_ALL C
ENV DEBIAN_FRONTEND noninteractive

MAINTAINER Aleksej Gavrilov <le9i0nx@gmail.com>

RUN DEBIAN_FRONTEND=noninteractive \
    apt-get update  && \
    apt-get dist-upgrade -y && \
    apt-get install -y \
        sudo openssh-server locales python ca-certificates systemd && \
    locale-gen --purge en_US.UTF-8 && \
    echo -e 'LANG="en_US.UTF-8"\nLANGUAGE="en_US:en"\n' > /etc/default/locale && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*  /tmp/*

RUN systemctl mask \
    systemd-remount-fs.service \
    dev-hugepages.mount \
    sys-fs-fuse-connections.mount \
    systemd-logind.service \
    getty.target \
    console-getty.service \
    dev-mqueue.mount \
    sys-kernel-config.mount \
    sys-kernel-debug.mount \
    display-manager.service \
    graphical.target

RUN sed -ri 's/^#PermitRootLogin\s+.*/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN echo "root:000000" | chpasswd

VOLUME ["/sys/fs/cgroup"]
VOLUME ["/run"]
VOLUME ["/tmp"]
ENV container=docker
ENV init /lib/systemd/systemd
ENTRYPOINT ["/lib/systemd/systemd"]
# docker run -d --privileged -it -v /sys/fs/cgroup:/sys/fs/cgroup:ro test-debian9


text:
import pytest
import sys
sys.path.append(".")
sys.path.append("..")
sys.path.append("../..")
from Hologram.Authentication import *
from Hologram.Cloud import Cloud

class TestCloud:

    def test_create_send(self):
        cloud = Cloud(None, send_host = '127.0.0.1', send_port = 9999)

        assert cloud.send_host == '127.0.0.1'
        assert cloud.send_port == 9999
        assert cloud.receive_host == ''
        assert cloud.receive_port == 0

    def test_create_receive(self):
        cloud = Cloud(None, receive_host = '127.0.0.1', receive_port = 9999)

        assert cloud.send_host == ''
        assert cloud.send_port == 0
        assert cloud.receive_host == '127.0.0.1'
        assert cloud.receive_port == 9999

    def test_invalid_send_message(self):
        cloud = Cloud(None, receive_host = '127.0.0.1', receive_port = 9999)

        with pytest.raises(Exception, match = 'Must instantiate a Cloud type'):
            cloud.sendMessage("hello SMS")

    def test_invalid_send_sms(self):
        cloud = Cloud(None, send_host = '127.0.0.1', send_port = 9999)

        with pytest.raises(Exception, match = 'Must instantiate a Cloud type'):
            cloud.sendSMS('+12345678900', 'hello SMS')

    # This is good for testing if we updated the internal SDK version numbers before release.
    def test_sdk_version(self):
        cloud = Cloud(None, send_host = '127.0.0.1', send_port = 9999)

        assert cloud.version == '0.9.1'


text:
'use strict';

angular.module(
    'tpp.controllers', ['ui.bootstrap', 'tpp.task', 'tpp.resource', 'tpp.project', 'tpp.utils', 'tpp.controllers.tasks']
).controller(
    'tppDisplayCtrl', ['$window', '$scope', '$routeParams', '$location', '$modal', 'Resource', 'Task', 'Project', 'dateUtil',
    function ($window, $scope, $routeParams, $location, $modal, Resource, Task, Project, dateUtil)
{
    $scope.OVERVIEW_THRESHOLD = 10;
    $scope.tasks = {};
    var taskList = [];

    /**
     * This function builds an object of tasks which are organized by resource ids and weeks:
     * {
     *   resourceId1: {
     *     week1: [task1, task2]
     *   }
     * }
     *
     * This allows the loop in template views/list.html to access the correct task fast
     *
     * @param taskList Array of tasks
     * @returns Object
     */
    function buildTasks(taskList) {
        return taskList.reduce(function (filtered, task) {
            filtered[task.resourceId] = filtered[task.resourceId] || {};
            filtered[task.resourceId][task.week] = (filtered[task.resourceId][task.week] || []).concat(task);

            return filtered;
        }, {});
    }

    $scope.weeks = {
        date: (function () {
            var date = moment();
            if ($routeParams.year) {
                date.weekYear($routeParams.year);
            }
            if ($routeParams.week) {
                date.week($routeParams.week);
            }
            return date.startOf('week');
        })(),
        numWeeks: parseInt($routeParams.numWeeks) || parseInt(localStorage.getItem('tppDisplayCtrl.numWeeks')) || 7
    };

    ($scope.setUp = function (weeks) {
        // build List of weeks from user inputted date and numWeeks
        $scope.weekList = dateUtil.getWeekList(weeks);

        // fetch tasks from server (only set list when finished loading to avoid flashing)
        taskList = Task.query({
            numWeeks: weeks.numWeeks,
            week: weeks.date.week(),
            year: weeks.date.weekYear()
        }, function () {
            $scope.tasks = buildTasks(taskList);
        });

        localStorage.setItem('tppDisplayCtrl.numWeeks', $scope.weeks.numWeeks);

        $location.search({
            'year': $scope.weeks.date.weekYear(),
            'week': $scope.weeks.date.week(),
            'numWeeks': $scope.weeks.numWeeks || 7
        });

    })($scope.weeks);

    // fetch resources from server
    $scope.resourceList = Resource.query();

    // fetch projects from server
    $scope.projectList = Project.query();

    // re-fetch on changing weeks
    $scope.$watchCollection('weeks', function (newWeeks) {
        $scope.setUp(newWeeks);
    });

    $scope.addResource = function (addedResource) {

        // Don't use copy here, ID will not be set otherwise
        var resource = new Resource({
            name: addedResource.name
        });
        resource.$save();

        $scope.resourceList.push(resource);

        // reset text input
        addedResource.name = '';
    };

    $scope.removeResource = function (resource) {
        if ($window.confirm('Really delete?')) {
            resource.$delete();
            $scope.resourceList = $scope.resourceList.filter(function (r) {
                return r.id !== resource.id;
            });
        }
    };

    $scope.addTask = function (resourceId, week) {
        var modalInstance = $modal.open({
            templateUrl: '/views/taskModal.html',
            controller: 'taskAddModalCtrl',
            resolve: {
                'resourceId': function () {
                    return resourceId;
                },
                'week': function () {
                    return week;
                },
                'projectList': function () {
                    return $scope.projectList;
                }
            }
        });

        modalInstance.result.then(function (task) {
            task.$save();
            taskList.push(task);
            $scope.tasks = buildTasks(taskList);
        });
    };

    $scope.editTask = function (task) {
        // fix selected option in dialog
        for (var i = 0; i < $scope.projectList.length; i++) {
            if (task.project.id === $scope.projectList[i].id) {
                task.project = $scope.projectList[i];
                break;
            }
        }
        var modalInstance = $modal.open({
            templateUrl: '/views/taskModal.html',
            controller: 'taskEditModalCtrl',
            resolve: {
                'task': function () {
                    return task;
                },
                'projectList': function () {
                    return $scope.projectList;
                }
            }
        });

        modalInstance.result.then(function (task) {
            task.$update();
            taskList = taskList.filter(function (t) {
                return t.id !== task.id;
            });
            taskList.push(task);
            $scope.tasks = buildTasks(taskList);
        });
    };

    $scope.deleteTask = function (task) {
        task.$delete();
        taskList = taskList.filter(function (t) {
            return t.id !== task.id;
        });
        $scope.tasks = buildTasks(taskList);
    };

    $scope.$on('keyPressed', function (event, keyPressedEvent) {
        var LEFT_ARROW = 37,
            UP_ARROW = 38,
            RIGHT_ARROW = 39,
            DOWN_ARROW = 40;
        if (LEFT_ARROW === keyPressedEvent.keyCode) {
            $scope.back();
        } else if (RIGHT_ARROW === keyPressedEvent.keyCode) {
            $scope.forward();
        } else if (UP_ARROW === keyPressedEvent.keyCode) {
            $scope.weeks.numWeeks += 1;
            keyPressedEvent.preventDefault();
        } else if (DOWN_ARROW === keyPressedEvent.keyCode) {
            $scope.weeks.numWeeks -= 1;
            keyPressedEvent.preventDefault();
        }
    });

    // default setting on what the list should be sorted
    $scope.sortCriteria = 'name';

    /**
     * Sort list by the passed criteria.
     * When the criteria was used before pretend a - before the criteria name to reverse sorting.
     * The name of the sort criteria is simply the key inside a data object passed by the dataprovider.
     *
     * @param {string} sortCriteria
     */
    $scope.sortListBy = function(sortCriteria) {
        if ($scope.sortCriteria === sortCriteria) {
            $scope.sortCriteria = '-' + sortCriteria;
        } else {
            $scope.sortCriteria = sortCriteria;
        }
    };

    $scope.isCurrent = function (week) {
        return moment().startOf('week').isSame(week);
    };

    // go one week back
    $scope.back = function () {
        $scope.weeks.date.subtract(1, 'w');
        $scope.setUp($scope.weeks);
    };

    // go one week forward
    $scope.forward = function () {
        $scope.weeks.date.add(1, 'w');
        $scope.setUp($scope.weeks);
    };

}]);


text:
require 'spec_helper'

describe Spree::CreditCard do

  let(:valid_credit_card_attributes) { {:number => '4111111111111111', :verification_value => '123', :month => 12, :year => 2014} }

  def stub_rails_env(environment)
    Rails.stub(:env => ActiveSupport::StringInquirer.new(environment))
  end

  let(:credit_card) { Spree::CreditCard.new }

  before(:each) do

    @order = create(:order)
    @payment = Spree::Payment.create({:amount => 100, :order => @order}, :without_protection => true)

    @success_response = mock('gateway_response', :success? => true, :authorization => '123', :avs_result => {'code' => 'avs-code'})
    @fail_response = mock('gateway_response', :success? => false)

    @payment_gateway = mock_model(Spree::PaymentMethod,
      :payment_profiles_supported? => true,
      :authorize => @success_response,
      :purchase => @success_response,
      :capture => @success_response,
      :void => @success_response,
      :credit => @success_response,
      :environment => 'test'
    )

    @payment.stub :payment_method => @payment_gateway
  end

  context "#can_capture?" do
    it "should be true if payment state is pending" do
      payment = mock_model(Spree::Payment, :state => 'pending', :created_at => Time.now)
      credit_card.can_capture?(payment).should be_true
    end
  end

  context "when transaction is more than 12 hours old" do
    let(:payment) { mock_model(Spree::Payment, :state => "completed",
                                               :created_at => Time.now - 14.hours,
                                               :amount => 99.00,
                                               :credit_allowed => 100.00,
                                               :order => mock_model(Spree::Order, :payment_state => 'credit_owed')) }

    context "#can_credit?" do

      it "should be true when payment state is 'completed' and order payment_state is 'credit_owed' and credit_allowed is greater than amount" do
        credit_card.can_credit?(payment).should be_true
      end

      it "should be false when order payment_state is not 'credit_owed'" do
        payment.order.stub(:payment_state => 'paid')
        credit_card.can_credit?(payment).should be_false
      end

      it "should be false when credit_allowed is zero" do
        payment.stub(:credit_allowed => 0)
        credit_card.can_credit?(payment).should be_false
      end

      (PAYMENT_STATES - ['completed']).each do |state|
        it "should be false if payment state is #{state}" do
          payment.stub :state => state
          credit_card.can_credit?(payment).should be_false
        end
      end

    end

    context "#can_void?" do
      (PAYMENT_STATES - ['void']).each do |state|
        it "should be true if payment state is #{state}" do
          payment.stub :state => state
          payment.stub :void? => false
          credit_card.can_void?(payment).should be_true
        end
      end

      it "should be valse if payment state is void" do
        payment.stub :state => 'void'
        credit_card.can_void?(payment).should be_false
      end
    end
  end

  context "when transaction is less than 12 hours old" do
    let(:payment) { mock_model(Spree::Payment, :state => 'completed') }

    context "#can_void?" do
      (PAYMENT_STATES - ['void']).each do |state|
        it "should be true if payment state is #{state}" do
          payment.stub :state => state
          credit_card.can_void?(payment).should be_true
        end
      end

      it "should be false if payment state is void" do
        payment.stub :state => 'void'
        credit_card.can_void?(payment).should be_false
      end

    end
  end

  context "#valid?" do
    it "should validate presence of number" do
      credit_card.attributes = valid_credit_card_attributes.except(:number)
      credit_card.should_not be_valid
      credit_card.errors[:number].should == ["can't be blank"]
    end

    it "should validate presence of security code" do
      credit_card.attributes = valid_credit_card_attributes.except(:verification_value)
      credit_card.should_not be_valid
      credit_card.errors[:verification_value].should == ["can't be blank"]
    end

    it "should only validate on create" do
      credit_card.attributes = valid_credit_card_attributes
      credit_card.save
      credit_card.should be_valid
    end
  end

  context "#save" do
    before do
      credit_card.attributes = valid_credit_card_attributes
      credit_card.save!
    end

    let!(:persisted_card) { Spree::CreditCard.find(credit_card.id) }

    it "should not actually store the number" do
      persisted_card.number.should be_blank
    end

    it "should not actually store the security code" do
      persisted_card.verification_value.should be_blank
    end
  end

  context "#spree_cc_type" do
    before do
      credit_card.attributes = valid_credit_card_attributes
    end

    context "in development mode" do
      before do
        stub_rails_env("production")
      end

      it "should return visa" do
        credit_card.save
        credit_card.spree_cc_type.should == "visa"
      end
    end

    context "in production mode" do
      before do
        stub_rails_env("production")
      end

      it "should return the actual cc_type for a valid number" do
        credit_card.number = "378282246310005"
        credit_card.save
        credit_card.spree_cc_type.should == "american_express"
      end
    end
  end

  context "#set_card_type" do
    before :each do
      stub_rails_env("production")
      credit_card.attributes = valid_credit_card_attributes
    end

    it "stores the credit card type after validation" do
      credit_card.number = "6011000990139424"
      credit_card.save
      credit_card.spree_cc_type.should == "discover"
    end

    it "does not overwrite the credit card type when loaded and saved" do
      credit_card.number = "5105105105105100"
      credit_card.save
      credit_card.number = "XXXXXXXXXXXX5100"
      credit_card.save
      credit_card.spree_cc_type.should == "master"
    end
  end

  context "#associations" do
    it "should be able to access its payments" do
      lambda { credit_card.payments.all }.should_not raise_error ActiveRecord::StatementInvalid
    end
  end
end


text:
angular.module('mobio.odML')

        .factory('odmlBikeAnt', function ($http, $q) {

            var odMLdataStructure = {
                "odML": {
                    "author": "mobio_app",
                    "date": "1970-01-01T00:00:00.000+0000",
                    "version": 1,
                    "xmlns:gui": "http://www.g-node.org/guiml",
                    "section": [
                        {//0
                            "name": "Calculated Speed",
                            "type": "calculatedSpeed",
                            "section": [
                            ]
                        },
                        {//1
                            "name": "Calculated Accumulated Distance",
                            "type": "calculatedAccumulatedDistance",
                            "property": [
                                {//0
                                    "name": "calculatedAccumulatedDistance",
                                    "value": {
                                        "type": "float",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//2
                            "name": "Cumulative Revolutions",
                            "type": "cumulativeRevolutions",
                            "property": [
                                {//0
                                    "name": "cumulativeRevolutions",
                                    "value": {
                                        "type": "float",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "timestampOfLastEvent",
                                    "value": {
                                        "type": "float",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//3
                            "name": "Calculated Cadence",
                            "type": "calculatedCadence",
                            "property": [
                                {//0
                                    "name": "calculatedCadence",
                                    "value": {
                                        "type": "float",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "isCombinedSensor",
                                    "value": {
                                        "type": "boolean",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//4
                            "name": "Cumulative Operating Time",
                            "type": "cumulativeOperatingTime",
                            "property": [
                                {//0
                                    "name": "cumulativeOperatingTime",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//5
                            "name": "Manufacturer And Serial",
                            "type": "manufacturerAndSerial",
                            "property": [
                                {//0
                                    "name": "manufacturerID",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "serialNumber",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//6
                            "name": "Version And Model",
                            "type": "versionAndModel",
                            "property": [
                                {//0
                                    "name": "softwareVersion",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "hardwareVersion",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                },
                                {//2
                                    "name": "modelNumber",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                }
                            ]
                        },
                        {//7
                            "name": "Battery Status",
                            "type": "batteryStatus",
                            "property": [
                                {//0
                                    "name": "batteryVoltage",
                                    "value": {
                                        "type": "int",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "batteryStatus",
                                    "value": {
                                        "type": "string",
                                        "content": ""
                                    }
                                }
                            ]
                        },
                        {//8
                            "name": "Motion And Speed",
                            "type": "motionAndSpeed",
                            "property": [
                                {//0
                                    "name": "estTimestamp",
                                    "value": {
                                        "type": "string",
                                        "content": 0
                                    }
                                },
                                {//1
                                    "name": "isStopped",
                                    "value": {
                                        "type": "boolean",
                                        "content": false
                                    }
                                }
                            ]
                        },
                        {//9
                            "name": "Wheel Circumference",
                            "type": "wheelCircumference",
                            "property": [
                                {//0
                                    "name": "wheelCircumference",
                                    "value": {
                                        "type": "float",
                                        "content": 0
                                    }
                                }
                            ]
                        }
                    ]
                }
            };

            return {
                getBasicObject: function () {
                    return JSON.parse(JSON.stringify(odMLdataStructure));
                },
                getDate: function (data) {
                    return data.odML.date;
                },
                getCalculatedSpeed: function (data) {
                    return data.odML.section[0];
                },
                getCalculatedAccumulatedDistance: function (data) {
                    return data.odML.section[1];
                },
                getCumulativeRevolutions: function (data) {
                    return data.odML.section[2];
                },
                getCalculatedCadence: function (data) {
                    return data.odML.section[3];
                },
                getCumulativeOperatingTime: function (data) {
                    return data.odML.section[4];
                },
                getManufacturerAndSerial: function (data) {
                    return data.odML.section[5];
                },
                getVersionAndModel: function (data) {
                    return data.odML.section[6];
                },
                getBatteryStatus: function (data) {
                    return data.odML.section[7];
                },
                getMotionAndSpeed: function (data) {
                    return data.odML.section[8];
                },
                getWheelCircumference: function (data) {
                    return data.odML.section[9];
                },
                setDate: function (data, value) {
                    var result = data;
                    result.odML.date = value;
                    return result;
                },
                addCalculatedSpeed: function (data, measurement) {
                    var toPush = {
                        "name": "cs",
                        "type": "cs",
                        "property": [
                            {
                                "name": "estTimestamp",
                                "value": {
                                    "type": "string",
                                    "content": moment(measurement.estTimestamp).format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
                                }
                            },
                            {
                                "name": "calculatedSpeed",
                                "value": {
                                    "type": "float",
                                    "content": measurement.calculatedSpeed
                                }
                            }
                        ]
                    };
                    var result = data;
                    result.odML.section[0].section.push(toPush);
                    return result;
                },
                setCalculatedAccumulatedDistance: function (data, measurement) {
                    var result = data;
                    result.odML.section[1].property[0].value.content = measurement.calculatedAccumulatedDistance;
                    return result;
                },
                setCumulativeRevolutions: function (data, measurement) {
                    var result = data;
                    result.odML.section[2].property[0].value.content = measurement.cumulativeRevolutions;
                    return result;
                },
                setCalculatedCadence: function (data, measurement) {
                    var result = data;
                    result.odML.section[3].property[0].value.content = measurement.calculatedCadence;
                    result.odML.section[3].property[1].value.content = measurement.isCombinedSensor;
                    return result;
                },
                setCumulativeOperatingTime: function (data, measurement) {
                    var result = data;
                    result.odML.section[4].property[0].value.content = measurement.cumulativeOperatingTime;
                    return result;
                },
                setManufacturerAndSerial: function (data, measurement) {
                    var result = data;
                    result.odML.section[5].property[0].value.content = measurement.manufacturerID;
                    result.odML.section[5].property[1].value.content = measurement.serialNumber;
                    return result;
                },
                setVersionAndModel: function (data, measurement) {
                    var result = data;
                    result.odML.section[6].property[0].value.content = measurement.softwareVersion;
                    result.odML.section[6].property[1].value.content = measurement.hardwareVersion;
                    result.odML.section[6].property[2].value.content = measurement.modelNumber;
                    return result;
                },
                setBatteryStatus: function (data, measurement) {
                    var result = data;
                    result.odML.section[7].property[0].value.content = measurement.batteryVoltage;
                    result.odML.section[7].property[1].value.content = measurement.batteryStatus;
                    return result;
                },
                setMotionAndSpeed: function (data, measurement) {
                    var result = data;
                    result.odML.section[8].property[0].value.content = moment(measurement.estTimestamp).format("YYYY-MM-DDTHH:mm:ss.SSSZZ");
                    result.odML.section[8].property[1].value.content = measurement.isStopped;
                    return result;
                },
                setWheelCircumference: function (data, wheelCircumference) {
                    var result = data;
                    result.odML.section[9].property[0].value.content = wheelCircumference;
                    return result;
                }
            };

        });


text:
'use strict';

var React = require('react');
var d3 = require('d3');

module.exports =  {

  propTypes: {
    axesColor:         React.PropTypes.string,
    colors:            React.PropTypes.func,
    colorAccessor:     React.PropTypes.func,
    data:              React.PropTypes.array.isRequired,
    height:            React.PropTypes.number,
    legend:            React.PropTypes.bool,
    legendOffset:      React.PropTypes.number,
    title:             React.PropTypes.string,
    width:             React.PropTypes.number,
    xAccessor:         React.PropTypes.func,
    xAxisFormatter:    React.PropTypes.func,
    xAxisLabel:        React.PropTypes.string,
    xAxisLabelOffset:  React.PropTypes.number,
    xAxisTickCount:    React.PropTypes.number,
    xAxisTickInterval: React.PropTypes.object,
    xAxisTickValues:   React.PropTypes.array,
    xOrient:           React.PropTypes.oneOf(['top', 'bottom']),
    yAccessor:         React.PropTypes.func,
    yAxisFormatter:    React.PropTypes.func,
    yAxisLabel:        React.PropTypes.string,
    yAxisLabelOffset:  React.PropTypes.number,
    yAxisTickCount:    React.PropTypes.number,
    yAxisTickInterval: React.PropTypes.object,
    yAxisTickValues:   React.PropTypes.array,
    yOrient:           React.PropTypes.oneOf(['left', 'right'])
  },

  getDefaultProps: function() {
    return {
      axesColor:        '#000',
      colors:           d3.scale.category20c(),
      colorAccessor:    (d, idx) => idx,
      height:           200,
      legend:           false,
      legendOffset:     120,
      title:            '',
      width:            400,
      xAccessor:        (d) => d.x,
      // xAxisFormatter: no predefined value right now
      xAxisLabel:       '',
      xAxisLabelOffset: 38,
      // xAxisTickCount: no predefined value right now
      // xAxisTickInterval: no predefined value right now
      // xAxisTickValues: no predefined value right now
      xOrient:          'bottom',
      yAccessor:        (d) => d.y,
      // yAxisFormatter: no predefined value right now
      yAxisLabel:       '',
      yAxisLabelOffset: 35,
      // yAxisTickCount: no predefined value right now
      // yAxisTickInterval: no predefined value right now
      // yAxisTickValues: no predefined value right now
      yOrient:          'left'
    };
  }
};


text:
<?php
class Kwc_Columns_Events extends Kwc_Abstract_List_Events
{
    public function getListeners()
    {
        $ret = parent::getListeners();
        $ret[] = array(
            'event' => 'Kwf_Component_Event_Component_ContentWidthChanged',
            'callback' => 'onContentWidthChanged'
        );
        $ret[] = array(
            'event' => 'Kwf_Component_Event_Component_RecursiveContentWidthChanged',
            'callback' => 'onRecursiveContentWidthChanged'
        );
        return $ret;
    }

    public function onRowInsertOrDelete(Kwf_Component_Event_Row_Abstract $event)
    {
        parent::onRowInsertOrDelete($event);
        $c = Kwf_Component_Data_Root::getInstance()->getComponentByDbId(
            $event->row->component_id, array('limit'=>1, 'ignoreVisible'=>true)
        );
        if ($c && $c->componentClass == $this->_class) {
            if ($event->row->visible) {
                $this->fireEvent(new Kwf_Component_Event_Component_ContentWidthChanged(
                    $this->_class, $c
                ));
            }
        }
    }

    public function onRowUpdate(Kwf_Component_Event_Row_Updated $event)
    {
        parent::onRowUpdate($event);
        $c = Kwf_Component_Data_Root::getInstance()->getComponentByDbId(
            $event->row->component_id, array('limit'=>1, 'ignoreVisible'=>true)
        );
        if ($c && $c->componentClass == $this->_class) {
            if ($event->isDirty('width') || $event->isDirty('visible')) {
                $this->fireEvent(new Kwf_Component_Event_Component_ContentWidthChanged(
                    $this->_class, $c
                ));
            }
        }
    }

    public function onContentWidthChanged(Kwf_Component_Event_Component_ContentWidthChanged $event)
    {
        $c = $event->component;
        $this->fireEvent(new Kwf_Component_Event_ComponentClassPage_ContentChanged(
            $this->_class, $c->getPageOrRoot()
        ));
    }

    public function onRecursiveContentWidthChanged(Kwf_Component_Event_Component_RecursiveContentWidthChanged $event)
    {
        $c = $event->component;
        $this->fireEvent(new Kwf_Component_Event_Component_RecursiveContentChanged(
            $this->_class, $c
        ));
    }
}


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKRIBLIGHTWRAP_H
#define NATIVE_EXTENSION_VTK_VTKRIBLIGHTWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkRIBLight.h>

#include "vtkLightWrap.h"
#include "../../plus/plus.h"

class VtkRIBLightWrap : public VtkLightWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkRIBLightWrap(vtkSmartPointer<vtkRIBLight>);
		VtkRIBLightWrap();
		~VtkRIBLightWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetShadows(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Render(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetShadows(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ShadowsOff(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ShadowsOn(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKRIBLIGHTWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKRIBLIGHTWRAP_CLASSDEF
#endif
};

#endif


text:
// InventoryWindow.h

// Representing the UI window for the player inventory

#pragma once

#include "Window.h"

class cInventoryWindow:
	public cWindow
{
	using Super = cWindow;

public:

	cInventoryWindow(cPlayer & a_Player);

	virtual void DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply) override;

	/** Loads the given Recipe into the crafting grid */
	void LoadRecipe(cPlayer & a_Player, UInt32 a_RecipeId);
protected:
	cPlayer & m_Player;
};


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ivanwu.googleapiavailabilitybridge">
</manifest>


text:
define([], function() {
    var notify = function (state, text, length) {
        var timeout;

        if (length) {
            timeout = length;
        } else {
            timeout = 2000;
        }

        return notification = noty({
            text: text,
            type: state,
            layout: "topCenter",
            timeout: timeout
        });
    };

    return notify;
});


text:
var vows = require('vows'),
    assert = require('assert');

var readonly = require('../lib/index.js');
var UnableRewriteException = require('../lib/UnableRewriteException.js');
var _ = require('underscore');

vows.describe('ReadOnly function').addBatch({
    'Restrict rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'Writable from module A': function (topic) {
            var moduleA = {};
            moduleA.obj = topic;
            moduleA.obj.A = 'd';
            assert.equal(moduleA.obj.A, 'd');
        },

        'Not writable from module B': function (topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
            assert.throws(function() { moduleB.obj.B = 'b'; }, UnableRewriteException);
        },
    },

    'Update and rewrite': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can rewrite from A and access from B': function (topic) {
            var moduleA = {};
            var moduleB = {};
            moduleA.obj = topic;
            moduleB.obj = readonly(topic);
            moduleA.obj.A = 'd';

            assert.equal(moduleB.obj.A, 'd');
        }
    },

    'Reference of _original': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },
        'cannot refer _original': function(topic) {
            var moduleB = {};
            moduleB.obj = readonly(topic);
        }
    },

    'Extends test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            return obj;
        },

        'can copy': function(obj) {
            var obj2 = _.clone(obj);
            obj2.A = 'd';
            assert.equal(obj.A, 'a');
        }
    },

    'Getter Test': {
        topic: function() {
            var obj = {'A':'a', 'B':'b', 'C':'c'};
            var cloned = {};

            function makeReadOnlyProperty(cloned, obj, prop) {
                Object.defineProperty(cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
            }

            for (var prop in obj) {
                makeReadOnlyProperty(cloned, obj, prop);
            }

            /*
            function makeGetter(prop) {
                return function() {
                    var p = prop;
                    return obj[p];
                };
            }

            var _cloned = {};
            for (var prop in obj) {
                var getter = makeGetter(prop);
                Object.defineProperty(_cloned, prop, {
                    set: function() {
                        throw new UnableRewriteException('original cannot be rewrite');
                    },
                    get: function() {
                        return obj[prop]
                    },
                    enumerable: true
                });
                _cloned[prop];
            }
            */
            return cloned;
        },

        'get a': function(obj) {
            assert.equal(obj.A, 'a');
        }
    }

}).export(module); // Export the Suite


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef EphemeralRange_h
#define EphemeralRange_h

#include "core/editing/Position.h"

namespace blink {

class Document;
class Range;

// Unlike |Range| objects, |EphemeralRangeTemplate| objects aren't relocated.
// You should not use |EphemeralRangeTemplate| objects after DOM modification.
//
// EphemeralRangeTemplate is supposed to use returning or passing start and end
// position.
//
//  Example usage:
//    Range* range = produceRange();
//    consumeRange(range);
//    ... no DOM modification ...
//    consumeRange2(range);
//
//  Above code should be:
//    EphemeralRangeTemplate range = produceRange();
//    consumeRange(range);
//    ... no DOM modification ...
//    consumeRange2(range);
//
//  Because of |Range| objects consume heap memory and inserted into |Range|
//  object list in |Document| for relocation. These operations are redundant
//  if |Range| objects doesn't live after DOM mutation.
//
template <typename Strategy>
class CORE_TEMPLATE_CLASS_EXPORT EphemeralRangeTemplate final {
    STACK_ALLOCATED();
public:
    EphemeralRangeTemplate(const PositionTemplate<Strategy>& start, const PositionTemplate<Strategy>& end);
    EphemeralRangeTemplate(const EphemeralRangeTemplate& other);
    // |position| should be |Position::isNull()| or in-document.
    explicit EphemeralRangeTemplate(const PositionTemplate<Strategy>& /* position */);
    // When |range| is nullptr, |EphemeralRangeTemplate| is |isNull()|.
    explicit EphemeralRangeTemplate(const Range* /* range */);
    EphemeralRangeTemplate();
    ~EphemeralRangeTemplate();

    EphemeralRangeTemplate<Strategy>& operator=(const EphemeralRangeTemplate<Strategy>& other);

    bool operator==(const EphemeralRangeTemplate<Strategy>& other) const;
    bool operator!=(const EphemeralRangeTemplate<Strategy>& other) const;

    Document& document() const;
    PositionTemplate<Strategy> startPosition() const;
    PositionTemplate<Strategy> endPosition() const;

    // Returns true if |m_startPositoin| == |m_endPosition| or |isNull()|.
    bool isCollapsed() const;
    bool isNull() const
    {
        DCHECK(isValid());
        return m_startPosition.isNull();
    }
    bool isNotNull() const { return !isNull(); }

    DEFINE_INLINE_TRACE()
    {
        visitor->trace(m_startPosition);
        visitor->trace(m_endPosition);
    }

    // |node| should be in-document and valid for anchor node of
    // |PositionTemplate<Strategy>|.
    static EphemeralRangeTemplate<Strategy> rangeOfContents(const Node& /* node */);

private:
    bool isValid() const;

    PositionTemplate<Strategy> m_startPosition;
    PositionTemplate<Strategy> m_endPosition;
#if DCHECK_IS_ON()
    uint64_t m_domTreeVersion;
#endif
};

extern template class CORE_EXTERN_TEMPLATE_EXPORT EphemeralRangeTemplate<EditingStrategy>;
using EphemeralRange = EphemeralRangeTemplate<EditingStrategy>;

extern template class CORE_EXTERN_TEMPLATE_EXPORT EphemeralRangeTemplate<EditingInFlatTreeStrategy>;
using EphemeralRangeInFlatTree = EphemeralRangeTemplate<EditingInFlatTreeStrategy>;

// Returns a newly created |Range| object from |range| or |nullptr| if
// |range.isNull()| returns true.
CORE_EXPORT Range* createRange(const EphemeralRange& /* range */);

} // namespace blink

#endif


text:
package com.ychstudio.systems;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.systems.IteratingSystem;
import com.badlogic.gdx.physics.box2d.Body;
import com.ychstudio.builders.ActorBuilder;
import com.ychstudio.components.Breakable;
import com.ychstudio.components.RigidBody;
import com.ychstudio.components.State;

public class BreakableSystem extends IteratingSystem {

    protected ComponentMapper<Breakable> mBreakable;
    protected ComponentMapper<State> mState;
    protected ComponentMapper<RigidBody> mRigidBody;

    public BreakableSystem() {
        super(Aspect.all(Breakable.class, State.class));
    }

    @Override
    protected void process(int entityId) {
        Breakable breakable = mBreakable.get(entityId);
        State state = mState.get(entityId);
        RigidBody rigidBody = mRigidBody.get(entityId);
        Body body = rigidBody.body;

        switch (breakable.state) {
            case EXPLODING:
                state.setCurrentState("exploding");
                if (state.getStateTime() > 0.6f) {
                    body.getWorld().destroyBody(body);
                    world.delete(entityId);

                    // chance to create PowerUp item
                    if (Math.random() < 0.2) {
                        ActorBuilder actorBuilder = ActorBuilder.init(body.getWorld(), world);
                        actorBuilder.createPowerUp(body.getPosition().x, body.getPosition().y);
                    }
                }
                break;
            case NORMAL:
            default:
                state.setCurrentState("normal");
                break;
        }
    }

}


text:
package info

import (
	"fmt"
	"math"
	"time"

	"github.com/gholt/ring/lowring"
)

type Info struct {
	Time                                  time.Time
	NodeCount                             int
	ActiveNodeCount                       int
	DisabledNodeCount                     int
	DrainingNodeCount                     int
	TotalCapacity                         int
	GroupCount                            int
	GroupToTier                           []int
	TierCount                             int
	TierToGroups                          [][]int
	ReplicaCount                          int
	PartitionCount                        int
	AssignmentCount                       int
	MaxPartitionCount                     int
	Rebalanced                            time.Time
	ReassignmentWait                      int
	MaxReplicaReassignableCount           int
	AssignmentInWaitCountAtRebalancedTime int
	AssignmentInWaitCountAtInfoTime       int
	MostUnderweight                       float64
	MostUnderweightNode                   int
	MostOverweight                        float64
	MostOverweightNode                    int
	ReplicaToMost                         []float64
	ReplicaToMostCount                    []int
	ReplicaToMostNode                     []int
	NodeToAssignmentCount                 []int
	NodeLevelRiskyPartitions              []*InfoRiskyPartition
	TierToRiskyPartitions                 [][]*InfoRiskyPartition
	WorstMirrorPercentage                 float64
	WorstMirrorCount                      int
	WorstMirrorNodeA                      int
	WorstMirrorNodeB                      int
	Warnings                              []string
}

type InfoRiskyPartition struct {
	Partition int
	Nodes     []int
}

func New(ring *lowring.Ring, quick bool, mirroring bool) (*Info, error) {
	info := &Info{Time: time.Now()}
	if quick {
		info.ReplicaCount = len(ring.ReplicaToPartitionToNode)
		info.PartitionCount = len(ring.ReplicaToPartitionToNode[0])
		info.NodeCount = len(ring.NodeToCapacity)
		info.GroupCount = len(ring.GroupToGroup)
		info.AssignmentCount = info.ReplicaCount * info.PartitionCount
		info.MaxPartitionCount = ring.MaxPartitionCount
		info.Rebalanced = ring.Rebalanced
		info.ReassignmentWait = int(ring.ReassignmentWait)
		info.MaxReplicaReassignableCount = int(ring.MaxReplicaReassignableCount)
		for partition := 0; partition < info.PartitionCount; partition++ {
			for replica := 0; replica < info.ReplicaCount; replica++ {
				if ring.ReplicaToPartitionToWait[replica][partition] > 0 {
					info.AssignmentInWaitCountAtRebalancedTime++
				}
			}
		}
	} else {
		if len(ring.NodeToCapacity) != len(ring.NodeToGroup) {
			return nil, fmt.Errorf("len(ring.NodeToCapacity) does not match len(ring.NodeToGroup); %d != %d", len(ring.NodeToCapacity), len(ring.NodeToGroup))
		}
		if len(ring.GroupToGroup) == 0 {
			return nil, fmt.Errorf("ring.GroupToGroup should have at least one entry and does not")
		}
		if ring.GroupToGroup[0] != 0 {
			return nil, fmt.Errorf("ring.GroupToGroup[0] should be 0 and is %d", ring.GroupToGroup[0])
		}
		info.ReplicaCount = len(ring.ReplicaToPartitionToNode)
		if info.ReplicaCount < 1 || info.ReplicaCount > 127 {
			return nil, fmt.Errorf("Replica count is not the range 1-127; it is %d", info.ReplicaCount)
		}
		info.PartitionCount = len(ring.ReplicaToPartitionToNode[0])
		if info.PartitionCount < 1 {
			return nil, fmt.Errorf("ring partition count is less than 1; no ring info to report on")
		}
		if ring.MaxPartitionCount < 1 {
			info.Warnings = append(info.Warnings, fmt.Sprintf("ring.MaxPartitionCount is less than 1 which is weird, but not exactly an error; it was %d", ring.MaxPartitionCount))
		}
		if ring.ReassignmentWait < 1 {
			info.Warnings = append(info.Warnings, fmt.Sprintf("ring.ReassignmentWait is less than 1 which is weird, but not exactly an error; it was %d", ring.ReassignmentWait))
		}
		if ring.MaxReplicaReassignableCount < 1 {
			return nil, fmt.Errorf("ring.MaxReplicaReassignableCount is %d which is less than 1 and will cause problems", ring.MaxReplicaReassignableCount)
		}
		info.NodeCount = len(ring.NodeToCapacity)
		for node := 0; node < info.NodeCount; node++ {
			capacity := ring.NodeToCapacity[node]
			if capacity > 0 {
				info.ActiveNodeCount++
				info.TotalCapacity += capacity
			} else if capacity == 0 {
				info.ActiveNodeCount++
				info.DrainingNodeCount++
			} else {
				info.DisabledNodeCount++
			}
			group := ring.NodeToGroup[node]
			for {
				if group >= len(ring.GroupToGroup) {
					return nil, fmt.Errorf("group %d has no entry in ring.GroupToGroup; len(ring.GroupToGroup) == %d", group, len(ring.GroupToGroup))
				}
				group = ring.GroupToGroup[group]
				if group == 0 {
					break
				}
			}
		}
		info.GroupCount = len(ring.GroupToGroup)
		info.GroupToTier = make([]int, info.GroupCount)
		info.TierToGroups = [][]int{}
		tierParents := []int{0}
		for tier := 0; ; tier++ {
			var nextTierParents []int
			for child, parent := range ring.GroupToGroup {
				if child == 0 {
					continue
				}
				for _, tierParent := range tierParents {
					if parent == tierParent {
						info.GroupToTier[child] = tier
						if tier == len(info.TierToGroups) {
							info.TierToGroups = append(info.TierToGroups, []int{})
						}
						info.TierToGroups[tier] = append(info.TierToGroups[tier], child)
						nextTierParents = append(nextTierParents, child)
						break
					}
				}
			}
			if tier == len(info.TierToGroups) {
				break
			}
			tierParents = nextTierParents
		}
		info.TierCount = len(info.TierToGroups)
		info.AssignmentCount = info.ReplicaCount * info.PartitionCount
		info.MaxPartitionCount = ring.MaxPartitionCount
		info.Rebalanced = ring.Rebalanced
		info.ReassignmentWait = int(ring.ReassignmentWait)
		info.MaxReplicaReassignableCount = int(ring.MaxReplicaReassignableCount)
		infoReplicaToPartitionToWait := make([][]uint16, len(ring.ReplicaToPartitionToWait))
		for replica := 0; replica < info.ReplicaCount; replica++ {
			infoReplicaToPartitionToWait[replica] = make([]uint16, len(ring.ReplicaToPartitionToWait[replica]))
			copy(infoReplicaToPartitionToWait[replica], ring.ReplicaToPartitionToWait[replica])
		}
		minutesElapsed := int64(info.Time.Sub(ring.Rebalanced) / time.Minute)
		if minutesElapsed > int64(ring.ReassignmentWait) || minutesElapsed >= int64(math.MaxUint16) {
			for replica := 0; replica < info.ReplicaCount; replica++ {
				for partition := 0; partition < info.PartitionCount; partition++ {
					infoReplicaToPartitionToWait[replica][partition] = 0
				}
			}
		} else if minutesElapsed > 0 {
			for replica := 0; replica < info.ReplicaCount; replica++ {
				for partition := 0; partition < info.PartitionCount; partition++ {
					if int64(infoReplicaToPartitionToWait[replica][partition])-minutesElapsed <= 0 {
						infoReplicaToPartitionToWait[replica][partition] = 0
					} else {
						infoReplicaToPartitionToWait[replica][partition] -= uint16(minutesElapsed)
					}
				}
			}
		}
		info.NodeToAssignmentCount = make([]int, info.NodeCount)
		replicaToNodeToCount := make([][]int, info.ReplicaCount)
		for replica := 0; replica < info.ReplicaCount; replica++ {
			replicaToNodeToCount[replica] = make([]int, info.NodeCount)
		}
		info.TierToRiskyPartitions = make([][]*InfoRiskyPartition, info.TierCount)
		var nodeLevelRiskyPartition *InfoRiskyPartition
		tierToRiskyPartition := make([]*InfoRiskyPartition, info.TierCount)
		nodeUsed := make([]bool, info.NodeCount)
		nodeUsed_Clearer := make([]bool, info.NodeCount)
		groupUsed := make([]bool, info.GroupCount)
		groupUsed_Clearer := make([]bool, info.GroupCount)
		for partition := 0; partition < info.PartitionCount; partition++ {
			for replica := 0; replica < info.ReplicaCount; replica++ {
				if replica == 0 {
					copy(nodeUsed, nodeUsed_Clearer)
					copy(groupUsed, groupUsed_Clearer)
					nodeLevelRiskyPartition = nil
					for tier := 0; tier < info.TierCount; tier++ {
						tierToRiskyPartition[tier] = nil
					}
				}
				node := ring.ReplicaToPartitionToNode[replica][partition]
				if nodeUsed[node] {
					if nodeLevelRiskyPartition == nil {
						nodeLevelRiskyPartition = &InfoRiskyPartition{Partition: partition, Nodes: []int{int(node)}}
						info.NodeLevelRiskyPartitions = append(info.NodeLevelRiskyPartitions, nodeLevelRiskyPartition)
					} else {
						nodeLevelRiskyPartition.Nodes = append(nodeLevelRiskyPartition.Nodes, int(node))
					}
				}
				nodeUsed[node] = true
				group := ring.NodeToGroup[node]
				for {
					if groupUsed[group] {
						tier := info.GroupToTier[group]
						riskyPartition := tierToRiskyPartition[tier]
						if riskyPartition == nil {
							riskyPartition = &InfoRiskyPartition{Partition: partition, Nodes: []int{int(node)}}
							tierToRiskyPartition[tier] = riskyPartition
							info.TierToRiskyPartitions[tier] = append(info.TierToRiskyPartitions[tier], riskyPartition)
						} else {
							riskyPartition.Nodes = append(riskyPartition.Nodes, int(node))
						}
					}
					groupUsed[group] = true
					group = ring.GroupToGroup[group]
					if group == 0 {
						break
					}
				}
				info.NodeToAssignmentCount[node]++
				replicaToNodeToCount[replica][node]++
				if ring.ReplicaToPartitionToWait[replica][partition] > 0 {
					info.AssignmentInWaitCountAtRebalancedTime++
				}
				if infoReplicaToPartitionToWait[replica][partition] > 0 {
					info.AssignmentInWaitCountAtInfoTime++
				}
			}
		}
		info.MostOverweight = -math.MaxFloat64
		info.MostUnderweight = math.MaxFloat64
		info.ReplicaToMost = make([]float64, info.ReplicaCount)
		info.ReplicaToMostCount = make([]int, info.ReplicaCount)
		info.ReplicaToMostNode = make([]int, info.ReplicaCount)
		info.WorstMirrorPercentage = 0
		info.WorstMirrorCount = -1
		info.WorstMirrorNodeA = -1
		info.WorstMirrorNodeB = -1
		for node := 0; node < info.NodeCount; node++ {
			capacity := ring.NodeToCapacity[node]
			nodeAssignmentCount := info.NodeToAssignmentCount[node]
			if capacity < 0 {
				if nodeAssignmentCount != 0 {
					return nil, fmt.Errorf("ring has %d assignments to node %d which is disabled with a capacity of %d", nodeAssignmentCount, node, capacity)
				}
				continue
			}
			if capacity == 0 {
				if nodeAssignmentCount != 0 {
					info.Warnings = append(info.Warnings, fmt.Sprintf("ring has %d assignments to node %d which is draining with a capacity of %d", nodeAssignmentCount, node, capacity))
				}
				continue
			}
			desire := float64(capacity) / float64(info.TotalCapacity) * float64(info.AssignmentCount)
			weight := (float64(nodeAssignmentCount) - desire) / desire
			if weight > info.MostOverweight {
				info.MostOverweight = weight
				info.MostOverweightNode = node
			}
			if weight < info.MostUnderweight {
				info.MostUnderweight = weight
				info.MostUnderweightNode = node
			}
			for replica := 0; replica < info.ReplicaCount; replica++ {
				replicaCount := replicaToNodeToCount[replica][node]
				replicaMost := float64(replicaCount) / float64(nodeAssignmentCount)
				if replicaMost > info.ReplicaToMost[replica] {
					info.ReplicaToMost[replica] = replicaMost
					info.ReplicaToMostCount[replica] = replicaCount
					info.ReplicaToMostNode[replica] = node
				}
			}
			if mirroring {
				ring.FillReplicaToNodeToPartitions()
				usedPartition := make([]bool, info.AssignmentCount)
				for replica := 0; replica < info.ReplicaCount; replica++ {
					for _, partition := range ring.ReplicaToNodeToPartitions[replica][node] {
						usedPartition[partition] = true
					}
				}
				for nodeB := node + 1; nodeB < info.NodeCount; nodeB++ {
					mirrorCount := 0
					for replica := 0; replica < info.ReplicaCount; replica++ {
						for _, partition := range ring.ReplicaToNodeToPartitions[replica][nodeB] {
							if usedPartition[partition] {
								mirrorCount++
							}
						}
					}
					if float64(mirrorCount)/float64(info.NodeToAssignmentCount[node]) > info.WorstMirrorPercentage {
						info.WorstMirrorPercentage = float64(mirrorCount) / float64(info.NodeToAssignmentCount[node])
						info.WorstMirrorCount = mirrorCount
						info.WorstMirrorNodeA = node
						info.WorstMirrorNodeB = nodeB
					}
					if float64(mirrorCount)/float64(info.NodeToAssignmentCount[nodeB]) > info.WorstMirrorPercentage {
						info.WorstMirrorPercentage = float64(mirrorCount) / float64(info.NodeToAssignmentCount[nodeB])
						info.WorstMirrorCount = mirrorCount
						info.WorstMirrorNodeA = node
						info.WorstMirrorNodeB = nodeB
					}
				}
			}
		}
	}
	return info, nil
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 16(1/2): 49 (1918)

#### Original name
Sphaeria cooperta Desm.

### Remarks
null


text:
package org.jetbrains.plugins.groovy.codeInspection.declaration;

import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.SuperMethodsSearch;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor;
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrModifierFix;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;

import javax.swing.*;

import static org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle.message;

public class GrMethodMayBeStaticInspection extends BaseInspection {
  public boolean myIgnoreTraitMethods = true;
  public boolean myOnlyPrivateOrFinal = false;
  public boolean myIgnoreEmptyMethods = true;

  @Override
  public JComponent createOptionsPanel() {
    final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this);
    optionsPanel.addCheckbox(message("method.may.be.static.option.ignore.trait.methods"), "myIgnoreTraitMethods");
    optionsPanel.addCheckbox(message("method.may.be.static.only.private.or.final.option"), "myOnlyPrivateOrFinal");
    optionsPanel.addCheckbox(message("method.may.be.static.ignore.empty.method.option"), "myIgnoreEmptyMethods");
    return optionsPanel;
  }

  @NotNull
  @Override
  protected BaseInspectionVisitor buildVisitor() {
    return new BaseInspectionVisitor() {
      @Override
      public void visitMethod(@NotNull GrMethod method) {
        if (checkMethod(method)) {
          final GrModifierFix modifierFix = new GrModifierFix(method, PsiModifier.STATIC, false, true, descriptor -> {
            final PsiElement element = descriptor.getPsiElement();
            final PsiElement parent = element.getParent();
            assert parent instanceof GrMethod : "element: " + element + ", parent:" + parent;
            return ((GrMethod)parent).getModifierList();
          });
          registerError(method.getNameIdentifierGroovy(), message("method.may.be.static"), new LocalQuickFix[]{modifierFix}, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
        }
      }
    };
  }

  private boolean checkMethod(final GrMethod method) {
    if (method.hasModifierProperty(PsiModifier.STATIC)) return false;
    if (method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) return false;
    if (method.getModifierList().hasExplicitModifier(PsiModifier.ABSTRACT)) return false;
    if (method.isConstructor()) return false;

    PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) return false;

    if (myIgnoreTraitMethods && GrTraitUtil.isTrait(containingClass)) return false;
    if (SuperMethodsSearch.search(method, null, true, false).findFirst() != null) return false;
    if (OverridingMethodsSearch.search(method).findFirst() != null) return false;
    if (ignoreMethod(method)) return false;

    if (myOnlyPrivateOrFinal) {
      if (!(method.hasModifierProperty(PsiModifier.FINAL) || method.hasModifierProperty(PsiModifier.PRIVATE))) return false;
    }

    GrOpenBlock block = method.getBlock();
    if (block == null) return false;
    if (myIgnoreEmptyMethods && block.getStatements().length == 0) return false;

    if (containingClass.getContainingClass() != null && !containingClass.hasModifierProperty(PsiModifier.STATIC)) {
      return false;
    }

    for (Condition<PsiElement> addin : InspectionManager.CANT_BE_STATIC_EXTENSION.getExtensionList()) {
      if (addin.value(method)) return false;
    }

    MethodMayBeStaticVisitor visitor = new MethodMayBeStaticVisitor();
    method.accept(visitor);
    return !visitor.haveInstanceRefsOutsideClosures();
  }

  private static boolean ignoreMethod(GrMethod method) {
    final GrParameter[] parameters = method.getParameters();
    if (method.getName().equals("propertyMissing") && (parameters.length == 2 || parameters.length == 1)) return true;
    if (method.getName().equals("methodMissing") && (parameters.length == 2 || parameters.length == 1)) return true;
    if (method.getContainingClass() instanceof PsiAnonymousClass) return true;

    for (GrMethodMayBeStaticInspectionFilter filter : GrMethodMayBeStaticInspectionFilter.EP_NAME.getExtensions()) {
      if (filter.isIgnored(method)) {
        return true;
      }
    }

    return false;
  }

  private static boolean isPrintOrPrintln(PsiElement element) {
    return element instanceof GrGdkMethod &&
           ("print".equals(((PsiMethod)element).getName()) || "println".equals(((PsiMethod)element).getName()));
  }

  private static class MethodMayBeStaticVisitor extends GroovyRecursiveElementVisitor {
    private boolean myHaveInstanceRefs = false;

    @Override
    public void visitElement(@NotNull GroovyPsiElement element) {
      if (myHaveInstanceRefs) return;

      super.visitElement(element);
    }

    @Override
    public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
      if (myHaveInstanceRefs) return;

      if (PsiUtil.isSuperReference(referenceExpression)) {
        registerInstanceRef();
        return;
      }
      if (PsiUtil.isThisReference(referenceExpression)) {
        if (!(referenceExpression.getParent() instanceof GrReferenceExpression)) {//if we have reference parent -- check it instead of this ref
          registerInstanceRef();
        }

        return;
      }

      GrExpression qualifier = referenceExpression.getQualifierExpression();
      if (qualifier == null || PsiUtil.isThisOrSuperRef(qualifier)) {
        GroovyResolveResult result = referenceExpression.advancedResolve();
        PsiElement element = result.getElement();
        if (isPrintOrPrintln(element)) return;

        PsiElement resolveContext = result.getCurrentFileResolveContext();
        if (qualifier == null && resolveContext != null) return;
        if (element instanceof PsiClass && ((PsiClass)element).getContainingClass() == null) return;
        if (element instanceof PsiMember && !((PsiMember)element).hasModifierProperty(PsiModifier.STATIC)) {
          registerInstanceRef();
        }
        if (element == null) {
          registerInstanceRef();
        }
      }
      else {
        super.visitReferenceExpression(referenceExpression);
      }
    }

    private void registerInstanceRef() {
      myHaveInstanceRefs = true;
    }

    @Override
    public void visitCodeReferenceElement(@NotNull GrCodeReferenceElement refElement) {
      super.visitCodeReferenceElement(refElement);

      if (myHaveInstanceRefs) return;

      final PsiElement resolvedElement = refElement.resolve();
      if (!(resolvedElement instanceof PsiClass)) return;

      final PsiClass aClass = (PsiClass)resolvedElement;
      final PsiElement scope = aClass.getScope();

      if (!(scope instanceof PsiClass)) return;
      if (!aClass.hasModifierProperty(PsiModifier.STATIC)) {
        registerInstanceRef();
      }
    }

    public boolean haveInstanceRefsOutsideClosures() {
      return myHaveInstanceRefs;
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace STVM.Wrapper.Http
{
    public class httpRequest
    {
        public class httpParameters : Dictionary<string, string>
        {
            public string UrlEncode
            {
                get { return string.Join("&", this.Select(param => param.Key + "=" + System.Web.HttpUtility.UrlEncode(param.Value))); }
            }

            public byte[] ByteEncode
            {
                get { return System.Text.Encoding.ASCII.GetBytes(this.UrlEncode); }
            }
        }

        public event ServerErrorEventHandler ServerErrorEvent;
        public httpParameters GetParameters;
        public httpParameters PostParameters;
        public string Response { get; private set; }

        public HttpStatusCode Get(string URL)
        {
            string getURL = URL + "?" + GetParameters.UrlEncode;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getURL);
            request.Method = "GET";

            try
            {
                //Send Web-Request and receive a Web-Response
                HttpWebResponse serverResponse = (HttpWebResponse)request.GetResponse();

                //Translate data from the Web-Response to a string
                Stream dataStream = serverResponse.GetResponseStream();
                StreamReader streamreader = new StreamReader(dataStream, Encoding.UTF8);
                Response = streamreader.ReadToEnd();
                streamreader.Close();

                // clear request parameters
                GetParameters.Clear();
                PostParameters.Clear();

                return serverResponse.StatusCode;
            }
            catch (WebException e)
            {
                if (ServerErrorEvent != null) { ServerErrorEvent(new ServerErrorEventArgs(e.Message)); }
                return HttpStatusCode.ServiceUnavailable;
            }
        }

        public HttpStatusCode Post(string URL)
        {
            string getURL = URL + "?" + GetParameters.UrlEncode;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getURL);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            try
            {
                //Attach data and send web request
                byte[] postData = this.PostParameters.ByteEncode;
                request.ContentLength = postData.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(postData, 0, postData.Length);
                dataStream.Close();

                //Receive a Web-Response
                HttpWebResponse serverResponse = (HttpWebResponse)request.GetResponse();

                //Translate data from the Web-Response to a string
                dataStream = serverResponse.GetResponseStream();
                StreamReader streamreader = new StreamReader(dataStream, Encoding.UTF8);
                Response = streamreader.ReadToEnd();
                streamreader.Close();

                // clear request parameters
                GetParameters.Clear();
                PostParameters.Clear();

                return serverResponse.StatusCode;
            }
            catch (WebException e)
            {
                if (ServerErrorEvent != null) { ServerErrorEvent(new ServerErrorEventArgs(e.Message)); }
                return HttpStatusCode.ServiceUnavailable;
            }
        }

        public httpRequest()
        {
            GetParameters = new httpParameters();
            PostParameters = new httpParameters();
        }

    }

    // event fired on server error
    public delegate void ServerErrorEventHandler(ServerErrorEventArgs e);
    public class ServerErrorEventArgs : EventArgs
    {
        public readonly string Message;
        public ServerErrorEventArgs(string message)
        {
            Message = message;
        }
    }

}


text:
<?php

namespace Matryoshka\Model\Hydrator\Strategy;

use DateTime;
use Matryoshka\Model\Exception;
use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;

/**
 * Class DateTimeStrategy
 */
class DateTimeStrategy implements StrategyInterface, NullableStrategyInterface
{
    use NullableStrategyTrait;

    /**
     * @var string
     */
    protected $format = DateTime::ISO8601;

    /**
     * @param string|null $format
     */
    public function __construct($format = null)
    {
        if ($format !== null) {
            $this->setFormat($format);
        }
    }

    /**
     * {@inheritdoc}
     * Convert a string value into a DateTime object
     *
     * @param string|int|null $value
     * @return \DateTime|null
     */
    public function hydrate($value)
    {
        if ($this->nullable && $value === null) {
            return null;
        }

        if (is_string($value) || is_int($value)) {
            if ($dateTime = DateTime::createFromFormat($this->getFormat(), $value)) {
                return $dateTime;
            }

            throw new Exception\InvalidArgumentException(sprintf(
                'Invalid format or value: format must be a string representing a valid \DateTime format, "%s" given;' .
                'value must be a string representing the time according to \DateTime::createFromFormat(), "%s" given.',
                $this->getFormat(),
                $value
            ));
        }

        throw new Exception\InvalidArgumentException(sprintf(
            'Invalid value: must be a string or integer representing the time according to the format, "%s" given',
            is_object($value) ? get_class($value) : gettype($value)
        ));
    }

    /**
     * {@inheritdoc}
     * Convert a DateTime object into a string
     *
     * @param \DateTime|null $value
     * @return string|null
     */
    public function extract($value)
    {
        if ($value instanceof DateTime) {
            return $value->format($this->getFormat());
        }

        if ($this->nullable && $value === null) {
            return null;
        }

        throw new Exception\InvalidArgumentException(sprintf(
            'Invalid value: must be an instance of DateTime, "%s" given.',
            is_object($value) ? get_class($value) : gettype($value)
        ));
    }

    /**
     * Set format
     *
     * @param string $format
     * @return DateTimeStrategy
     */
    public function setFormat($format)
    {
        $this->format = (string) $format;
        return $this;
    }

    /**
     * Get format
     *
     * @return string
     */
    public function getFormat()
    {
        return $this->format;
    }
}


text:
package no.asgari.civilization.server.application;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.java8.auth.Authenticator;
import lombok.Cleanup;
import no.asgari.civilization.server.model.Player;
import org.apache.commons.codec.digest.DigestUtils;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.JacksonDBCollection;

import java.util.Optional;

public class CivAuthenticator implements Authenticator<BasicCredentials, Player> {
    private final JacksonDBCollection<Player, String> playerCollection;

    public CivAuthenticator(DB db) {
        this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
    }

    @Override
    public Optional<Player> authenticate(BasicCredentials credentials) {
        @Cleanup DBCursor<Player> dbPlayer = playerCollection.find(
                DBQuery.is("username", credentials.getUsername()), new BasicDBObject());

        if (dbPlayer == null || !dbPlayer.hasNext()) {
            return Optional.empty();
        }

        Player player = dbPlayer.next();

        CivSingleton.instance().playerCache().put(player.getId(), player.getUsername());

        if (player.getPassword().equals(DigestUtils.sha1Hex(credentials.getPassword()))) {
            return Optional.of(player);
        }
        return Optional.empty();
    }
}


text:
<?php

namespace Puli\Manager\Api\Factory\Generator;

use Puli\Manager\Api\Php\Method;

/**
 * Generates the instantiation code for a service.
 *
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
interface ServiceGenerator
{
    /**
     * Generates a "new Service()" statement stored in the given variable.
     *
     * The resulting code could look something like this:
     *
     * ```php
     * $dependency = new Dependency();
     * $varName = new Service($dependency);
     * ```
     *
     * This code is added to the method passed in the second parameter.
     *
     * @param string            $varName           The variable name without
     *                                             leading "$".
     * @param Method            $targetMethod      The method in which the code
     *                                             is stored.
     * @param GeneratorRegistry $generatorRegistry The generator registry.
     * @param array             $options           Additional implementation
     *                                             specific options.
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array());
}


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the BasicDependency class.
 * @constructor
 * Deployment dependency information.
 *
 * @member {string} [id] The ID of the dependency.
 *
 * @member {string} [resourceType] The dependency resource type.
 *
 * @member {string} [resourceName] The dependency resource name.
 *
 */
class BasicDependency {
  constructor() {
  }

  /**
   * Defines the metadata of BasicDependency
   *
   * @returns {object} metadata of BasicDependency
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'BasicDependency',
      type: {
        name: 'Composite',
        className: 'BasicDependency',
        modelProperties: {
          id: {
            required: false,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          resourceType: {
            required: false,
            serializedName: 'resourceType',
            type: {
              name: 'String'
            }
          },
          resourceName: {
            required: false,
            serializedName: 'resourceName',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = BasicDependency;


text:
class CreateBlogComments < ActiveRecord::Migration
  def change
    create_table :blog_comments do |t|
      t.string :name, null: false
      t.string :email, null: false
      t.string :website
      t.text :body, null: false
      t.references :post, null: false
      t.string :state

      t.timestamps
    end
    add_index :blog_comments, :post_id
  end
end