text:
// FIXME: get rid of this class, as I don't think it adds anything of
// real value..? 20021126 mortene.
//
// UPDATE: voxel data should be stored in SoVolumeData, not in a(ny)
// reader. 20041008 mortene.

/*!
  \class SoVRMemReader VolumeViz/readers/SoVRMemReader.h
  \brief FIXME: doc
*/

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

#include <VolumeViz/readers/SoVRMemReader.h>
#include <VolumeViz/misc/CvrUtil.h>
#include <VolumeViz/misc/CvrVoxelChunk.h>

#include <Inventor/errors/SoDebugError.h>

#include <string.h> // memcpy()

class SoVRMemReaderP {
public:
  SoVRMemReaderP(SoVRMemReader * master) {
    this->master = master;

    this->dimensions = SbVec3s(0, 0, 0);
    this->dataType = SoVolumeData::UNSIGNED_BYTE;
  }

  SbVec3s dimensions;
  SoVolumeData::DataType dataType;

private:
  SoVRMemReader * master;
};

#define PRIVATE(p) (p->pimpl)
#define PUBLIC(p) (p->master)

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

SoVRMemReader::SoVRMemReader(void)
{
  PRIVATE(this) = new SoVRMemReaderP(this);
}

SoVRMemReader::~SoVRMemReader()
{
  delete PRIVATE(this);
}

void
SoVRMemReader::setUserData(void * data)
{
}

void SoVRMemReader::getDataChar(SbBox3f & size,
                                SoVolumeData::DataType & type,
                                SbVec3s & dim)
{
  type = PRIVATE(this)->dataType;
  dim = PRIVATE(this)->dimensions;

  const short largestdimension = SbMax(dim[0], SbMax(dim[1], dim[2]));
  SbVec3f normdims(dim[0], dim[1], dim[2]);
  normdims /= float(largestdimension);
  normdims *= 2.0f;
  size.setBounds(-normdims / 2.0f, normdims / 2.0f);
}

void
SoVRMemReader::getSubSlice(SbBox2s & subslice, int slicenumber, void * data)
{
  unsigned int bytesprvoxel;
  switch (PRIVATE(this)->dataType) {
  case SoVolumeData::UNSIGNED_BYTE: bytesprvoxel = 1; break;
  case SoVolumeData::UNSIGNED_SHORT: bytesprvoxel = 2; break;
  default: assert(FALSE); break;
  }

  // FIXME: interface of buildSubPage() should be improved to avoid
  // this roundabout way of clipping out a slice.  20021203 mortene.
  CvrVoxelChunk vc(PRIVATE(this)->dimensions, bytesprvoxel, this->m_data);
  CvrVoxelChunk * output = vc.buildSubPage(2 /* Z */, slicenumber, subslice);
  (void)memcpy(data, output->getBuffer(), output->bufferSize());
  delete output;
}

void
SoVRMemReader::setData(const SbVec3s &dimensions,
                       void * data,
                       SoVolumeData::DataType type)
{
  PRIVATE(this)->dimensions = dimensions;
  // FIXME: this is completely bogus use of SoVolumeReader::m_data --
  // this is *not* where the voxel data is supposed to be stored. That
  // is inside SoVolumeData. 20041008 mortene.
  this->m_data = data;
  PRIVATE(this)->dataType = type;
}


text:
class Inspection < ActiveRecord::Base
  include Statesman::Adapters::ActiveRecordQueries

  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  belongs_to :inspection_type
  belongs_to :facility
  has_many   :inspection_transitions, class_name: "InspectionTransition"

  sortable by: ["start_date DESC"], default: "start_date DESC"
  has_ransackable_associations %w(facility)
  ransack_can_autocomplete

  scope :text_search, ->(query) { search('name_cont' => query).result }

  def self.search(params={})
    byebug
  end

  def self.per_page
    20
  end

  def state_machine
    @state_machine ||= InspectionStateMachine.new(self,transition_class:InspectionTransition)
  end

  def self.transition_class
    InspectionTransition
  end

  def self.initial_state
    :scheduled
  end

  # @return date range
  def date_range
    start_date..end_date
  end

  def inspection_number
    name = facility.establishment.short_name.upcase
    hex =  id.to_s(16)
    "INSP-#{name}-#{hex}"
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace UnityTest
{
    [Serializable]
    public class NetworkResultsReceiver : EditorWindow
    {
        public static NetworkResultsReceiver Instance = null;

        private string m_StatusLabel;
        private TcpListener m_Listener;

        [SerializeField]
        private PlatformRunnerConfiguration m_Configuration;

        private List<ITestResult> m_TestResults = new List<ITestResult>();

        #region steering variables
        private bool m_RunFinished;
        private bool m_Repaint;

        private TimeSpan m_TestTimeout = TimeSpan.Zero;
        private DateTime m_LastMessageReceived;
        private bool m_Running;

        public TimeSpan ReceiveMessageTimeout = TimeSpan.FromSeconds(30);
        private readonly TimeSpan m_InitialConnectionTimeout = TimeSpan.FromSeconds(300);
        private bool m_TestFailed;
        #endregion

        private void AcceptCallback(TcpClient client)
        {
            m_Repaint = true;
            ResultDTO dto;
            try
            {
                m_LastMessageReceived = DateTime.Now;
                using (var stream = client.GetStream())
                {
                    var bf = new DTOFormatter();
                    dto = (ResultDTO)bf.Deserialize(stream);
                    stream.Close();
                }
                client.Close();
            }
            catch (ObjectDisposedException e)
            {
                Debug.LogException(e);
                m_StatusLabel = "Got disconnected";
                return;
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                return;
            }

            switch (dto.messageType)
            {
                case ResultDTO.MessageType.TestStarted:
                    m_StatusLabel = dto.testName;
                    m_TestTimeout = TimeSpan.FromSeconds(dto.testTimeout);
                    break;
                case ResultDTO.MessageType.TestFinished:
                    m_TestResults.Add(dto.testResult);
                    m_TestTimeout = TimeSpan.Zero;
                    if (dto.testResult.Executed && dto.testResult.ResultState != TestResultState.Ignored && !dto.testResult.IsSuccess)
                        m_TestFailed = true;
                    break;
                case ResultDTO.MessageType.RunStarted:
                    m_TestResults = new List<ITestResult>();
                    m_StatusLabel = "Run started: " + dto.loadedLevelName;
                    break;
                case ResultDTO.MessageType.RunFinished:
                    WriteResultsToLog(dto, m_TestResults);
                    if (!string.IsNullOrEmpty(m_Configuration.resultsDir))
                    {
                        var platform = m_Configuration.runInEditor ? "Editor" : m_Configuration.buildTarget.ToString();
                        var resultWriter = new XmlResultWriter(dto.loadedLevelName, platform, m_TestResults.ToArray());
                        try
                        {
                            if (!Directory.Exists(m_Configuration.resultsDir))
                            {
                                Directory.CreateDirectory(m_Configuration.resultsDir);
                            }
                            var filePath = Path.Combine(m_Configuration.resultsDir, dto.loadedLevelName + ".xml");
                            File.WriteAllText(filePath, resultWriter.GetTestResult());
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                    if (dto.levelCount - dto.loadedLevel == 1)
                    {
                        m_Running = false;
                        m_RunFinished = true;
                    }
                    break;
                case ResultDTO.MessageType.Ping:
                    break;
            }
        }

        private void WriteResultsToLog(ResultDTO dto, List<ITestResult> list)
        {
            string result = "Run finished for: " + dto.loadedLevelName;
            var failCount = list.Count(t => t.Executed && !t.IsSuccess);
            if (failCount == 0)
                result += "\nAll tests passed";
            else
                result += "\n" + failCount + " tests failed";

            if (failCount == 0)
                Debug.Log(result);
            else
                Debug.LogWarning(result);
        }

        public void Update()
        {
            if (EditorApplication.isCompiling
                && m_Listener != null)
            {
                m_Running = false;
                m_Listener.Stop();
                return;
            }

            if (m_Running)
            {
                try
                {
                    if (m_Listener != null && m_Listener.Pending())
                    {
                        using (var client = m_Listener.AcceptTcpClient())
                        {
                            AcceptCallback(client);
                            client.Close();
                        }
                    }
                }
                catch (InvalidOperationException e)
                {
                    m_StatusLabel = "Exception happened: " + e.Message;
                    Repaint();
                    Debug.LogException(e);
                }
            }

            if (m_Running)
            {
                var adjustedtestTimeout =  m_TestTimeout.Add(m_TestTimeout);
                var timeout = ReceiveMessageTimeout > adjustedtestTimeout ? ReceiveMessageTimeout : adjustedtestTimeout;
                if ((DateTime.Now - m_LastMessageReceived) > timeout)
                {
                    Debug.LogError("Timeout when waiting for test results");
                    m_RunFinished = true;
                }
            }
            if (m_RunFinished)
            {
                if (InternalEditorUtility.inBatchMode)
                    EditorApplication.Exit(m_TestFailed ? Batch.returnCodeTestsFailed : Batch.returnCodeTestsOk);
                Close();
            }
            if (m_Repaint) Repaint();
        }

        public void OnEnable()
        {
            minSize = new Vector2(300, 100);

            //Unity 5.0.0 quirk throws an exception on setting the postion when in batch mode
            if( !UnityEditorInternal.InternalEditorUtility.inBatchMode )
                position = new Rect(position.xMin, position.yMin, 300, 100);
			titleContent = new GUIContent("Test run monitor");
            Instance = this;
            m_StatusLabel = "Initializing...";
            if (EditorApplication.isCompiling) return;
            EnableServer();
        }

        private void EnableServer()
        {
			if (m_Configuration == null) throw new Exception("No result receiver server configuration.");

            var ipAddress = IPAddress.Any;
            if (m_Configuration.ipList != null && m_Configuration.ipList.Count == 1)
                ipAddress = IPAddress.Parse(m_Configuration.ipList.Single());

            var ipAddStr = Equals(ipAddress, IPAddress.Any) ? "[All interfaces]" : ipAddress.ToString();

			m_Listener = new TcpListener(ipAddress, m_Configuration.port);
            m_StatusLabel = "Waiting for connection on: " + ipAddStr + ":" + m_Configuration.port;

            try
            {
                m_Listener.Start(100);
            }
            catch (SocketException e)
            {
                m_StatusLabel = "Exception happened: " + e.Message;
                Repaint();
                Debug.LogException(e);
            }
            m_Running = true;
            m_LastMessageReceived = DateTime.Now + m_InitialConnectionTimeout;
        }

        public void OnDisable()
        {
            Instance = null;
            if (m_Listener != null)
                m_Listener.Stop();
        }

        public void OnGUI()
        {
            EditorGUILayout.LabelField("Status:", EditorStyles.boldLabel);
            EditorGUILayout.LabelField(m_StatusLabel);
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Stop"))
            {
                StopReceiver();
                if (InternalEditorUtility.inBatchMode)
                    EditorApplication.Exit(Batch.returnCodeRunError);
            }
        }

        public static void StartReceiver(PlatformRunnerConfiguration configuration)
        {
            var w = (NetworkResultsReceiver)GetWindow(typeof(NetworkResultsReceiver), false);
            w.SetConfiguration(configuration);
			if (!EditorApplication.isCompiling)
			{
				w.EnableServer();
			}
            w.Show(true);
        }

        private void SetConfiguration(PlatformRunnerConfiguration configuration)
        {
            m_Configuration = configuration;
        }

        public static void StopReceiver()
        {
            if (Instance == null) return;
            Instance.Close();
        }
    }
}


text:
#import "SCGeopackageHelper.h"
#import "SpatialConnect.h"
#import "SpatialConnectHelper.h"
#import <XCTest/XCTest.h>

@interface SCRasterTest : XCTestCase
@property(nonatomic) SpatialConnect *sc;
@end

@implementation SCRasterTest

@synthesize sc;

- (void)setUp {
  [super setUp];
  self.sc = [SpatialConnectHelper loadConfigAndStartServices];
}

- (void)tearDown {
  [super tearDown];
  [self.sc stopAllServices];
}

- (void)testRasterTableInfo {
  XCTestExpectation *expect = [self expectationWithDescription:@"Table Info"];
  [[SCGeopackageHelper loadGPKGRasterStore:self.sc]
      subscribeNext:^(SCDataStore *ds) {
        id<SCRasterStore> rs = (id<SCRasterStore>)[[self.sc dataService]
            storeByIdentifier:ds.storeId];
        XCTAssertNotNil(rs);
        [expect fulfill];
      }];
  [self waitForExpectationsWithTimeout:120.0 handler:nil];
}

@end


text:
namespace asio = boost::asio;
using namespace am;

//-----------------------------------------------------------------------------
AssetManagerClient::AssetManagerClient(const std::string& base_address,
    const std::string& host,
    long tcp_port,
    long udp_port)
: base_address_(base_address)
, options_(0)
, start_bundle_(false)
{
  tcp_client_ = new TCPClient(host, tcp_port);
  udp_client_ = new UDPClient(host, udp_port);
}

AssetManagerClient::~AssetManagerClient()
{
  delete tcp_client_;
  delete udp_client_;
}

void AssetManagerClient::SetOption(Option option)
{
  options_ ^= option;
}

void AssetManagerClient::SetSystemMute(bool mute)
{
  tnyosc::Message msg("/AM/Mute");
  msg.append(mute ? 1 : 0);
  SendCoreMessage(msg.byte_array());
}

void AssetManagerClient::SetSystemVolume(float volume)
{
  if (0.0f <= volume && volume <= 1.0f) {
    tnyosc::Message msg("/AM/Volume");
    msg.append(20*log10(volume));
    SendCoreMessage(msg.byte_array());
  }
}

void AssetManagerClient::Load()
{
  tnyosc::Message msg("/AM/Load");
  msg.append(base_address_);
  SendCoreMessage(msg.byte_array());
}

void AssetManagerClient::Unload()
{
  tnyosc::Message msg("/AM/Unload");
  msg.append(base_address_);
  SendCoreMessage(msg.byte_array());
}

void AssetManagerClient::SetMute(bool mute)
{
  tnyosc::Message msg("/AM/Project/Mute");
  msg.append(base_address_);
  msg.append(mute ? 1 : 0);
  SendCoreMessage(msg.byte_array());
}

void AssetManagerClient::SetVolume(float volume)
{
  if (0.0f <= volume && volume <= 1.0f) {
    tnyosc::Message msg("/AM/Project/Volume");
    msg.append(base_address_);
    msg.append(20*log10(volume));
    SendCoreMessage(msg.byte_array());
  }
}

void AssetManagerClient::SendCoreMessage(const std::vector<char>& msg)
{
  if (options_ & CORE_USE_UDP) {
    if (start_bundle_)
      AppendBundle(udp_bundle_, msg);
    else
      udp_client_->Send(msg);
  } else {
    tcp_client_->Send(msg);
  }
}

void AssetManagerClient::SendCustomTCP(const std::string& url,
    const char* format, ...)
{
  std::vector<char> buf(MAX_MESSAGE_SIZE);
  std::string address(base_address_);
  address.append(url);
  va_list ap;
  va_start(ap, format);
  int32_t size = voscpack((uint8_t*)&buf[0], address.c_str(), format, ap);
  va_end(ap);
  if (size > 0) {
    buf.resize(size);
    tcp_client_->Send(buf);
  }
}

void AssetManagerClient::SendCustomUDP(const std::string& url,
    const char* format, ...)
{
  std::vector<char> buf(MAX_MESSAGE_SIZE);
  std::string address(base_address_);
  address.append(url);
  va_list ap;
  va_start(ap, format);
  int32_t size = voscpack((uint8_t*)&buf[0], address.c_str(), format, ap);
  va_end(ap);
  if (size > 0) {
    buf.resize(size);
    if (start_bundle_)
      AppendBundle(udp_bundle_, buf);
    else
      udp_client_->Send(buf);
  }
}

void AssetManagerClient::StartBundle()
{
  if (start_bundle_) EndBundle();
  NewBundle(udp_bundle_);
  start_bundle_ = true;
}

void AssetManagerClient::EndBundle()
{
  if (udp_bundle_.size() > 16) {
    udp_client_->Send(udp_bundle_);
    udp_bundle_.clear();
  }
  start_bundle_ = false;
}

void AssetManagerClient::NewBundle(std::vector<char>& bundle)
{
  static std::string id = "#bundle";
  bundle.resize(16);
  std::copy(id.begin(), id.end(), bundle.begin());
  bundle[15] = 1;
}

void AssetManagerClient::AppendBundle(std::vector<char>& bundle,
    const std::vector<char>& message)
{
  if (bundle.size() + message.size() > MAX_MESSAGE_SIZE) {
    udp_client_->Send(bundle);
    NewBundle(bundle);
  }
  if (message.size()) {
    int32_t a = htonl(message.size());
    bundle.insert(bundle.end(), (char*)&a, (char*)&a+4);
    bundle.insert(bundle.end(), message.begin(), message.end());
  }
}

void AssetManagerClient::BlockUntilQueuesAreEmpty()
{
  tcp_client_->BlockUntilQueueIsEmpty();
  udp_client_->BlockUntilQueueIsEmpty();
}


text:
balance = float(raw_input("enter balance: "))
annualInterestRate = float(raw_input("enter annual interest rate: "))
monthlyPaymentRate = float(raw_input("enter monthly payment rate: "))

z = 0
for n in range(12):
	minpay = balance*monthlyPaymentRate
	ub = balance - minpay
	mir = annualInterestRate/12.0
	i = ub*mir
	fb = ub + i
	z = z + minpay
	print '\n'
	print "Month: ", n+1
	print "Minimum monthly payment:", round(minpay,2)
	print "Remaining balance: ", round(fb,2)
	balance = fb
	if (n+1) == 12:
		print '\n'
		print "total Paid", round(z,2)
		print "remaining balance", round(fb,2)


text:
package com.mapswithme.maps.purchase;

import android.support.annotation.NonNull;

import com.mapswithme.maps.R;
import com.mapswithme.maps.dialog.AlertDialog;
import com.mapswithme.util.UiUtils;

enum BookmarkPaymentState
{
  NONE
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          throw new UnsupportedOperationException("This state can't be used!");
        }
      },
  PRODUCT_DETAILS_LOADING
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          showProgress(fragment);
        }
      },
  PRODUCT_DETAILS_LOADED
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          hideProgress(fragment);
          fragment.updateProductDetails();
        }
      },
  TRANSACTION_STARTING
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          showProgress(fragment);
        }
      },
  TRANSACTION_FAILURE
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          UiUtils.hide(fragment.getViewOrThrow(), R.id.progress);
          AlertDialog alertDialog = new AlertDialog.Builder()
              .setReqCode(PurchaseUtils.REQ_CODE_START_TRANSACTION_FAILURE)
              .setTitleId(R.string.error_server_title)
              .setMessageId(R.string.error_server_message)
              .setPositiveBtnId(R.string.ok)
              .build();
          alertDialog.show(fragment, name());
        }
      },
  TRANSACTION_STARTED
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          hideProgress(fragment);
          fragment.launchBillingFlow();
        }
      },
  PAYMENT_IN_PROGRESS
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          // Do nothing by default.
        }
      },
  PAYMENT_FAILURE
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          PurchaseUtils.showPaymentFailureDialog(fragment, name());
        }
      },
  VALIDATION
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          showProgress(fragment);
          UiUtils.hide(fragment.getViewOrThrow(), R.id.cancel_btn);
        }
      },
  VALIDATION_FINISH
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          hideProgress(fragment);
          fragment.finishValidation();
        }
      },
  PRODUCT_DETAILS_FAILURE
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          PurchaseUtils.showProductDetailsFailureDialog(fragment, name());
        }
      },
  SUBS_PRODUCT_DETAILS_FAILURE
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          UiUtils.hide(fragment.getViewOrThrow(), R.id.buy_subs_container);
          PurchaseUtils.showProductDetailsFailureDialog(fragment, name());
        }
      },
  SUBS_PRODUCT_DETAILS_LOADED
      {
        @Override
        void activate(@NonNull BookmarkPaymentFragment fragment)
        {
          UiUtils.hide(fragment.getViewOrThrow(), R.id.subs_progress);
          fragment.updateSubsProductDetails();
        }
      };;

  private static void showProgress(@NonNull BookmarkPaymentFragment fragment)
  {
    UiUtils.show(fragment.getViewOrThrow(), R.id.inapp_progress);
    UiUtils.hide(fragment.getViewOrThrow(), R.id.buy_inapp_btn);
  }

  private static void hideProgress(@NonNull BookmarkPaymentFragment fragment)
  {
    UiUtils.hide(fragment.getViewOrThrow(), R.id.inapp_progress);
    UiUtils.show(fragment.getViewOrThrow(), R.id.buy_inapp_btn);
  }

  abstract void activate(@NonNull BookmarkPaymentFragment fragment);
}


text:
using NetMud.Data.Architectural;
using NetMud.DataStructure.Administrative;
using NetMud.DataStructure.Architectural;
using NetMud.DataStructure.Architectural.ActorBase;
using NetMud.DataStructure.Combat;
using NetMud.Utility;
using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Script.Serialization;

namespace NetMud.Data.Combat
{
    [Serializable]
    public class FightingArt : LookupDataPartial, IFightingArt
    {
        /// <summary>
        /// What type of approval is necessary for this content
        /// </summary>
        [JsonIgnore]
        [ScriptIgnore]
        public override ContentApprovalType ApprovalType { get { return ContentApprovalType.Staff; } }

        /// <summary>
        /// How much stam this takes/damages
        /// </summary>
        [Display(Name = "Stamina Cost/Damage", Description = "Stamina Cost / Damage.")]
        [UIHint("ValuePairInt")]
        public ValuePair<int> Stamina { get; set; }

        /// <summary>
        /// How much health this costs/damages the actor/victim
        /// </summary>
        [Display(Name = "Health Cost/Damage", Description = "Health Cost / Damage.")]
        [UIHint("ValuePairInt")]
        public ValuePair<int> Health { get; set; }

        /// <summary>
        /// Results in actor/victim position change
        /// </summary>
        [Display(Name = "Position Result", Description = "esults in actor/victim position change.")]
        [UIHint("ValuePairMobilityState")]
        public ValuePair<MobilityState> PositionResult { get; set; }

        /// <summary>
        /// The min and max distance this is usable
        /// </summary>
        [Display(Name = "Distance Range", Description = "The min and max distance this is usable.")]
        [UIHint("ValueRangeULong")]
        public ValueRange<ulong> DistanceRange { get; set; }

        /// <summary>
        /// How should this alter the combatent distance
        /// </summary>
        [Display(Name = "Distance Change", Description = "How should this alter the combatent distance.")]
        [DataType(DataType.Text)]
        public int DistanceChange { get; set; }

        /// <summary>
        /// How many action frames this takes to execute from init before the hit
        /// </summary>
        [Display(Name = "Setup", Description = "How many action frames this takes to execute from init before the hit.")]
        [DataType(DataType.Text)]
        public int Setup { get; set; }

        /// <summary>
        /// How many action frames this takes to execute after the hit to end
        /// </summary>
        [Display(Name = "Recovery", Description = "How many action frames this takes to execute after the hit to end.")]
        [DataType(DataType.Text)]
        public int Recovery { get; set; }

        /// <summary>
        /// How many frames this adds to the recovery of the Actor when blocked and how much additional stagger it does when blocked
        /// </summary>
        [Display(Name = "Impact", Description = "How many frames this adds to the recovery of the Actor when blocked and how much additional stagger it does to the victim on hit or block.")]
        [DataType(DataType.Text)]
        public int Impact { get; set; }

        /// <summary>
        /// How much stagger-armor does this have while executing (reduces incoming stagger directly, does not reduce stagger costs)
        /// </summary>
        [Display(Name = "Armor", Description = "How much stagger-armor does this have while executing (reduces incoming stagger directly, does not reduce stagger costs)")]
        [DataType(DataType.Text)]
        public int Armor { get; set; }

        /// <summary>
        /// State of readiness this art puts the user in during its duration
        /// </summary>
        [Display(Name = "Readiness", Description = "State of readiness this art puts the user in during its duration.")]
        [UIHint("EnumDropDownList")]
        public ReadinessState Readiness { get; set; }

        /// <summary>
        /// Is this a part of a multipart attack
        /// </summary>
        [Display(Name = "Rekka", Description = "Name of multipart attack.")]
        [DataType(DataType.Text)]
        public string RekkaKey { get; set; }

        /// <summary>
        /// Where in the multipart attack does this go
        /// </summary>
        [Display(Name = "Rekka Position", Description = "Where in the multipart attack does this go.")]
        [DataType(DataType.Text)]
        public int RekkaPosition { get; set; }

        /// <summary>
        /// Where does this move aim
        /// </summary>
        [Display(Name = "Aim", Description = "Where does this move aim.")]
        [UIHint("EnumDropDownList")]
        public AnatomyAim Aim { get; set; }

        /// <summary>
        /// Criteria for usage for actor
        /// </summary>
        [Display(Name = "Actor Criteria", Description = "Criteria for the one executing the Art.")]
        [UIHint("FightingArtCriteria")]
        public IFightingArtCriteria ActorCriteria { get; set; }

        /// <summary>
        /// Criteria for usage for victim
        /// </summary>
        [Display(Name = "Victim Criteria", Description = "Criteria for the one being targeted by the Art.")]
        [UIHint("FightingArtCriteria")]
        public IFightingArtCriteria VictimCriteria { get; set; }

        /// <summary>
        /// The quality we're checking for
        /// </summary>
        [Display(Name = "Quality", Description = "Name of quality this adds to on use.")]
        [DataType(DataType.Text)]
        public string ResultQuality { get; set; }

        /// <summary>
        /// Is this quality additive or replace
        /// </summary>
        [Display(Name = "Additive", Description = "Does this quality add to an existing quality (true) or replace the value(false).")]
        [UIHint("Boolean")]
        public bool AdditiveQuality { get; set; }

        /// <summary>
        /// The value we're adding to the quality
        /// </summary>
        [Display(Name = "Amount", Description = "How much is added for the applied quality.")]
        [DataType(DataType.Text)]
        public int QualityValue { get; set; }

        /// <summary>
        /// The verb of the sentence for output building
        /// </summary>
        [Display(Name = "Verb", Description = "The verb of the sentence for output building (see examples).")]
        [DataType(DataType.Text)]
        public string ActionVerb { get; set; }

        /// <summary>
        /// The subject of the sentence for output building
        /// </summary>
        [Display(Name = "Subject", Description = "The subject of the sentence for output building (see examples).")]
        [DataType(DataType.Text)]
        public string ActionSubject { get; set; }

        /// <summary>
        /// The predicate of the sentence for output building
        /// </summary>
        [Display(Name = "Predicate", Description = "The predicate of the sentence for output building (see examples).")]
        [DataType(DataType.Text)]
        public string ActionPredicate { get; set; }

        public FightingArt()
        {
            QualityValue = 0;
            AdditiveQuality = true;
            Aim = AnatomyAim.Mid;
            PositionResult = new ValuePair<MobilityState>(MobilityState.None, MobilityState.None);
            DistanceRange = new ValueRange<ulong>(0, 1);
            Stamina = new ValuePair<int>(1, 0);
            Health = new ValuePair<int>(0, 1);
            Impact = 1;
            Armor = 0;
            Setup = 1;
            Recovery = 1;
            RekkaPosition = -1;
            ActorCriteria = new FightingArtCriteria();
            VictimCriteria = new FightingArtCriteria();
            Readiness = ReadinessState.Offensive;
        }

        /// <summary>
        /// Is this art valid to be used at the moment
        /// </summary>
        /// <param name="actor">who's doing the hitting</param>
        /// <param name="victim">who's being hit</param>
        /// <returns>yea or nay</returns>
        public bool IsValid(IMobile actor, IMobile victim, ulong distance, IFightingArt lastAttack = null)
        {
            return distance.IsBetweenOrEqual(DistanceRange.Low, DistanceRange.High)
                && actor.CurrentHealth >= Health.Actor
                && actor.CurrentStamina >= Stamina.Actor
                && (lastAttack == null || (lastAttack.RekkaKey.Equals(RekkaKey) && lastAttack.RekkaPosition == RekkaPosition - 1));
        }

        /// <summary>
        /// Calculate the cost ratio of this art
        /// </summary>
        /// <returns></returns>
        public double CalculateCostRatio()
        {
            double cost = ((short)Readiness * 10)
                + (Impact * 5)
                + (Health.Victim * 10)
                + (Stamina.Victim * 5)
                + ((short)PositionResult.Victim * 10)
                + (QualityValue * 2)
                + (Armor * 4)
                - (Setup * 3)
                - (Recovery * 2.5)
                - (RekkaPosition >= 0 ? 10 : 0)
                - (Stamina.Actor * 5)
                - (Health.Actor * 2.5);

            return cost;
        }
    }
}


text:
Codebase for learning how to display geolocations and connections between them in an Openframeworks iOS app.

In its current form the app displays a visualization for the global flight network, showing all major airports, the connections sorted by number of connections. Future development plans include making this app so users can upload custom data and interact with it more than in v0.1.0.

This iOS app is currently for local testing only and has not been submitted to the App Store.

## Setup

* Install Openframeworks iOS
* Copy this repo into your OF apps folder
* If needed install the ofxCsv plugin

## Requirements

* [Openframeworks iOS](http://openframeworks.cc/download/)
* [ofxCsv](https://github.com/paulvollmer/ofxCsv)

## Sample data & credits

* [Global Flight Networks](http://www.visualizing.org/datasets/global-flights-network) by [visualizing.org]
* Nightsky texture [http://commons.wikimedia.org/wiki/File:Vermont_night_sky_stargazing.JPG](wikipedia.org)


text:
using namespace alife::cell;
using namespace geometry;

namespace alife {

////////////////
// Boid
////////////////

double Boid::desiredSeparation = 50.0;
double Boid::neighborDist = 100.0;

Boid::Boid(int id, Vec3d location, Vec3i borderMin, Vec3i borderMax, bool borderWrapping, bool borderRepulsion,
           Vec3d acceleration, Vec3d velocity, double maxSpeed, double maxForce) :
    id(id),
    location(location),
    borderMin(borderMin),
    borderMax(borderMax),
    borderWrapping(borderWrapping),
    borderRepulsion(borderRepulsion),
    acceleration(acceleration),
    velocity(velocity),
    maxSpeed(maxSpeed),
    maxForce(maxForce)
{
    Vec3i center = borderMin + ((borderMax - borderMin) / 2);
    borderCenter = Vec3d(center.x, center.y, center.z);
}

void Boid::run(const std::vector<Boid*>& boids)
{
    flock(boids);
    update();

    if(borderWrapping)
        wrapToBorders();

    if(borderRepulsion)
        borderRepulse();
}

void Boid::applyForce(Vec3d force)
{
    acceleration = acceleration + force;
}

void Boid::update()
{
    velocity = velocity + acceleration;
    velocity.limit(maxSpeed);
    location = location + velocity;
    acceleration = acceleration * 0;
}

geometry::Vec3d Boid::steer(geometry::Vec3d target)
{
    Vec3d desired = target - location;
    double distance = desired.length();

    if(distance > 0)
    {
        desired.normalize();
        desired = desired * maxSpeed;
        Vec3d steer = desired - velocity;
        steer.limit(maxForce);
        return steer;
    }

    else
    {
        return Vec3d(0, 0, 0);
    }
}

void Boid::seek(Vec3d target)
{
    acceleration += steer(target);
}

geometry::Vec3d Boid::separate(const std::vector<Boid*>& boids)
{
    Vec3d steer(0, 0, 0);
    int count = 0;

    for(int i = 0; i < boids.size(); ++i)
    {
        Boid* boid = boids[i];
        double distance = location.distance(boid->getLocation());

        if(distance > 0 && distance < desiredSeparation)
        {
            Vec3d difference = location - boid->getLocation();
            difference.normalize();
            difference = difference / distance;
            steer = steer + difference;
            ++count;
        }
    }

    if(count > 0)
    {
        steer = steer / (double) count; // Average
    }

    if(steer.length() > 0)
    {
        steer.normalize();
        steer = steer * maxSpeed;
        steer = steer - velocity;
        steer.limit(maxForce);
    }

    return steer;
}

void Boid::flock(const std::vector<Boid*>& boids)
{
    Vec3d separationForce = separate(boids) * 1.5; // Emphasize separation over the other two forces
    Vec3d alignForce = align(boids);
    Vec3d cohesionForce = cohesion(boids);

    applyForce(separationForce);
    applyForce(alignForce);
    applyForce(cohesionForce);
}

geometry::Vec3d Boid::align(const std::vector<Boid*>& boids)
{
    Vec3d sum(0, 0, 0);
    int count = 0;

    for(int i = 0; i < boids.size(); ++i)
    {
        Boid* boid = boids[i];
        double distance = location.distance(boid->getLocation());

        if(distance > 0 && distance < neighborDist)
        {
            sum = sum + boid->getVelocity();
            ++count;
        }
    }

    if(count > 0)
    {
        sum = sum / (double) count;
        //sum.normalize();
        //sum = sum * maxSpeed;
        //Vec3d steer = sum - velocity;
        //steer.limit(maxForce);
        return sum;
    }

    else
    {
        return Vec3d(0, 0, 0);
    }
}

geometry::Vec3d Boid::cohesion(const std::vector<Boid*>& boids)
{
    Vec3d sum(0, 0, 0);
    int count = 0;

    for(int i = 0; i < boids.size(); ++i)
    {
        Boid* boid = boids[i];
        double distance = location.distance(boid->getLocation());
        if(distance > 0 && distance < neighborDist)
        {
            sum = sum + boid->getLocation();
            ++count;
        }
    }

    if(count > 0)
    {
        sum = sum / (double) count;
        return steer(sum);
    }

    else
    {
        return Vec3d(0, 0, 0);
    }
}

void Boid::drift()
{
    double radius = 30.0;
    double diameter = 60.0;
    int driftBounds = 0.45;
    driftAngle += randomRange<int>(-driftBounds, driftBounds);

    Vec3d center = velocity;
    center.normalize();
    center *= diameter;
    center += location;

    Vec3d offset(radius * cos(driftAngle), radius * sin(driftAngle));
    Vec3d target = center + offset;
    acceleration += steer(target);
}

void Boid::wrapToBorders()
{
    // Wrap x coordinate
    if(location.x >= borderMax.x)
        location.x = borderMin.x;

    else if(location.x < borderMin.x)
        location.x = borderMax.x -1;

    // Wrap y coordinate
    if(location.y >= borderMax.y)
        location.y = borderMin.y;

    else if(location.y < borderMin.y)
        location.y = borderMax.y -1;

    // Wrap z coordinate
    if(location.z >= borderMax.z)
        location.z = borderMin.z;

    else if(location.z < borderMin.z)
        location.z = borderMax.z -1;
}

void Boid::borderRepulse()
{
    if(location.x < borderMin.x || location.x > borderMax.x
            || location.y < borderMin.y || location.y > borderMax.y
            || location.z < borderMin.z || location.z > borderMax.z)
    {
        seek(borderCenter);
    }
}

bool Boid::getBorderWrapping()
{
    return borderWrapping;
}

void Boid::setBorderWrapping(bool borderWrapping)
{
    this->borderWrapping = borderWrapping;
}

int Boid::getID()
{
    return id;
}

Vec3d Boid::getLocation()
{
    return location;
}

geometry::Vec3d Boid::getVelocity()
{
    return velocity;
}

geometry::Vec3d Boid::getAcceleration()
{
    return acceleration;
}

double Boid::getMaxForce()
{
    return maxForce;
}

double Boid::getMaxSpeed()
{
    return maxSpeed;
}

////////////////
// Flock
////////////////

Flock::Flock(Vec3i borderMin, Vec3i borderMax, bool borderWrapping, bool borderRepulsion):
    borderMin(borderMin),
    borderMax(borderMax),
    borderWrapping(borderWrapping),
    borderRepulsion(borderRepulsion),
    boidIDCounter(0)
{

}

Flock::~Flock()
{
    clear();
}

void Flock::run()
{
    for(int i = 0; i < boids.size(); ++i)
    {
        boids[i]->run(boids);
    }
}

void Flock::seek(Vec3d target)
{
    for(int i = 0; i < boids.size(); ++i)
    {
        boids[i]->seek(target);
    }
}

void Flock::drift()
{
    for(int i = 0; i < boids.size(); ++i)
    {
        boids[i]->drift();
    }
}

int Flock::addBoid(Vec3d location, Vec3d acceleration, Vec3d velocity, double maxSpeed, double maxForce)
{
    boids.push_back(new Boid(boidIDCounter, location, borderMin, borderMax, borderWrapping, borderRepulsion, acceleration, velocity,
                               maxSpeed, maxForce));
    ++boidIDCounter;
    return boidIDCounter;
}

int Flock::addBoid(Boid *boid)
{
    boids.push_back(boid);
    ++boidIDCounter;
    return boidIDCounter;
}

void Flock::removeBoid(int id)
{
    for(int i = 0; i < boids.size(); ++i)
    {
        if(id == boids[i]->getID())
        {
            delete boids[i];
            boids.erase(boids.begin() + i);
        }
    }
}

void Flock::clear()
{
    for(int i = 0; i < boids.size(); ++i)
    {
        delete boids[i];
    }

    boids.clear();
}

const std::vector<Boid*>& Flock::getBoids()
{
    return boids;
}

bool Flock::getBorderWrapping()
{
    return borderWrapping;
}

void Flock::setBorderWrapping(bool borderWrapping)
{
    this->borderWrapping = borderWrapping;

    for(int i = 0; i < boids.size(); ++i)
    {
        boids[i]->setBorderWrapping(borderWrapping);
    }
}

int Flock::getNumberOfBoids()
{
    return boids.size();
}

int Flock::size()
{
    return boids.size();
}

} // alife namespace


text:
package com.tomasbozzo.optionals.service;

import com.tomasbozzo.optionals.model.PaymentMethod;

import java.util.Optional;

public class PaymentMethodService {

    public Optional<String> getName(PaymentMethod paymentMethod) {
        return Optional.ofNullable(paymentMethod)
                .map(PaymentMethod::getName);
    }
}


text:
<?php
namespace envtests\application\mysql;

/**
 * Test common MySql operation
 *
 * @method deleteAllow()
 * @method deleteNotAllow()
 * @method insertAllow()
 * @method insertNotAllow()
 * @method updateAllow()
 * @method updateNotAllow()
 * @method selectAllow()
 * @method selectNotAllow()
 *
 * @see http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
 * @author Roman Ozana <ozana@omdesign.cz>
 */
class Operations extends Core {

	/** @var string */
	public $table = '_envtesting_';

	/** @var string */
	public $coll = 'data';

	/**
	 * Call all private methods
	 *
	 * @param string $name
	 * @param array $args
	 * @return string
	 * @throws \envtesting\Error
	 */
	public function __call($name, $args) {
		$this->getConnection()->beginTransaction();
		try {
			$result = call_user_func_array(array($this, $name), $args);
			$this->getConnection()->rollBack();
			return $result;
		} catch (\envtesting\Warning $e) {
			$this->getConnection()->rollBack();
			throw $e;
		} catch (\envtesting\Error $e) {
			$this->getConnection()->rollBack();
			throw $e;
		}
	}

	// -------------------------------------------------------------------------------------------------------------------
	// DELETE
	// -------------------------------------------------------------------------------------------------------------------

	/**
	 * Check if user can delete data
	 *
	 * @throws \envtesting\Error
	 */
	private function deleteAllow() {
		$this->tryDeleteData($this->table, $this->coll, __FUNCTION__);
		return 'DELETE allow to user ' . $this->user . PHP_EOL . $this;
	}

	/**
	 * Check if user can't delete data
	 *
	 * @throws \envtesting\Error
	 */
	private function deleteNotAllow() {
		try {
			$this->tryDeleteData($this->table, $this->coll, __FUNCTION__);
		} catch (\envtesting\Error $e) {
			if ($this->lastErrorNumber() == 1142) {
				return 'DELETE denied to user ' . $this->user . PHP_EOL . $this;
			}
		}
		throw new \envtesting\Error('DELETE allow to user ' . $this->user . PHP_EOL . $this);
	}

	// -------------------------------------------------------------------------------------------------------------------
	// INSERT
	// -------------------------------------------------------------------------------------------------------------------

	/**
	 * Check if iser can't insert data
	 *
	 * @throws \envtesting\Error
	 */
	private function insertAllow() {
		$this->tryInsertData($this->table, $this->coll, __FUNCTION__);
		return 'INSERT allow to user ' . $this->user . PHP_EOL . $this;
	}

	/**
	 * Check if iser can't insert data
	 *
	 * @throws \envtesting\Error
	 */
	private function insertNotAllow() {
		try {
			$this->tryInsertData($this->table, $this->coll, __FUNCTION__);
		} catch (\envtesting\Error $e) {
			if ($this->lastErrorNumber() == 1142) {
				return 'INSERT denied to user ' . $this->user . PHP_EOL . $this;
			}
		}

		throw new \envtesting\Error('INSERT allow to user ' . $this->user . PHP_EOL . $this);
	}

	// -------------------------------------------------------------------------------------------------------------------
	// UPDATE
	// -------------------------------------------------------------------------------------------------------------------

	/**
	 * Check if iser can't insert data
	 *
	 * @throws \envtesting\Error
	 */
	private function updateAllow() {
		$this->tryInsertData($this->table, $this->coll, __FUNCTION__);
		return 'UPDATE allow to user ' . $this->user . PHP_EOL . $this;
	}

	/**
	 * Check if iser can't insert data
	 *
	 * @throws \envtesting\Error
	 */
	private function updateNotAllow() {
		try {
			$this->tryInsertData($this->table, $this->coll, __FUNCTION__);
		} catch (\envtesting\Error $e) {
			if ($this->lastErrorNumber() == 1142) {
				return 'UPDATE denied to user ' . $this->user . PHP_EOL . $this;
			}
		}

		throw new \envtesting\Error('UPDATE allow to user ' . $this->user . PHP_EOL . $this);
	}

	// -------------------------------------------------------------------------------------------------------------------
	// SELECT
	// -------------------------------------------------------------------------------------------------------------------

	/**
	 * @return string
	 */
	private function selectAllow() {
		$this->trySelectData($this->table, $this->coll, __FUNCTION__);
		return 'SELECT allow to use ' . $this->user . PHP_EOL . $this;
	}

	/**
	 * @return string
	 */
	private function selectNotAllow() {
		try {
			$this->trySelectData($this->table, $this->coll, __FUNCTION__);
		} catch (\envtesting\Error $e) {
			if ($this->lastErrorNumber() == 1142) {
				return 'SELECT denied to user ' . $this->user . PHP_EOL . $this;
			}
		}

		throw new \envtesting\Error('SELECT allow to user ' . $this->user . PHP_EOL . $this);
	}

}


text:
require 'rubygems'
require 'rake'
require 'set'
require 'fileutils'
require 'file_path_utils.rb'

class FileSystemUtils

  constructor :file_wrapper

  # build up path list from input of one or more strings or arrays of (+/-) paths & globs
  def collect_paths(*paths)
    raw   = []  # all paths and globs
    plus  = Set.new # all paths to expand and add
    minus = Set.new # all paths to remove from plus set

    # assemble all globs and simple paths, reforming our glob notation to ruby globs
    paths.each do |paths_container|
      case (paths_container)
        when String then raw << (FilePathUtils::reform_glob(paths_container))
        when Array  then paths_container.each {|path| raw << (FilePathUtils::reform_glob(path))}
        else raise "Don't know how to handle #{paths_container.class}"
      end
    end

    # iterate through each path and glob
    raw.each do |path|

      dirs = []  # container for only (expanded) paths

      # if a glob, expand it and slurp up all non-file paths
      if path.include?('*')
        # grab base directory only if globs are snug up to final path separator
        if (path =~ /\/\*+$/)
          dirs << FilePathUtils.extract_path(path)
        end

        # grab expanded sub-directory globs
        expanded = @file_wrapper.directory_listing( FilePathUtils.extract_path_no_aggregation_operators(path) )
        expanded.each do |entry|
          dirs << entry if @file_wrapper.directory?(entry)
        end

      # else just grab simple path
      # note: we could just run this through glob expansion but such an
      #       approach doesn't handle a path not yet on disk)
      else
        dirs << FilePathUtils.extract_path_no_aggregation_operators(path)
      end

      # add dirs to the appropriate set based on path aggregation modifier if present
      FilePathUtils.add_path?(path) ? plus.merge(dirs) : minus.merge(dirs)
    end

    return (plus - minus).to_a.uniq
  end

  # given a file list, add to it or remove from it
  def revise_file_list(list, revisions)
    revisions.each do |revision|
      # include or exclude file or glob to file list
      file = FilePathUtils.extract_path_no_aggregation_operators( revision )
      FilePathUtils.add_path?(revision) ? list.include(file) : list.exclude(file)
    end
  end

end


text:
'use strict';

var dirBase = '{app,src}/**/Resources/public';

exports.options = {
    imageop: true
}

exports.browserSync = {
    proxy: 'symfony-gulp-builder:8080',
    startPath: '/app_dev.php'
}

exports.inject = {
    styles:  '<link rel="stylesheet" href="{{ asset("[filePath]") }}" />',
    scripts: '<script src="{{ asset("[filePath]") }}"></script>'
}

exports.templates  = ['./{app,src}/**/*.twig'];

exports.assets = {
    styles:  {
        css: [dirBase+'/**/*.css'],
// Add your CSS preprocessors below
        sass:[dirBase+'/**/*.scss'] // ex: sass
    },
    scripts: {
        js: [dirBase+'/**/*.js']
// Add your JS preprocessors below
    },
    img:   [dirBase+'/**/img/**/*.{png,jpg,jpeg,gif,svg}'],
    fonts: [dirBase+'/**/fonts/**/*.{eot,woff,woff2,ttf,otf,svg}'],
    components: ['app/Resources/components'] // if bower is installed
};


text:
// eslint-disable-next-line import/no-extraneous-dependencies
/* eslint-disable no-unused-expressions */
const resizeTo = require('terra-toolkit/lib/nightwatch/responsive-helpers').resizeTo;

module.exports = resizeTo(['tiny', 'small', 'medium', 'large', 'huge', 'enormous'], {
  'Displays a default divider': (browser) => {
    browser
      .url(`${browser.launchUrl}/#/tests/divider-tests/default`)
      .expect.element('#divider').to.be.present;
  },
});


text:
import unittest

from werkzeug import Client
from werkzeug.wrappers.base_response import BaseResponse

from blazeweb.users import User, UserProxy

from blazewebtestapp.applications import make_wsgi

class TestUserFunctional(unittest.TestCase):

    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_attr(self):
        r = self.client.get('/usertests/setfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'foo set')

        r = self.client.get('/usertests/getfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'barbaz')

    def test_auth(self):
        r = self.client.get('/usertests/setauth')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getauth')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'True')

    def test_perm(self):
        r = self.client.get('/usertests/addperm')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getperms')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'TrueFalseTrue')

    def test_clear(self):
        r = self.client.get('/usertests/clear')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'FalseFalseNone')

    def test_message(self):
        r = self.client.get('/usertests/setmsg')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getmsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'test: my message')

        r = self.client.get('/usertests/nomsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'0')

class TestUserUnit(object):
    def _check_empty(self, u):
        assert u.is_authenticated is False
        assert u.is_super_user is False
        assert not u.perms

    def test_defaults(self):
        u = User()
        self._check_empty(u)

    def test_clear(self):
        u = User()
        u.is_authenticated = True
        u.is_super_user = True
        u.add_perm('foobar')
        u.clear()
        self._check_empty(u)

    def test_lazy_dict_attrs(self):
        u = User()
        u.foobar = 1
        assert u['foobar'] == 1

    def test_api_attrs_not_in_dict(self):
        u = User()
        u.foobar = 1

        assert u._is_authenticated is False
        assert '_is_authenticated' not in u

        assert u._is_super_user is False
        assert '_is_super_user' not in u

        assert not u.perms
        assert 'perms' not in u

        assert not u._messages
        assert '_messages' not in u

    def test_perms(self):
        u = User()
        assert not u.has_perm('foobar')
        u.add_perm('foobar')
        assert u.has_perm('foobar')

        assert not u.has_any_perm('baz', 'zip')
        assert not u.has_any_perm(('baz', 'zip'))
        assert u.has_any_perm('baz', 'foobar')
        assert u.has_any_perm('foobar', 'baz')
        assert u.has_any_perm(('baz', 'foobar'))
        assert u.has_any_perm(['foobar', 'baz'])

    def test_super_user_perms(self):
        u = User()
        u.is_super_user = True
        assert u.is_super_user
        assert u.has_perm('foobar')
        u.add_perm('foobar')
        assert u.has_perm('foobar')

        assert u.has_any_perm('baz', 'zip')
        assert u.has_any_perm('foobar', 'baz')

    def test_get_set_properties(self):
        u = User()
        assert not u.is_authenticated
        u.is_authenticated = True
        assert u.is_authenticated

        u = User()
        assert not u.is_super_user
        u.is_super_user = True
        assert u.is_super_user

    def test_repr(self):
        u = User()
        assert repr(u)

class TestUserProxy(object):

    def test_bool_value(self):
        # make sure UserProxy._current_obj() returns a SOP with the real
        # User behind it instead of returning the real User instance.
        u = UserProxy()
        if not u:
            assert False, 'expected user'


text:
module Scratch
  class StackTooSmall < Exception
    def initialize items, expected
      super( "Not enough items on stack:
      Expected: #{expected.inspect} items but stack is #{items.inspect}"
           )
    end
  end

  class UnexpectedEOI < Exception
    def message
      "Unexpected end of input"
    end
  end

  class ConstantReDefine < Exception
    def initialize constant
      @constant = constant
    end

    def message
      "Unable to redefine constant #{@constant}"
    end
  end

  class InvalidType < Exception
    def initialize expected_class, received_class
      super "Expecting a(n) '#{expected_class}' class, but received a(n) '#{received_class}' class instead."
    end
  end
end


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

#nullable disable

using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework;
using Roslyn.Test.Utilities;
using Xunit;

namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS
{
    using static CSharpHelpers;

    [UseExportProvider]
    public class CSharpReferenceTests
    {
        [WpfFact]
        [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
        public void AddRemoveProjectAndMetadataReference_CPS()
        {
            using var environment = new TestEnvironment();
            var project1 = CreateCSharpCPSProject(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
            var project2 = CreateCSharpCPSProject(environment, "project2", commandLineArguments: @"/out:c:\project2.dll");
            var project3 = CreateCSharpCPSProject(environment, "project3", commandLineArguments: @"/out:c:\project3.dll");
            var project4 = CreateCSharpCPSProject(environment, "project4");

            // Add project reference
            project3.AddProjectReference(project1, new MetadataReferenceProperties());

            // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
            project3.AddMetadataReference(@"c:\project2.dll", new MetadataReferenceProperties());

            // Add project reference with no output path
            project3.AddProjectReference(project4, new MetadataReferenceProperties());

            // Add metadata reference
            var metadaRefFilePath = @"c:\someAssembly.dll";
            project3.AddMetadataReference(metadaRefFilePath, new MetadataReferenceProperties(embedInteropTypes: true));

            IEnumerable<ProjectReference> GetProject3ProjectReferences()
            {
                return environment.Workspace
                                  .CurrentSolution.GetProject(project3.Id).ProjectReferences;
            }

            IEnumerable<PortableExecutableReference> GetProject3MetadataReferences()
            {
                return environment.Workspace.CurrentSolution.GetProject(project3.Id)
                                  .MetadataReferences
                                  .Cast<PortableExecutableReference>();
            }

            Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
            Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
            Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));
            Assert.True(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));

            // Change output path for project reference and verify the reference.
            ((IWorkspaceProjectContext)project4).BinOutputPath = @"C:\project4.dll";
            Assert.Equal(@"C:\project4.dll", project4.BinOutputPath);

            Assert.True(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project4.Id));

            // Remove project reference
            project3.RemoveProjectReference(project1);

            // Remove project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
            project3.RemoveMetadataReference(@"c:\project2.dll");

            // Remove metadata reference
            project3.RemoveMetadataReference(metadaRefFilePath);

            Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project1.Id));
            Assert.False(GetProject3ProjectReferences().Any(pr => pr.ProjectId == project2.Id));
            Assert.False(GetProject3MetadataReferences().Any(mr => mr.FilePath == metadaRefFilePath));

            project1.Dispose();
            project2.Dispose();
            project4.Dispose();
            project3.Dispose();
        }

        [WpfFact]
        [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
        public void RemoveProjectConvertsProjectReferencesBack()
        {
            using var environment = new TestEnvironment();
            var project1 = CreateCSharpCPSProject(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
            var project2 = CreateCSharpCPSProject(environment, "project2");

            // Add project reference as metadata reference: since this is known to be the output path of project1, the metadata reference is converted to a project reference
            project2.AddMetadataReference(@"c:\project1.dll", new MetadataReferenceProperties());
            Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);

            // Remove project1. project2's reference should have been converted back
            project1.Dispose();
            Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project2.Id).AllProjectReferences);
            Assert.Single(environment.Workspace.CurrentSolution.GetProject(project2.Id).MetadataReferences);

            project2.Dispose();
        }

        [WpfFact]
        [WorkItem(461967, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/461967")]
        [WorkItem(727173, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/727173")]
        [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
        public void AddingMetadataReferenceToProjectThatCannotCompileInTheIdeKeepsMetadataReference()
        {
            using var environment = new TestEnvironment(typeof(NoCompilationLanguageServiceFactory));
            var project1 = CreateCSharpCPSProject(environment, "project1", commandLineArguments: @"/out:c:\project1.dll");
            var project2 = CreateNonCompilableProject(environment, "project2", @"C:\project2.fsproj");
            project2.BinOutputPath = "c:\\project2.dll";

            project1.AddMetadataReference(project2.BinOutputPath, MetadataReferenceProperties.Assembly);

            // We should not have converted that to a project reference, because we would have no way to produce the compilation
            Assert.Empty(environment.Workspace.CurrentSolution.GetProject(project1.Id).AllProjectReferences);

            project2.Dispose();
            project1.Dispose();
        }

        [WpfFact]
        [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
        public void AddRemoveAnalyzerReference_CPS()
        {
            using var environment = new TestEnvironment();
            using var project = CreateCSharpCPSProject(environment, "project1");
            // Add analyzer reference
            var analyzerAssemblyFullPath = @"c:\someAssembly.dll";

            bool AnalyzersContainsAnalyzer()
            {
                return environment.Workspace.CurrentSolution.Projects.Single()
                                  .AnalyzerReferences.Cast<AnalyzerReference>()
                                  .Any(a => a.FullPath == analyzerAssemblyFullPath);
            }

            project.AddAnalyzerReference(analyzerAssemblyFullPath);
            Assert.True(AnalyzersContainsAnalyzer());

            // Remove analyzer reference
            project.RemoveAnalyzerReference(analyzerAssemblyFullPath);
            Assert.False(AnalyzersContainsAnalyzer());
        }
    }
}


text:
package com.yinfork.infoqapp.volley;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.yinfork.infoqapp.MyApplication;

import java.util.Map;

/**
 * Created by Administrator on 2015/10/22.
 */
public class VolleyClient {

    private static StringRequest mStringRequest;

    public static void RequestGet(String url, String tag, VolleyResponse vf) {
        MyApplication.getmRequestQueue().cancelAll(tag);
        mStringRequest = new StringRequest(Request.Method.GET, url, vf.loadLinstener(), vf.errorListener()) {

        };
        MyApplication.getmRequestQueue().add(mStringRequest);
    }

    public static void PcRequestGet(String url, String tag, VolleyResponse vf) {
        MyApplication.getmRequestQueue().cancelAll(tag);
        mStringRequest = new PcStringRequest(Request.Method.GET, url, vf.loadLinstener(), vf.errorListener()) {

        };

        MyApplication.getmRequestQueue().add(mStringRequest);
    }

    public static void RequestPost(Context context, String url, String tag, final Map<String, String> params, VolleyResponse vf) {
        MyApplication.getmRequestQueue().cancelAll(tag);
        mStringRequest = new StringRequest(Request.Method.POST, url, vf.loadLinstener(), vf.errorListener()) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        MyApplication.getmRequestQueue().add(mStringRequest);

    }
}


text:
<?php

namespace CachetHQ\Cachet\Presenters;

use CachetHQ\Cachet\Presenters\Traits\TimestampsTrait;
use Illuminate\Contracts\Support\Arrayable;
use McCool\LaravelAutoPresenter\BasePresenter;
use McCool\LaravelAutoPresenter\Facades\AutoPresenter;

class ComponentGroupPresenter extends BasePresenter implements Arrayable
{
    use TimestampsTrait;

    /**
     * Returns the lowest component status.
     *
     * @return string|null
     */
    public function lowest_status()
    {
        if ($component = $this->wrappedObject->enabled_components_lowest()->first()) {
            return AutoPresenter::decorate($component)->status;
        }
    }

    /**
     * Returns the lowest component status, readable by humans.
     *
     * @return string|null
     */
    public function lowest_human_status()
    {
        if ($component = $this->wrappedObject->enabled_components_lowest()->first()) {
            return AutoPresenter::decorate($component)->human_status;
        }
    }

    /**
     * Returns the lowest component status color.
     *
     * @return string|null
     */
    public function lowest_status_color()
    {
        if ($component = $this->wrappedObject->enabled_components_lowest()->first()) {
            return AutoPresenter::decorate($component)->status_color;
        }
    }

    /**
     * Determine the class for collapsed/uncollapsed groups.
     *
     * @return string
     */
    public function collapse_class()
    {
        return $this->is_collapsed() ? 'ion-ios-plus-outline' : 'ion-ios-minus-outline';
    }

    /**
     * Determine if the group should be collapsed.
     *
     * @return bool
     */
    public function is_collapsed()
    {
        if ($this->wrappedObject->collapsed === 0) {
            return false;
        } elseif ($this->wrappedObject->collapsed === 1) {
            return true;
        }

        return $this->wrappedObject->components->filter(function ($component) {
            return $component->status > 1;
        })->isEmpty();
    }

    /**
     * Convert the presenter instance to an array.
     *
     * @return string[]
     */
    public function toArray()
    {
        return array_merge($this->wrappedObject->toArray(), [
            'created_at'          => $this->created_at(),
            'updated_at'          => $this->updated_at(),
            'lowest_human_status' => $this->lowest_human_status(),
        ]);
    }

    /**
     * Determine if any of the contained components have active subscriptions.
     *
     * @return bool
     */
    public function has_subscriber($subscriptions)
    {
        $enabled_components = $this->wrappedObject->enabled_components()->orderBy('order')->pluck('id')->toArray();
        $intersected = array_intersect($enabled_components, $subscriptions);

        return count($intersected) != 0;
    }

    /**
     * Determine the class for collapsed/uncollapsed groups on the subscription form.
     *
     * @return string
     */
    public function collapse_class_with_subscriptions($subscriptions)
    {
        return $this->has_subscriber($subscriptions) ? 'ion-ios-minus-outline' : 'ion-ios-plus-outline';
    }
}


text:
Mailgun-PHP
===========

This is the Mailgun PHP SDK. This SDK contains methods for easily interacting
with the Mailgun API.
Below are examples to get you started. For additional examples, please see our
official documentation
at http://documentation.mailgun.com

[![Latest Stable Version](https://poser.pugx.org/mailgun/mailgun-php/v/stable.png)](https://packagist.org/packages/mailgun/mailgun-php)
[![Build Status](https://travis-ci.org/mailgun/mailgun-php.png)](https://travis-ci.org/mailgun/mailgun-php)

Installation
------------
To install the SDK, you will need to be using [Composer](http://getcomposer.org/)
in your project.
If you aren't using Composer yet, it's really simple! Here's how to install
composer and the Mailgun SDK.

```PHP
# Install Composer
curl -sS https://getcomposer.org/installer | php

# Add Mailgun as a dependency
php composer.phar require mailgun/mailgun-php:~1.7.2
```

**For shared hosts without SSH access, check out our [Shared Host Instructions](SharedHostInstall.md).**

**Rather just download the files? [Library Download](https://9f67cbbd1116d8afb399-7760483f5d1e5f28c2d253278a2a5045.ssl.cf2.rackcdn.com/mailgun-php-1.7.2.zip).**

Next, require Composer's autoloader, in your application, to automatically
load the Mailgun SDK in your project:
```PHP
require 'vendor/autoload.php';
use Mailgun\Mailgun;
```

Usage
-----
Here's how to send a message using the SDK:

```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";

# Now, compose and send your message.
$mg->sendMessage($domain, array('from'    => 'bob@example.com',
                                'to'      => 'sally@example.com',
                                'subject' => 'The PHP SDK is awesome!',
                                'text'    => 'It is so simple to send a message.'));
```

Or obtain the last 25 log items:
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";

# Now, issue a GET against the Logs endpoint.
$mg->get("$domain/log", array('limit' => 25,
                              'skip'  => 0));
```

Response
--------

The results, provided by the endpoint, are returned as an object, which you
can traverse like an array.

Example:

```php
$mg = new Mailgun("key-example");
$domain = "example.com";

$result = $mg->get("$domain/log", array('limit' => 25,
                                        'skip'  => 0));

$httpResponseCode = $result->http_response_code;
$httpResponseBody = $result->http_response_body;

# Iterate through the results and echo the message IDs.
$logItems = $result->http_response_body->items;
foreach($logItems as $logItem){
    echo $logItem->message_id . "\n";
}
```

Example Contents:
**$httpResponseCode** will contain an integer. You can find how we use HTTP response
codes in our documentation:
http://documentation.mailgun.com/api-intro.html?highlight=401#errors

**$httpResponseBody** will contain an object of the API response. In the above
example, a var_dump($result) would contain the following:

```
object(stdClass)#26 (2) {
["http_response_body"]=>
  object(stdClass)#26 (2) {
    ["total_count"]=>
    int(12)
    ["items"]=>
    array(1) {
      [0]=>
      object(stdClass)#31 (5) {
        ["hap"]=>
        string(9) "delivered"
        ["created_at"]=>
        string(29) "Tue, 20 Aug 2013 20:24:34 GMT"
        ["message"]=>
        string(66) "Delivered: me@samples.mailgun.org → travis@mailgunhq.com 'Hello'"
        ["type"]=>
        string(4) "info"
        ["message_id"]=>
        string(46) "20130820202406.24739.21973@samples.mailgun.org"
      }
    }
  }
}
```

Debugging
---------

Debugging the PHP SDK can be really helpful when things aren't working quite right.
To debug the SDK, here are some suggestions:

Set the endpoint to Mailgun's Postbin. A Postbin is a web service that allows you to
post data, which is then displayed through a browser. This allows you to quickly determine
what is actually being transmitted to Mailgun's API.

**Step 1 - Create a new Postbin.**
Go to http://bin.mailgun.net. The Postbin will generate a special URL. Save that URL.

**Step 2 - Instantiate the Mailgun client using Postbin.**

*Tip: The bin id will be the URL part after bin.mailgun.net. It will be random generated letters and numbers. For example, the bin id in this URL, http://bin.mailgun.net/aecf68de, is "aecf68de".*

```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun('key-example', 'bin.mailgun.net', 'aecf68de', $ssl = False);
$domain = 'example.com';

# Now, compose and send your message.
$mg->sendMessage($domain, array('from'    => 'bob@example.com',
                                'to'      => 'sally@example.com',
                                'subject' => 'The PHP SDK is awesome!',
                                'text'    => 'It is so simple to send a message.'));
```
Additional Info
---------------

For usage examples on each API endpoint, head over to our official documentation
pages.

This SDK includes a [Message Builder](src/Mailgun/Messages/README.md),
[Batch Message](src/Mailgun/Messages/README.md) and [Opt-In Handler](src/Mailgun/Lists/README.md) component.

Message Builder allows you to quickly create the array of parameters, required
to send a message, by calling a methods for each parameter.
Batch Message is an extension of Message Builder, and allows you to easily send
a batch message job within a few seconds. The complexity of
batch messaging is eliminated!

Support and Feedback
--------------------

Be sure to visit the Mailgun official
[documentation website](http://documentation.mailgun.com/) for additional
information about our API.

If you find a bug, please submit the issue in Github directly.
[Mailgun-PHP Issues](https://github.com/mailgun/Mailgun-PHP/issues)

As always, if you need additional assistance, drop us a note through your Control Panel at
[https://mailgun.com/cp/support](https://mailgun.com/cp/support).


text:
import ky from 'ky'
import { GlobalConfiguration } from 'src/GlobalConfiguration'

export const api = ky.create({
  prefixUrl: GlobalConfiguration.API_URL,
  timeout: 60000,
})

export const externalApi = ky.create({
  timeout: 60000,
})


text:
/**
 * @jest-environment jsdom
 */

/**
 * This is required to trick typescript into thinking this file is a module
 * rather than a script. If this file is a script, it won't get its own scope
 * and EXPECTED_EXPORTS will be in the global scope, where it conflicts with
 * a variable of the same name in `exports-node.ts`.
 */
export {};

const EXPECTED_EXPORTS = [
  "audioContext",
  "spn",
  "bufferSize",
  "sampleRate",
  "melBands",
  "chromaBands",
  "callback",
  "windowingFunction",
  "featureExtractors",
  "EXTRACTION_STARTED",
  "numberOfMFCCCoefficients",
  "_featuresToExtract",
  "windowing",
  "_errors",
  "createMeydaAnalyzer",
  "listAvailableFeatureExtractors",
  "extract",
];

describe("package exports", () => {
  test("meyda web exports at least currently expected fields", () => {
    expect(window["Meyda"]).not.toBeDefined();
    var meyda = require("../dist/web/meyda");

    expect(Object.keys(meyda)).toEqual(EXPECTED_EXPORTS);
    expect(Object.keys(window["Meyda"])).toEqual(EXPECTED_EXPORTS);
    // @ts-ignore
    delete window["Meyda"];
  });

  test("meyda web min exports at least currently expected fields", () => {
    expect(global["Meyda"]).not.toBeDefined();
    var meyda = require("../dist/web/meyda.min");

    expect(Object.keys(meyda)).toEqual(EXPECTED_EXPORTS);
    expect(Object.keys(global["Meyda"])).toEqual(EXPECTED_EXPORTS);
    // @ts-ignore
    delete global["Meyda"];
  });
});

describe("package exports", () => {
  test("meyda node exports at least currently expected fields", () => {
    var meyda = require("../dist/node/main");

    expect(Object.keys(meyda)).toEqual(EXPECTED_EXPORTS);
    expect(Object.keys(global["Meyda"])).toEqual(EXPECTED_EXPORTS);
  });
});


text:
using UnityEngine;

namespace Custom_Scenery
{
    public class Main : IMod
    {
        private GameObject _go;

        public void onEnabled()
        {
            _go = new GameObject();

            _go.AddComponent<SceneryLoader>();

            _go.GetComponent<SceneryLoader>().Path = Path;

            _go.GetComponent<SceneryLoader>().Identifier = Identifier;

            _go.GetComponent<SceneryLoader>().LoadScenery();
        }

        public void onDisabled()
        {
            _go.GetComponent<SceneryLoader>().UnloadScenery();

            Object.Destroy(_go);
        }

        public string Name { get { return "Tropical Buildings"; } }
        public string Description { get { return "Bamboo buildings for tropical themes."; } }
        public string Path { get; set; }
        public string Identifier { get; set; }
    }
}


text:
// Code generated by go-swagger; DO NOT EDIT.

package admin

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
)

// NewGetVersionParams creates a new GetVersionParams object
// with the default values initialized.
func NewGetVersionParams() *GetVersionParams {

	return &GetVersionParams{

		timeout: cr.DefaultTimeout,
	}
}

// NewGetVersionParamsWithTimeout creates a new GetVersionParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewGetVersionParamsWithTimeout(timeout time.Duration) *GetVersionParams {

	return &GetVersionParams{

		timeout: timeout,
	}
}

// NewGetVersionParamsWithContext creates a new GetVersionParams object
// with the default values initialized, and the ability to set a context for a request
func NewGetVersionParamsWithContext(ctx context.Context) *GetVersionParams {

	return &GetVersionParams{

		Context: ctx,
	}
}

// NewGetVersionParamsWithHTTPClient creates a new GetVersionParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewGetVersionParamsWithHTTPClient(client *http.Client) *GetVersionParams {

	return &GetVersionParams{
		HTTPClient: client,
	}
}

/*GetVersionParams contains all the parameters to send to the API endpoint
for the get version operation typically these are written to a http.Request
*/
type GetVersionParams struct {
	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithTimeout adds the timeout to the get version params
func (o *GetVersionParams) WithTimeout(timeout time.Duration) *GetVersionParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the get version params
func (o *GetVersionParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the get version params
func (o *GetVersionParams) WithContext(ctx context.Context) *GetVersionParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the get version params
func (o *GetVersionParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the get version params
func (o *GetVersionParams) WithHTTPClient(client *http.Client) *GetVersionParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the get version params
func (o *GetVersionParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WriteToRequest writes these params to a swagger request
func (o *GetVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <note/>
    <predicate lemma="indent">
        <note/>
        <roleset framnet="" id="indent.01" name="To make an indentation" vncls="">
            <roles>
                <role descr="agent, indenter" f="" n="0"/>
                <note/>
                <role descr="thing indented, dented" f="" n="1"/>
            </roles>
            <note>Roleset based on parallel entries to VN, PB and sense groupings. Framed by Claire. No appropriate VN entry found.</note>
            <example name="paragraph" src="web" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>You will notice that I indented the paragraph, and that it is double-spaced.</text>
                <note/>
                <arg f="" n="0">I</arg>
                <rel f="">indented</rel>
                <arg f="" n="1">the paragraph</arg>
            </example>
            <example name="make a dent" src="web" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>She indented the tender bark of the cottonwood shoots.</text>
                <note/>
                <arg f="" n="0">She</arg>
                <rel f="">indented</rel>
                <arg f="" n="1">the tender bark of the cottonwood shoots</arg>
            </example>
        </roleset>
        <roleset framnet="" id="indent.02" name="Indenture as servent" vncls="">
            <roles>
                <role descr="Causing of indenturing" f="" n="0"/>
                <note/>
                <role descr="entity made servant" f="" n="1"/>
                <role descr="master, entity indentured to" f="" n="2"/>
            </roles>
            <note>Roleset based on parallel entries to VN, PB and sense groupings. Framed by Claire. No appropriate VN entry found.</note>
            <example name="All arguments" src="web" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Disguising himself as a houseboy, he indented himself to a rich household.</text>
                <note/>
                <arg f="prd" n="m">Disguising himself as a houseboy</arg>
                <arg f="" n="0">he</arg>
                <rel f="">indented</rel>
                <arg f="" n="1">himself</arg>
                <arg f="" n="2">to a rich household</arg>
            </example>
        </roleset>
    </predicate>
</frameset>


text:
package com.orientechnologies.lucene.tests;

import com.orientechnologies.lucene.index.OLuceneIndexNotUnique;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/** Created by Enrico Risa on 29/04/15. */
public class OLuceneGetSearcherTest extends OLuceneBaseTest {

  @Before
  public void init() {
    OClass song = db.createVertexClass("Person");
    song.createProperty("isDeleted", OType.BOOLEAN);

    db.command("create index Person.isDeleted on Person (isDeleted) FULLTEXT ENGINE LUCENE");
  }

  @Test
  public void testSearcherInstance() {

    OIndex index = db.getMetadata().getIndexManagerInternal().getIndex(db, "Person.isDeleted");

    Assert.assertEquals(true, index.getInternal() instanceof OLuceneIndexNotUnique);

    OLuceneIndexNotUnique idx = (OLuceneIndexNotUnique) index.getInternal();

    Assert.assertNotNull(idx.searcher());
  }
}


text:
EvaCloudImage - Light-weight url based image transformation php library
================================================================

Master: [![Build Status](https://secure.travis-ci.org/AlloVince/EvaThumber.png?branch=master)](http://travis-ci.org/AlloVince/EvaThumber)

EvaCloudImage is a url based image transformation php library.

EvaCloudImage allow you to easily transform your images to any required dimension. EvaCloudImage support optimizing, resizing or cropping the images by just change few url letters.

Shadow Protection
-----------------

Sometimes we don't want to expose images source url, EvaCloudImage allow you create shadow image to protect source file:

 - Image source file : [http://evacloudimage.avnpc.com/upload/demo.jpg](http://evacloudimage.avnpc.com/upload/demo.jpg)
 - Shadow image : [http://evacloudimage.avnpc.com/thumb/demo.jpg](http://evacloudimage.avnpc.com/thumb/demo.jpg), use this url in your website, visitor will not know source file url.

Shadow protection support multi-level directory structure, if cache enabled, all folders in URL will be created.

Resize Dimensions
-----------------

Here is the [original image](http://evacloudimage.avnpc.com/upload/demo.jpg):

    http://evacloudimage.avnpc.com/upload/demo.jpg

EvaCloudImage could resize the image by simply passing in the width and height parameters in URL.

###Resize by width:

The following URL points to a 300px width dynamically created image, pass the '*w*' parameter by '*w_300*':

    http://evacloudimage.avnpc.com/thumb/demo,w_300.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,w_300.jpg)

###Resize by height:

The following URL points to a 150px height dynamically created image, pass the '*h*' parameter by '*h_150*':

    http://evacloudimage.avnpc.com/thumb/demo,h_150.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,h_150.jpg)

###Resize by percent:

By passing integer values for resizing images by fixed width and height. You can also change the dimension of an image using percents.

For example, resizing the demo image to *40%* of its original size is done by setting the '*width*' parameter to *0.4*:

    http://evacloudimage.avnpc.com/thumb/demo,w_0.4.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,w_0.4.jpg)

Crop
----

Crop use '*c*' as parameter, under crop mode, you could pass an integer value for cropping from the center of the image.

    http://evacloudimage.avnpc.com/thumb/demo,c_100.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_100.jpg)

'*g*' parameter is shorten for *gravity* which assist Crop mode, this paramter defined which part of the image to take, or crop height.

Below example use both crop and gravity will get a 100px*200px image cropping from center of the image

    http://evacloudimage.avnpc.com/thumb/demo,c_200,g_100.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_200,g_100.jpg)

Cropping fixed coordinates of image, by using the 'x' and 'y' parameters. Also the width and height parameters is required.

    http://evacloudimage.avnpc.com/thumb/demo,c_100,g_200,x_80,y_10.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_100,g_200,x_80,y_10.jpg)

EvaCloudImage support both cropping and resizing on same time, below example will crop image to 100*200 and resize to 50px width. Resizing is always after cropping.

    http://evacloudimage.avnpc.com/thumb/demo,c_100,g_200,w_50.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_100,g_200,w_50.jpg)

###Fill Mode

We always use resized images with exact given dimensions to meet web page layouts, EvaCloudImage support set crop to 'fill' by 'c_fill', then set the image width and height will get the part of the image which fills the given dimensions:

    http://evacloudimage.avnpc.com/thumb/demo,c_fill,w_250,h_50.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_fill,w_250,h_50.jpg)

Under fill mode, change gravity to '*top*', '*bottom*', '*left*', '*right*' will change crop quadrants.

    http://evacloudimage.avnpc.com/thumb/demo,c_fill,g_top,w_250,h_60.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,c_fill,g_top,w_250,h_60.jpg)

Rotate
-----------------

The rotate parameter is '*r*' for rotate images, by passing an integer value could rotate image clockwise:

For example, rotate the demo image by 90 degress clockwise by setting the '*r*' parameter to *90*:

    http://evacloudimage.avnpc.com/thumb/demo,h_200,r_90.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,h_200,r_90.jpg)

JPG Quality
-----------------

The quality parameter is '*q*' for changing compression quality, default quality is 100:

    http://evacloudimage.avnpc.com/thumb/demo,h_200,q_10.jpg

![EvaCloudImage Resized Image](http://evacloudimage.avnpc.com/thumb/demo,h_200,q_10.jpg)

Download
------------

Ready to get started? Well then, download the [latest release](https://github.com/AlloVince/EvaCloudImage/zipball/master)!

Installation
------------

###Requirements

1. PHP version must greater than 5.3.0
2. GD 2.0+
3. Mod-rewrite module enabled in webserver.

###Enable Url Re-write

####Apache Setting

Apache setting is already wroten in .htaccess.

Please make sure the [mod_rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) Module is already enabled.

####Nginx

Config as below

    server {
            listen   80;
            server_name  evacloudimage.avnpc.com;
            location / {
                    root  /usr/www/EvaCloudImage/;
                    index index.php index.html index.htm;
                    if (!-e $request_filename){
                       rewrite ^/(.*)$ /index.php?$1& last;
                    }
            }
            location ~ \.php$ {
                    include fastcgi_params;
                    fastcgi_pass   127.0.0.1:9000;
                    fastcgi_index  index.php;
                    fastcgi_param  SCRIPT_FILENAME  /usr/www/EvaCloudImage/$fastcgi_script_name;
            }
    }

###Configuration

Edit config.inc.php to change image paths.

    array(
        'libPath' => __DIR__ . '/lib',  //PHPthumb library path
        'sourceRootPath' => __DIR__ . '/upload',  //original image save path, require path read permission
        'thumbFileRootPath' => __DIR__ . '/thumb', //resized thumbnails save path, require read and write permission
        'thumbUrlRootPath' => __DIR__, //thumbnails url root path, require read and write permission
        'saveImage' => false,  //if true, thumbnails will be created and auto save as same directory structure as original images
    );

Tech
----

EvaCloudImage uses below open source projects to work properly:

 - [PHP Thumb](https://github.com/masterexploder/PHPThumb) : thumbnail generation library;
 - [Cloudinary](http://cloudinary.com/) : API design is almost as same as Cloudinary;

License
-------

EvaCloudImage is a independent components of [EvaEngine](https://github.com/AlloVince/eva-engine), which released under the [New BSD License](http://framework.zend.com/license/new-bsd).

TODO
----

1. Add ImageMagick support.
2. Image size limit mode
3. Better error handler
4. Face detect.
5. Image effect filters
6. Add allow image sizes

Thanks to
---------
Demo image is from [Рыбачка](http://nzakonova.35photo.ru/photo_391467/), great shot!


text:
angular.module('Framework').controller('templateController', ['$scope',
	function ($scope)
	{
		/* jshint validthis: true */
		var vm = this; //bind $scope to vm (viewmodel)
		vm.someBoolean = false;

		vm.someFunction = function(){
			return 5;
		};

	}
]);