text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using BTCPayServer.Payments;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;

namespace BTCPayServer.Models.WalletViewModels
{
    public class PullPaymentsModel : BasePagingViewModel
    {
        public class PullPaymentModel
        {
            public class ProgressModel
            {
                public int CompletedPercent { get; set; }
                public int AwaitingPercent { get; set; }
                public string CompletedFormatted { get; set; }
                public string AwaitingFormatted { get; set; }
                public string LimitFormatted { get; set; }
                public string ResetIn { get; set; }
                public string EndIn { get; set; }
                public decimal Awaiting { get; set; }
                public decimal Completed { get; set; }
                public decimal Limit { get; set; }
            }
            public string Id { get; set; }
            public string Name { get; set; }
            public string ProgressText { get; set; }
            public ProgressModel Progress { get; set; }
            public DateTimeOffset StartDate { get; set; }
            public DateTimeOffset? EndDate { get; set; }
            public bool AutoApproveClaims { get; set; }
            public bool Archived { get; set; } = false;
        }

        public List<PullPaymentModel> PullPayments { get; set; } = new List<PullPaymentModel>();
        public override int CurrentPageCount => PullPayments.Count;
        public string PaymentMethodId { get; set; }
        public IEnumerable<PaymentMethodId> PaymentMethods { get; set; }
        public PullPaymentState ActiveState { get; set; } = PullPaymentState.Active;
    }

    public class NewPullPaymentModel
    {
        [MaxLength(30)]
        public string Name { get; set; }
        public string Description { get; set; }
        [Required]
        public decimal Amount
        {
            get; set;
        }
        [Required]
        [ReadOnly(true)]
        public string Currency { get; set; }
        [MaxLength(500)]
        [Display(Name = "Custom CSS URL")]
        public string CustomCSSLink { get; set; }
        [Display(Name = "Custom CSS Code")]
        public string EmbeddedCSS { get; set; }

        [Display(Name = "Payment Methods")]
        public IEnumerable<string> PaymentMethods { get; set; }
        public IEnumerable<SelectListItem> PaymentMethodItems { get; set; }
        [Display(Name = "Minimum acceptable expiration time for BOLT11 for refunds")]
        [Range(1, 365 * 10)]
        public long BOLT11Expiration { get; set; } = 30;
        [Display(Name = "Automatically approve claims")]
        public bool AutoApproveClaims { get; set; } = false;
    }

    public class UpdatePullPaymentModel
    {

        public string Id { get; set; }

        public UpdatePullPaymentModel()
        {
        }

        public UpdatePullPaymentModel(Data.PullPaymentData data)
        {
            if (data == null)
            {
                return;
            }

            Id = data.Id;
            var blob = data.GetBlob();
            Name = blob.Name;
            Description = blob.Description;
            CustomCSSLink = blob.View.CustomCSSLink;
            EmbeddedCSS = blob.View.EmbeddedCSS;
        }

        [MaxLength(30)]
        public string Name { get; set; }
        public string Description { get; set; }
        [Display(Name = "Custom CSS URL")]
        public string CustomCSSLink { get; set; }
        [Display(Name = "Custom CSS Code")]
        public string EmbeddedCSS { get; set; }
    }
}


text:
require 'helper'

class TestClient < Test::Unit::TestCase

  def test_client_exists
    assert_not_equal nil, Strikeiron.client
  end

  def test_client_actions
    VCR.use_cassette('client actions') do
      actions = Strikeiron.client.wsdl.soap_actions
      supported_actions = %w(get_sales_tax_value get_sales_tax_categories get_remaining_hits)
      supported_actions.each do |action|
        assert_equal true, actions.include?(action.to_sym)
      end
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
require "#{File.dirname(__FILE__)}/test_document"

class Node
  include Mongoid::Document
  include Mongoid::Acts::NestedSet::TestDocument
  acts_as_nested_set :scope => :root_id

  field :name
  field :root_id, :type => Integer
end


text:
package io.primeval.saga.router.exception;

import java.util.Optional;

import org.osgi.util.promise.Promise;

import io.primeval.saga.action.Context;
import io.primeval.saga.action.Result;
import io.primeval.saga.router.Route;

@FunctionalInterface
public interface ExceptionRecovery<T extends Throwable> {
    Promise<Result<?>> recover(T exception, Context context, Optional<Route> boundRoute);

}


text:
namespace DotGame.Graphics
{
    /// <summary>
    /// Verwaltet Befehle an das IGraphicsDevice, wie die Befehle über die Pipeline oder Zeichen-Befehle.
    /// </summary>
    public interface IRenderContext : IGraphicsObject
    {
        IRenderUpdateContext UpdateContext { get; }

        /// <summary>
        /// Leert den Inhalt des aktuell gebundenen RenderTargets. Ist kein RenderTarget gebunden, wird der Backbuffer angesprochen.
        /// </summary>
        /// <param name="color">Die Farbe.</param>
        void Clear(Color color);

        /// <summary>
        /// Leert den Inhalt des aktuell gebundenen RenderTargets. Ist kein RenderTarget gebunden, wird der Backbuffer angesprochen.
        /// </summary>
        /// <param name="clearOptions">Die <see cref="ClearOptions"/>-Flags, die die angesprochenen Channel angeben.</param>
        /// <param name="color">Die Farbe für Farbchannel benutzt wird.</param>
        /// <param name="depth">Der Wert für den Tiefenchannel (standardmäßig 1).</param>
        /// <param name="stencil">Der Wert für den Stencilchannel (standardmäßig 0).</param>
        void Clear(ClearOptions clearOptions, Color color, float depth, byte stencil);

        /// <summary>
        /// Setzt Color-RenderTarget und Depth-RenderTarget auf die Standardwerte.
        /// </summary>
        void SetRenderTargetsBackBuffer();
        void SetRenderTargets(IRenderTarget2D depth, params IRenderTarget2D[] colorTargets);
        void SetRenderTargetsDepth(IRenderTarget2D depth);
        void SetRenderTargetsColor(params IRenderTarget2D[] colorTargets);

        void SetViewport(Viewport viewport);

        void SetScissor(Rectangle rectangle);

        void SetBlendFactor(Color blendFactor);

        void SetStencilReference(byte stencilReference);

        /// <summary>
        /// Setzt die Pipeline auf den neuen Zustand.
        /// </summary>
        /// <param name="state"></param>
        void SetState(IRenderState state);

        /// <summary>
        /// Setzt den VertexBuffer.
        /// </summary>
        /// <param name="vertexBuffer"></param>
        void SetVertexBuffer(IVertexBuffer vertexBuffer);

        /// <summary>
        /// Setzt den IndexBuffer.
        /// </summary>
        /// <param name="indexBuffer"></param>
        void SetIndexBuffer(IIndexBuffer indexBuffer);

        /// <summary>
        /// Setzt den aktuellen ConstantBuffer für alle globale Variablen.
        /// </summary>
        /// <param name="buffer"></param>
        void SetConstantBuffer(IShader shader, IConstantBuffer buffer);

        /// <summary>
        /// Setzt den aktuellen ConstantBuffer für die Variable name.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="buffer"></param>
        void SetConstantBuffer(IShader shader, string name, IConstantBuffer buffer);

        /// <summary>
        /// Setzt die Texture für einen Shader auf NULL.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        void SetTextureNull(IShader shader, string name);

        /// <summary>
        /// Setzt die Texture für einen Shader.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <param name="texture"></param>
        void SetTexture(IShader shader, string name, ITexture2D texture);
        /// <summary>
        /// Setzt die Texture für einen Shader.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <param name="texture"></param>
        void SetTexture(IShader shader, string name, ITexture2DArray texture);
        /// <summary>
        /// Setzt die Texture für einen Shader.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <param name="texture"></param>
        void SetTexture(IShader shader, string name, ITexture3D texture);
        /// <summary>
        /// Setzt die Texture für einen Shader.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <param name="texture"></param>
        void SetTexture(IShader shader, string name, ITexture3DArray texture);

        /// <summary>
        /// Setzt den Sampler für einen Shader.
        /// </summary>
        /// <param name="shader"></param>
        /// <param name="name"></param>
        /// <param name="sampler"></param>
        void SetSampler(IShader shader, string name, ISampler sampler);

        /// <summary>
        /// Zeichnet nicht indexierte Vertices mit dem gesetzten PrimitiveType und der Anzahl der Vertices im gesetzten VertexBuffer.
        /// </summary>
        void Draw();

        /// <summary>
        /// Zeichnet nicht indexierte Vertices mit dem gesetzten PrimitiveType und den übergebenen Parametern.
        /// </summary>
        void Draw(int vertexCount, int startVertexLocation);

        /// <summary>
        /// Zeichnet indexierte Vertices mit dem gesetzten PrimitiveType und der Anzahl aller Indices im gesetzten IndexBuffer.
        /// </summary>
        void DrawIndexed();

        /// <summary>
        /// Zeichnet indexierte Vertices mit dem gesetzten PrimitiveType und den übergebenen Parametern.
        /// </summary>
        void DrawIndexed(int indexCount, int startIndexLocation, int baseVertexLocation);
    }
}


text:
class NcgAssets extends Polymer.MutableData(Polymer.Element) {
	static get is() {
		return 'ncg-assets';
	}
}

customElements.define('ncg-assets', NcgAssets);


text:
require "fast_spec_helper"
require "octokit"
require "app/models/commit"

describe Commit do
  describe "#file_content" do
    context "when content is returned from GitHub" do
      it "returns content" do
        file_contents = double(content: Base64.encode64("some content"))
        github = double(:github_api, file_contents: file_contents)
        commit = Commit.new("test/test", "abc", github)

        expect(commit.file_content("test.rb")).to eq "some content"
      end
    end

    context "when nothing is returned from GitHub" do
      it "returns nil" do
        github = double(:github_api, file_contents: nil)
        commit = Commit.new("test/test", "abc", github)

        expect(commit.file_content("test.rb")).to eq nil
      end
    end

    context "when content is nil" do
      it "returns nil" do
        contents = double(:contents, content: nil)
        github = double(:github_api, file_contents: contents)
        commit = Commit.new("test/test", "abc", github)

        expect(commit.file_content("test.rb")).to eq nil
      end
    end
  end
end


text:
<?php

namespace Joselfonseca\LaravelTactician\Tests\Stubs;

class TestCommandInput
{
    public $property;

    public function __construct($property)
    {
        $this->property = $property;
    }
}


text:
<?php

namespace tests\src\moduleapp\module\controllers;

class TestController extends \luya\base\Controller
{
    public function actionIndex()
    {
        return 'foo';
    }

    public function actionBar()
    {
        return 'bar';
    }
}


text:
from unittest.mock import patch

from kubernetes import client

from kfserving import V1alpha2EndpointSpec
from kfserving import V1alpha2PredictorSpec
from kfserving import V1alpha2TensorflowSpec
from kfserving import V1alpha2InferenceServiceSpec
from kfserving import V1alpha2InferenceService
from kfserving import KFServingClient

KFServing = KFServingClient()

mocked_unit_result = \
    '''
{
    "api_version": "serving.kubeflow.org/v1alpha2",
    "kind": "InferenceService",
    "metadata": {
        "name": "flower-sample",
        "namespace": "kubeflow"
    },
    "spec": {
        "default": {
            "predictor": {
                "tensorflow": {
                    "storage_uri": "gs://kfserving-samples/models/tensorflow/flowers"
                }
            }
        }
    }
}
 '''

def generate_inferenceservice():
    tf_spec = V1alpha2TensorflowSpec(
        storage_uri='gs://kfserving-samples/models/tensorflow/flowers')
    default_endpoint_spec = V1alpha2EndpointSpec(predictor=V1alpha2PredictorSpec(
        tensorflow=tf_spec))

    isvc = V1alpha2InferenceService(
        api_version='serving.kubeflow.org/v1alpha2',
        kind='InferenceService',
        metadata=client.V1ObjectMeta(name='flower-sample'),
        spec=V1alpha2InferenceServiceSpec(default=default_endpoint_spec))
    return isvc

def test_inferenceservice_client_creat():
    '''Unit test for kfserving create api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.create',
               return_value=mocked_unit_result):
        isvc = generate_inferenceservice()
        assert mocked_unit_result == KFServing.create(
            isvc, namespace='kubeflow')

def test_inferenceservice_client_get():
    '''Unit test for kfserving get api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.get',
               return_value=mocked_unit_result):
        assert mocked_unit_result == KFServing.get(
            'flower-sample', namespace='kubeflow')

def test_inferenceservice_client_watch():
    '''Unit test for kfserving get api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.get',
               return_value=mocked_unit_result):
        assert mocked_unit_result == KFServing.get('flower-sample', namespace='kubeflow',
                                                   watch=True, timeout_seconds=120)

def test_inferenceservice_client_patch():
    '''Unit test for kfserving patch api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.patch',
               return_value=mocked_unit_result):
        isvc = generate_inferenceservice()
        assert mocked_unit_result == KFServing.patch(
            'flower-sample', isvc, namespace='kubeflow')

def test_inferenceservice_client_rollout_canary():
    '''Unit test for kfserving promote api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.rollout_canary',
               return_value=mocked_unit_result):
        assert mocked_unit_result == KFServing.rollout_canary(
            'flower-sample', namespace='kubeflow')

def test_inferenceservice_client_replace():
    '''Unit test for kfserving replace api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.replace',
               return_value=mocked_unit_result):
        isvc = generate_inferenceservice()
        assert mocked_unit_result == KFServing.replace(
            'flower-sample', isvc, namespace='kubeflow')

def test_inferenceservice_client_delete():
    '''Unit test for kfserving delete api'''
    with patch('kfserving.api.kf_serving_client.KFServingClient.delete',
               return_value=mocked_unit_result):
        assert mocked_unit_result == KFServing.delete(
            'flower-sample', namespace='kubeflow')


text:
package go_kafka_client

import (
	"fmt"
	"github.com/elodina/siesta"
	"github.com/elodina/siesta-producer"
	"testing"
	"time"
)

var schemaRepositoryUrl = "http://localhost:8081"

func TestLogEmitter(t *testing.T) {
	partitions := 1
	topic := fmt.Sprintf("testLogEmitter-%d", time.Now().Unix())

	CreateMultiplePartitionsTopic(localZk, topic, partitions)
	EnsureHasLeader(localZk, topic)

	loggerConfig := NewKafkaLogEmitterConfig()
	loggerConfig.SchemaRegistryUrl = schemaRepositoryUrl
	loggerConfig.Topic = topic
	loggerConfig.Source = "go_kafka_client.log.emitter"
	loggerConfig.Tags = map[string]string{"origin": topic}
	loggerConfig.ProducerConfig = producer.NewProducerConfig()
	loggerConfig.ConnectorConfig = siesta.NewConnectorConfig()
	loggerConfig.ConnectorConfig.BrokerList = []string{localBroker}

	logger, err := NewKafkaLogEmitter(loggerConfig)
	assert(t, err, nil)
	logger.Info("Message sent at %d", time.Now().Unix())

	consumeMessages := 1
	consumeStatus := make(chan int)
	delayTimeout := 10 * time.Second

	config := testConsumerConfig()
	config.Strategy = newCountingStrategy(t, consumeMessages, consumeTimeout, consumeStatus)
	consumer := NewConsumer(config)
	go consumer.StartStatic(map[string]int{topic: 1})

	if actual := <-consumeStatus; actual != consumeMessages {
		t.Errorf("Failed to consume %d messages within %s. Actual messages = %d", consumeMessages, consumeTimeout, actual)
	}

	closeWithin(t, delayTimeout, consumer)
}

func TestMetricsEmitter(t *testing.T) {
	partitions := 1
	topic := fmt.Sprintf("testMetricsEmitter-%d", time.Now().Unix())

	CreateMultiplePartitionsTopic(localZk, topic, partitions)
	EnsureHasLeader(localZk, topic)

	consumeMessages := 1
	consumeStatus := make(chan int)
	delayTimeout := 10 * time.Second

	metricsProducerConfig := producer.NewProducerConfig()
	connectorConfig := siesta.NewConnectorConfig()
	connectorConfig.BrokerList = []string{localBroker}
	reporter, err := NewCodahaleKafkaReporter(topic, schemaRepositoryUrl, metricsProducerConfig, connectorConfig)
	assert(t, err, nil)

	config := testConsumerConfig()
	config.Strategy = newCountingStrategy(t, consumeMessages, consumeTimeout, consumeStatus)
	consumer := NewConsumer(config)
	go consumer.Metrics().WriteJSON(10*time.Second, reporter)
	go consumer.StartStatic(map[string]int{topic: 1})

	if actual := <-consumeStatus; actual != consumeMessages {
		t.Errorf("Failed to consume %d messages within %s. Actual messages = %d", consumeMessages, consumeTimeout, actual)
	}

	closeWithin(t, delayTimeout, consumer)
}


text:
package org.hisp.dhis.commons.action;

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

import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.Action;

/**
 * @author Lars Helge Overland
 */
public class GetCategoryOptionsAction
    implements Action
{
    @Autowired
    private DataElementCategoryService categoryService;

    // -------------------------------------------------------------------------
    // Output
    // -------------------------------------------------------------------------

    private List<DataElementCategoryOption> categoryOptions;

    public List<DataElementCategoryOption> getCategoryOptions()
    {
        return categoryOptions;
    }

    // -------------------------------------------------------------------------
    // Action
    // -------------------------------------------------------------------------

    @Override
    public String execute()
    {
        categoryOptions = new ArrayList<>( categoryService.getAllDataElementCategoryOptions() );

        Collections.sort( categoryOptions, IdentifiableObjectNameComparator.INSTANCE );

        return SUCCESS;
    }
}


text:
----------------

A data-driven `UICollectionView` framework for building fast and flexible lists.

|         | Main Features  |
----------|-----------------
🙅 | Never call `performBatchUpdates(_:, completion:)` or `reloadData()` again
🏠 | Better architecture with reusable cells and components
🔠 | Create collections with multiple data types
🔑 | Decoupled diffing algorithm
✅   | Fully unit tested
🔍 | Customize your diffing behavior for your models
📱 | Simply `UICollectionView` at its core
🚀 | Extendable API
🐦 | Written in Objective-C with full Swift interop support

`IGListKit` is built and maintained with ❤ by [Instagram engineering](https://engineering.instagram.com/).
We use the open source version `master` branch in the Instagram app.

## Requirements

- Xcode 9.0+
- iOS 9.0+
- tvOS 9.0+
- macOS 10.11+ *(diffing algorithm components only)*
- Interoperability with Swift 3.0+

## Installation

### CocoaPods

The preferred installation method is with [CocoaPods](https://cocoapods.org). Add the following to your `Podfile`:

```ruby
pod 'IGListKit', '~> 4.0.0'
```

### Carthage

For [Carthage](https://github.com/Carthage/Carthage), add the following to your `Cartfile`:

```ogdl
github "Instagram/IGListKit" ~> 4.0.0
```

> For advanced usage, see our [Installation Guide](https://instagram.github.io/IGListKit/installation.html).

## Getting Started

```bash
$ git clone https://github.com/Instagram/IGListKit.git
$ cd IGListKit/
$ ./scripts/setup.sh
```

- Our [Getting Started guide](https://instagram.github.io/IGListKit/getting-started.html)
- Ray Wenderlich's [IGListKit Tutorial: Better UICollectionViews](https://www.raywenderlich.com/147162/iglistkit-tutorial-better-uicollectionviews)
- Our [example projects](https://github.com/Instagram/IGListKit/tree/master/Examples)
- Ryan Nystrom's [talk at try! Swift NYC](https://realm.io/news/tryswift-ryan-nystrom-refactoring-at-scale-lessons-learned-rewriting-instagram-feed/) (Note: this talk was for an earlier version. Some APIs have changed.)
- [Migrating an UITableView to IGListCollectionView](https://medium.com/cocoaacademymag/iglistkit-migrating-an-uitableview-to-iglistkitcollectionview-65a30cf9bac9), by Rodrigo Cavalcante
- [Keeping data fresh in Buffer for iOS with AsyncDisplayKit, IGListKit & Pusher](https://overflow.buffer.com/2017/04/10/keeping-data-fresh-buffer-ios-asyncdisplaykit-iglistkit-pusher/), Andy Yates, Buffer

## Documentation

You can find [the docs here](https://instagram.github.io/IGListKit). Documentation is generated with [jazzy](https://github.com/realm/jazzy) and hosted on [GitHub-Pages](https://pages.github.com).

To regenerate docs, run `./scripts/build_docs.sh` from the root directory in the repo.

## Vision

For the long-term goals and "vision" of `IGListKit`, please read our [Vision](https://github.com/Instagram/IGListKit/blob/master/Guides/VISION.md) doc.

## Contributing

Please see the [CONTRIBUTING](https://github.com/Instagram/IGListKit/blob/master/.github/CONTRIBUTING.md) file for how to help. At Instagram, we sync the open source version of `IGListKit` daily, so we're always testing the latest changes. But that requires all changes be thoroughly tested and follow our style guide.

We have a set of [starter tasks](https://github.com/Instagram/IGListKit/issues?q=is%3Aissue+is%3Aopen+label%3Astarter-task) that are great for beginners to jump in on and start contributing.

## License

`IGListKit` is [MIT-licensed](./LICENSE).

The files in the `/Examples/` directory are licensed under a separate license as specified in each file. Documentation is licensed [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/).


text:
import PropTypes from 'prop-types';

const Post = PropTypes.shape({
  contents: PropTypes.string.isRequired,
  datePublished: PropTypes.string.isRequired,
  id: PropTypes.number.isRequired,
  tagIds: PropTypes.arrayOf(PropTypes.number.isRequired),
  title: PropTypes.string.isRequired,
  userId: PropTypes.number.isRequired,
  urlTitle: PropTypes.string.isRequired,
});

const Posts = PropTypes.arrayOf(Post);

const Archive = PropTypes.objectOf(
  PropTypes.objectOf(
    PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        title: PropTypes.string.isRequired,
        urlTitle: PropTypes.string.isRequired,
      }).isRequired
    ).isRequired
  ).isRequired
);

const Similar = PropTypes.shape({
  'Extra Reading': Posts,
  'Similar Blog Posts': Posts,
});

export { Archive, Post, Posts, Similar };


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
 ! @(#)G_Profile_n_Recovery.xml 1.1 05/06/13
 !
 -->
<template type="basic" name="G_Profile_n_Recovery" author="chempack" investigator=""
         label="G_Profile_n_Recovery"
        time_created="20130506T164003" tabname="Installation" apptype="Installation"
        application="liquids" scans="G_Profile_n_Recovery" seqfil="G_Profile_n_Recovery">
  <protocol title="G_Profile_n_Recovery" type="protocol">
    <action  type="LIB" status="Ready" lock="off" title="G_Profile_n_Recovery" exp="G_Profile_n_Recovery"
         dodialog="no"
        time="0:34" macro="G_Profile_n_Recovery" data="" />
  </protocol>
</template>


text:
CS440-Digit-Classification
==========================
Naïve Bayes Classifier is a widely used classification scheme, which is based on Bayes' Theorem.
In this part, we were given a data set of 5000 training examples and 1000 test examples of handwriting images and the corresponding labels (digit 0-9).

Data-preprocessing
=========================
Convert each 'pixel' like image into a vector of features. In the training sample file, there are 5000 pixel images of handwriting digit of size 20*28. We convert each 'pixel\' of '#' or '+' to numerical value 1 and space ' ' to numerical value 0 and thus build a vector of dimension 560 (=20*28) with binary values for each example. Each element in the vector is termed as 'feature' of data sample. A sample converted sample is as follows:

Training a Naive Bayesian Classifier
=========================
From the 5000 training samples, we applied Naive Bayesian Classification method as described above. Specifically, we calculate the prior and likelihood probability for each class and features. The prior is a vector that each element corresponds to the percentage of samples of a specific class in the whole training samples. The likelihood is stored in a probability table that for each class (row) Ci and feature (column) Xk represents the likelihood P(Xk|Ci), which is obtained by the total number of  Xk == 1 in sample of class Ci divided by the total number of sample of Ci.
After Calculate the likelihood probability table, Laplacian correction scheme is applied to as a smoothing method to avoid zero probability.

Testing
=========================
With the 100 test examples, total number of correctly classified examples: 766 , with correct ratio: 0.766

Team & Copyright
=============
COPYRIGHT CS440 Group @ University of Illinois at Urbana-Champaign
By Haoran Yu, Le Wang and Tao Feng


text:
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const paths = require('../scripts/paths');

const IS_DEV = process.env.NODE_ENV !== 'production';

const SERVER_PORT = process.env.PORT || 3000;
const CONTENT_PORT = IS_DEV ? SERVER_PORT + 1 : SERVER_PORT;

const MATCH_JS = /\.js$/i;
const MATCH_CSS_LESS = /\.(css|less)$/i;
const MATCH_FONTS = /\.(eot|ttf|woff|woff2|svg)(\?.+)?$/;

const POSTCSS_LOADER = {
  loader: 'postcss-loader',
  options: {
    ident: 'postcss',
    plugins: () => [
      autoprefixer({
        browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9'],
      }),
    ],
  },
};

const DEFINE_PLUGIN = new webpack.DefinePlugin({
  'process.env.NODE_ENV': IS_DEV ? JSON.stringify('development') : JSON.stringify('production'),
  'process.env.STEEMCONNECT_CLIENT_ID': JSON.stringify(
    process.env.STEEMCONNECT_CLIENT_ID || 'busy.app',
  ),
  'process.env.STEEMCONNECT_REDIRECT_URL': JSON.stringify(
    process.env.STEEMCONNECT_REDIRECT_URL || 'http://localhost:3000/callback',
  ),
  'process.env.STEEMCONNECT_HOST': JSON.stringify(
    process.env.STEEMCONNECT_HOST || 'https://steemconnect.com',
  ),
  'process.env.STEEMJS_URL': JSON.stringify(process.env.STEEMJS_URL || 'https://api.steemit.com'),
  'process.env.SIGNUP_URL': JSON.stringify(
    process.env.SIGNUP_URL || 'https://signup.steemit.com/?ref=busy',
  ),
  'process.env.MANIFEST_PATH': JSON.stringify(paths.assets),
});

module.exports = {
  SERVER_PORT,
  CONTENT_PORT,
  MATCH_JS,
  MATCH_CSS_LESS,
  MATCH_FONTS,
  POSTCSS_LOADER,
  DEFINE_PLUGIN,
};


text:
// Copyright 2009 Indeed
package com.indeed.util.varexport;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;

import java.util.Map;
import java.util.Set;

/**
 * To be used instead of {@link Export} or the introspection methods of {@link VarExporter} to
 * export a manually updated variable.
 *
 *
Example usage:
 *
 *

 *   ManagedVariable<Integer> var = ManagedVariable.<Integer>builder().setName("myvar").setValue(524).build();
 *   // ...
 *   var.set(52473);
 *

 *
 * @author jack@indeed.com (Jack Humphrey)
 */
public class ManagedVariable<T> extends Variable<T> {

    public static <T> Builder<T> builder() {
        return new Builder<T>("");
    }

    public static <T> Builder<T> builder(String namespace) {
        return new Builder<T>(namespace);
    }

    public static class Builder<T> {
        private final String namespace;
        private String name = null;
        private String doc = "";
        private boolean expand = false;
        private Set<String> tags = ImmutableSet.of();
        private T value = null;

        private Builder(String namespace) {
            this.namespace = namespace;
        }

        public Builder<T> setName(String name) {
            this.name = name;
            return this;
        }

        public Builder<T> setDoc(String doc) {
            this.doc = doc;
            return this;
        }

        public Builder<T> setExpand(boolean expand) {
            this.expand = expand;
            return this;
        }

        public Builder<T> setValue(T value) {
            this.value = value;
            return this;
        }

        public Builder<T> setTags(Set<String> tags) {
            this.tags = tags;
            return this;
        }

        public ManagedVariable<T> build() {
            if (name == null) {
                throw new RuntimeException("name must not be null for ManagedVariable");
            }
            if (tags == null) {
                throw new RuntimeException("tags must not be null for ManagedVariable");
            }
            return new ManagedVariable<T>(name, tags, doc, expand, value, namespace);
        }
    }

    @VisibleForTesting
    protected Supplier<Long> clock =
            new Supplier<Long>() {
                public Long get() {
                    return System.currentTimeMillis();
                }
            };

    private T value;
    private Long lastUpdated = clock.get();

    private ManagedVariable(
            String name, Set<String> tags, String doc, boolean expand, T value, String namespace) {
        super(name, tags, doc, expand, namespace);
        this.value = value;
    }

    public void set(T value) {
        this.value = value;
        lastUpdated = clock.get();
    }

    @Override
    protected boolean isLive() {
        return true;
    }

    protected boolean canExpand() {
        return value != null && Map.class.isAssignableFrom(value.getClass());
    }

    @Override
    public Long getLastUpdated() {
        return lastUpdated;
    }

    public T getValue() {
        return value;
    }
}


text:
<?php

namespace Bpaulin\UpfitBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ExerciseSettings
 */
class ExerciseSettings
{
    /**
     * id
     *
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * position
     *
     * @ORM\Column(type="smallint")
     */
    protected $position;

    /**
     * sets
     *
     * @ORM\Column(type="smallint")
     * @Assert\Range(min = "0", max = "999")
     */
    protected $sets;

    /**
     * number
     *
     * @ORM\Column(type="smallint")
     * @Assert\Range(min = "0", max = "999")
     */
    protected $number;

    /**
     * unit
     *
     * @ORM\Column(type="string", type="string", length=20 )
     */
    protected $unit;

    /**
     * difficulty
     *
     * @ORM\Column(type="smallint", nullable=true)
     * @Assert\Range(min = "0", max = "999")
     */
    protected $difficulty;

    /**
     * difficulty Unit
     *
     * @ORM\Column(type="string", nullable=true, length=20 )
     */
    protected $difficultyUnit;

    /**
     * Resting Time
     *
     * @ORM\Column(type="integer", nullable=true)
     */
    protected $rest;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set rest
     *
     * @param  integer $rest
     * @return Stage
     */
    public function setRest($rest)
    {
        $this->rest = $rest;

        return $this;
    }

    /**
     * Get rest
     *
     * @return integer
     */
    public function getRest()
    {
        return $this->rest;
    }

    /**
     * Set position
     *
     * @param  integer          $position
     * @return ExerciseSettings
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set exercise
     *
     * @param  \Bpaulin\UpfitBundle\Entity\Exercise $exercise
     * @return ExerciseSettings
     */
    public function setExercise(\Bpaulin\UpfitBundle\Entity\Exercise $exercise = null)
    {
        $this->exercise = $exercise;

        return $this;
    }

    /**
     * Get exercise
     *
     * @return \Bpaulin\UpfitBundle\Entity\Exercise
     */
    public function getExercise()
    {
        return $this->exercise;
    }

    /**
     * Set sets
     *
     * @param  integer          $sets
     * @return ExerciseSettings
     */
    public function setSets($sets)
    {
        $this->sets = $sets;

        return $this;
    }

    /**
     * Get sets
     *
     * @return integer
     */
    public function getSets()
    {
        return $this->sets;
    }

    /**
     * Set number
     *
     * @param  integer          $number
     * @return ExerciseSettings
     */
    public function setNumber($number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return integer
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Set unit
     *
     * @param  integer          $unit
     * @return ExerciseSettings
     */
    public function setUnit($unit)
    {
        $this->unit = $unit;

        return $this;
    }

    /**
     * Get unit
     *
     * @return integer
     */
    public function getUnit()
    {
        return $this->unit;
    }

    /**
     * Set difficulty
     *
     * @param  string           $difficulty
     * @return ExerciseSettings
     */
    public function setDifficulty($difficulty)
    {
        $this->difficulty = $difficulty;

        return $this;
    }

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

    /**
     * Set difficultyUnit
     *
     * @param  string           $difficultyUnit
     * @return ExerciseSettings
     */
    public function setDifficultyUnit($difficultyUnit)
    {
        $this->difficultyUnit = $difficultyUnit;

        return $this;
    }

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


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.github.wenzhu.maven.user</groupId>
		<artifactId>user-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<!-- 继承的绝对路径是pom的文件 -->
		<relativePath>../user-parent/pom.xml</relativePath>
	</parent>
	<artifactId>user-service</artifactId>
	<packaging>jar</packaging>

	<name>user-service</name>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jasig</groupId>
			<artifactId>AjaxPortletSupport</artifactId>
			<version>1.0.7</version>
		</dependency>
		<dependency>
			<groupId>org.easymock</groupId>
			<artifactId>easymock</artifactId>
		</dependency>

		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>user-core</artifactId>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>user-log</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-rar-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>


text:
package org.hisp.dhis.webapi.controller;

import com.google.common.collect.Lists;
import org.hisp.dhis.deletedobject.DeletedObject;
import org.hisp.dhis.deletedobject.DeletedObjectQuery;
import org.hisp.dhis.deletedobject.DeletedObjectService;
import org.hisp.dhis.fieldfilter.FieldFilterService;
import org.hisp.dhis.node.NodeUtils;
import org.hisp.dhis.node.Preset;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.webapi.service.ContextService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@RestController
@RequestMapping( value = "/deletedObjects" )
public class DeletedObjectController
{
    private final FieldFilterService fieldFilterService;
    private final DeletedObjectService deletedObjectService;
    private final ContextService contextService;

    public DeletedObjectController( FieldFilterService fieldFilterService, DeletedObjectService deletedObjectService,
        ContextService contextService )
    {
        this.fieldFilterService = fieldFilterService;
        this.deletedObjectService = deletedObjectService;
        this.contextService = contextService;
    }

    @GetMapping
    public RootNode getDeletedObjects( DeletedObjectQuery query )
    {
        List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) );

        if ( fields.isEmpty() )
        {
            fields.addAll( Preset.ALL.getFields() );
        }

        List<DeletedObject> deletedObjects = deletedObjectService.getDeletedObjects( query );

        RootNode rootNode = NodeUtils.createMetadata();

        if ( !query.isSkipPaging() )
        {
            query.setTotal( deletedObjectService.countDeletedObjects( query ) );
            rootNode.addChild( NodeUtils.createPager( query.getPager() ) );
        }

        rootNode.addChild( fieldFilterService.filter( DeletedObject.class, deletedObjects, fields ) );

        return rootNode;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2004 The Apache Software Foundation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<!DOCTYPE connector PUBLIC "-//Sun Microsystems, Inc.//DTD Connector 1.0//EN"
	"http://java.sun.com/dtd/connector_1_0.dtd">

<connector>
    <display-name>test 1.0 adapter spec</display-name>
    <description>test ra.xml for jca 1.0</description>

    <vendor-name>apache-geronimo</vendor-name>
    <spec-version>1.0</spec-version>
    <eis-type>test</eis-type>
    <version>0.0</version>
    <resourceadapter>
        <managedconnectionfactory-class>org.apache.geronimo.connector.mock.MockManagedConnectionFactory</managedconnectionfactory-class>
        <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
        <connectionfactory-impl-class>org.apache.geronimo.connector.mock.MockConnectionFactory</connectionfactory-impl-class>
        <connection-interface>javax.resource.cci.Connection</connection-interface>
        <connection-impl-class>org.apache.geronimo.connector.mock.MockConnection</connection-impl-class>
        <transaction-support>XATransaction</transaction-support>
        <config-property>
            <config-property-name>OutboundStringProperty1</config-property-name>
            <config-property-type>java.lang.String</config-property-type>
            <config-property-value>originalvalue1</config-property-value>
        </config-property>
        <config-property>
            <config-property-name>OutboundStringProperty2</config-property-name>
            <config-property-type>java.lang.String</config-property-type>
            <config-property-value>originalvalue2</config-property-value>
        </config-property>
        <config-property>
            <config-property-name>OutboundStringProperty3</config-property-name>
            <config-property-type>java.lang.String</config-property-type>
        </config-property>
        <config-property>
            <config-property-name>OutboundStringProperty4</config-property-name>
            <config-property-type>java.lang.String</config-property-type>
        </config-property>

        <authentication-mechanism>
            <description>description</description>
            <authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
            <credential-interface>javax.resource.spi.security.PasswordCredential</credential-interface>
        </authentication-mechanism>
        <authentication-mechanism>
            <description>description</description>
            <authentication-mechanism-type>Kerbv5</authentication-mechanism-type>
            <credential-interface>javax.resource.spi.security.GenericCredential</credential-interface>
        </authentication-mechanism>
        <reauthentication-support>false</reauthentication-support>
        <security-permission>
            <description>test security permission</description>
            <security-permission-spec>org.apache.geronimo.TestSecurityPermission</security-permission-spec>
        </security-permission>
    </resourceadapter>
</connector>


text:
#include "AccessPoint.h"

#include <folly/Conv.h>
#include <folly/IPAddress.h>

#include "mcrouter/lib/fbi/cpp/util.h"

namespace facebook { namespace memcache {

AccessPoint::AccessPoint(folly::StringPiece host, uint16_t port,
                         mc_protocol_t protocol)
    : host_(host.str()),
      port_(port),
      protocol_(protocol) {
  initialize();
}

bool AccessPoint::create(folly::StringPiece host_port_protocol,
                         mc_protocol_t default_protocol,
                         AccessPoint& ap) {
  if (host_port_protocol.empty()) {
    return false;
  }

  if (host_port_protocol[0] == '[') {
    // IPv6
    auto closing = host_port_protocol.find(']');
    if (closing == std::string::npos) {
      return false;
    }
    ap.host_ = host_port_protocol.subpiece(1, closing - 1).str();
    host_port_protocol.advance(closing + 1);
  } else {
    // IPv4 or hostname
    auto colon = host_port_protocol.find(':');
    if (colon == std::string::npos) {
      return false;
    }
    ap.host_ = host_port_protocol.subpiece(0, colon).str();
    host_port_protocol.advance(colon);
  }

  if (host_port_protocol.empty() || host_port_protocol[0] != ':') {
    // port is required
    return false;
  }

  // skip ':'
  host_port_protocol.advance(1);
  auto colon = host_port_protocol.find(':');
  if (colon == std::string::npos) {
    // protocol is optional

    if (host_port_protocol.empty()) {
      return false;
    }
    ap.port_ = folly::to<uint16_t>(host_port_protocol);
    ap.protocol_ = default_protocol;
  } else {
    if (colon == 0) {
      return false;
    }
    ap.port_ = folly::to<uint16_t>(host_port_protocol.subpiece(0, colon));
    host_port_protocol.advance(colon + 1);
    ap.protocol_ = mc_string_to_protocol(host_port_protocol.data());
  }

  if (ap.host_.empty()) {
    return false;
  }

  ap.initialize();

  return true;
}

std::string AccessPoint::toHostPortString() const {
  if (isV6_) {
    return folly::to<std::string>("[", host_, "]:", port_);
  }
  return folly::to<std::string>(host_, ":", port_);
}

void AccessPoint::initialize() {
  isV6_ = false;
  try {
    folly::IPAddress ip(host_);
    host_ = ip.toFullyQualified();
    isV6_ = ip.isV6();
  } catch (const folly::IPAddressFormatException& e) {
    // host is not an IP address (e.g. 'localhost')
  }
}

std::string AccessPoint::toString() const {
  assert(protocol_ != mc_unknown_protocol);
  return folly::to<std::string>(toHostPortString(), ":TCP:",
                                mc_protocol_to_string(protocol_));
}

}}  // facebook::memcache


text:
namespace IECorePython
{

void bindAlexaLogcToLinearOp();

} // namespace IECorePython

#endif // IECOREPYTHON_ALEXALOGCTOLINEAROPBINDING_H


text:
def extractWatashiWaSugoiDesu(item):
	'''
	Parser for 'Watashi wa Sugoi Desu'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('Violant of the Silver',                           'Violant of the Silver',                                                                                'translated'),
		('dolls',                                           'I Decided to Not Compete and Quietly Create Dolls Instead',                                                     'translated'),
		('But You Said You\'d Give Me Delicious Candy!!',   'But You Said You\'d Give Me Delicious Candy!!',                                                                 'translated'),
		('Kokkuri-san',                                     'But You Said You\'d Give Me Delicious Candy!!',                                                                 'translated'),
		('Cute Friend',                                     'The Hero's Cute Childhood Friend, Doesn't Know of His Pitch-Black Nature',                                      'translated'),
		('TS Girl',                                         'My Best Friend Became A Transsexual Girl, And Says He Wants to Marry Me, But I'll Flat Out Refuse.',            'translated'),
		('SFY',                                             'Searching For You',                                                                                'translated'),
		('smgo',                                            'The Show Must Go On',                                                                                'translated'),
		('wsbw',                                            'When She Becomes a Witch',                                                                                'translated'),
		('gdg',                                             'The Gentle Death God Laughs Above the Cherry-Blossom Sky',                                                      'translated'),
		('Corporate Slave',                                 'Money makes the (Other) World Go Round: The Corporate Slave Dragged into the Saint Summoning',                  'translated'),
		('undead sage',                                     'The Executed Sage Reincarnates as a Lich and Begins a War of Aggression',                                       'translated'),
		('tensei saki de suterareta',                       'Tensei Saki de Suterareta no de, Mofumofu Tachi to Oryouri Shimasu ~Okazari Ouhi wa my Pace ni Saikyou Desu~',  'translated'),
		('KtBC',                                            'Kiss the Black Cat',                                                                                'translated'),
		('Ossan Idol',                                      'Ossan (36) Ga Idol Ni Naru Hanashi',                                                                            'translated'),
		('Strongest Wiseman',                               'Child Rearing Journal of the Strongest Wiseman~About My Daughter Being the Cutest in the World~',             'translated'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	titlemap = [
		('Child Rearing Journal of the Strongest Wiseman~About My Daughter Being the Cutest in the World~',  'Child Rearing Journal of the Strongest Wiseman~About My Daughter Being the Cutest in the World~',      'translated'),
		('Ossan Idol : Chapter',                                                                          'Ossan (36) Ga Idol Ni Naru Hanashi',                                                                     'translated'),
	]

	for titlecomponent, name, tl_type in titlemap:
		if titlecomponent.lower() in item['title'].lower():
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


text:
package net.java.sip.communicator.gui.plaf;

import javax.swing.plaf.metal.*;
import javax.swing.plaf.ColorUIResource;
import net.java.sip.communicator.gui.GuiManager;
import java.awt.Color;
import javax.swing.*;
import net.java.sip.communicator.common.*;

/**
 * SipCommunicator color settings
 * @todo load from XML
 * @author Emil Ivov <emcho@dev.java.net>
 * @version 1.0
 */

public class SipCommunicatorColorTheme
    extends DefaultMetalTheme
{
    private static final Console console = Console.getConsole(SipCommunicatorColorTheme.class);

    //Set default colors
    //ColorUIResource defaultForeground = new ColorUIResource(122, 150, 233);
    ColorUIResource defaultForeground = new ColorUIResource(48, 63, 112);
    ColorUIResource menuForeground    = defaultForeground;

    ColorUIResource textHighlightColor = new ColorUIResource(212, 208, 200);
    //ColorUIResource textColor          = new ColorUIResource(21, 49, 129);
    ColorUIResource textColor          = new ColorUIResource(48, 63, 112);
       ColorUIResource controlTextColor   = textColor;
    ColorUIResource inactiveControlTextColor = textHighlightColor;
    ColorUIResource userTextColor      = textColor;
    ColorUIResource highlightedTextColor = textColor;

    ColorUIResource defaultBackground = new ColorUIResource(255, 255, 255);
    ColorUIResource menuBackground    = defaultBackground;

    ColorUIResource scSecondaryThree = new ColorUIResource(242, 242, 242);
    ColorUIResource scPrimaryOne     = new ColorUIResource(212, 208, 200);
    ColorUIResource scPrimaryThree   = scSecondaryThree;

    //-----------------------
    public static ColorUIResource NOT_REGISTERED = new ColorUIResource(224, 101, 131);
    public static ColorUIResource REGISTERING    = new ColorUIResource(134, 124, 176);
    public static ColorUIResource REGISTERED     = new ColorUIResource(85, 182, 127);
    //--------
//    public static ColorUIResource CONTACT_GROUP    = new ColorUIResource(134, 124, 176);
    public static ColorUIResource CONTACT_GROUP    = new ColorUIResource(213, 105, 131);
//    public static ColorUIResource CONTACT_GROUP    = new ColorUIResource(236, 46, 94);
//    public static ColorUIResource ON_LINE_CONTACT  = new ColorUIResource(48, 63, 112);
    public static ColorUIResource ON_LINE_CONTACT  = new ColorUIResource(53, 40, 120);
    public static ColorUIResource OFF_LINE_CONTACT = new ColorUIResource(Color.gray);
//    public static ColorUIResource OFF_LINE_CONTACT = new ColorUIResource(49, 49, 49);

    public String getName()
    {
        return "SipCommunicatorColorTheme";
    }
//--------------------------- MENUS --------------------------------------------
    public ColorUIResource getMenuForeground()
    {
        //return defaultForeground;
        return textColor;
    }

    public ColorUIResource getTextHighlightColor()
    {
        return textHighlightColor;
    }

    public ColorUIResource getMenuBackground()
    {
        return defaultBackground;
    }

    public ColorUIResource getMenuSelectedForeground()
    {
        return highlightedTextColor;
    }

    public ColorUIResource getMenuSelectedBackground()
    {
        return textHighlightColor;
    }

//---------------------------- PRIMARY, SECONDARY ... --------------------------
    protected ColorUIResource getPrimary1()
    {
        return defaultForeground;
    }

    protected ColorUIResource getPrimary3()
    {
        return scPrimaryThree;
    }

    protected ColorUIResource getPrimary2()
    {
        return scPrimaryOne;
    }

    protected ColorUIResource getSecondary1()
    {
        return defaultForeground;
    }
    /*
    protected ColorUIResource getSecondary2()
    {
       return defaultBackground;
    }
*/
    protected ColorUIResource getSecondary3()
    {
       return scSecondaryThree;
    }

    protected ColorUIResource getBlack()
    {
//       return defaultForeground;
        return textColor;
    }

//    public ColorUIResource getHighlightedTextColor()
//    {
//       return highlightedTextColor;
//    }
/*
    public ColorUIResource getControlTextColor()
    {
       return highlightedTextColor;
    }
*/
//------------------------------------------------------------------------------
    public ColorUIResource getInactiveControlTextColor()
    {
        return inactiveControlTextColor;

    }

    public ColorUIResource getControlTextColor()
    {
        return controlTextColor;
    }

    public ColorUIResource getUserTextColor()
    {
        return userTextColor;
    }

    /**
     * Helper method to use when running separate sip-communicator modules
     */
    public static void initLookAndFeel()
    {
        MetalLookAndFeel mlf = new MetalLookAndFeel();
        mlf.setCurrentTheme( new SipCommunicatorColorTheme());

        try {
            UIManager.setLookAndFeel(mlf);
        }
        catch (UnsupportedLookAndFeelException ex) {
            console.error("Failed to set custom look and feel", ex);
        }
    }

}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.core.analysis;

import static org.junit.Assert.*;

import org.junit.*;

import ghidra.app.plugin.core.analysis.AnalysisBackgroundCommand;
import ghidra.app.plugin.core.analysis.AutoAnalysisManager;
import ghidra.framework.cmd.Command;
import ghidra.framework.options.Options;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.address.AddressSet;
import ghidra.program.model.data.DWordDataType;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.SourceType;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.TestEnv;

public class ArmBranchReturnDetectionTest extends AbstractGhidraHeadedIntegrationTest {

	private TestEnv env;
	private PluginTool tool;

	private Program program;

	private ProgramBuilder builder;

	@Before
	public void setUp() throws Exception {
		env = new TestEnv();
		tool = env.getTool();
	}

	@After
	public void tearDown() {
		if (program != null) {
			env.release(program);
		}
		program = null;
		env.dispose();
	}

	private void analyze() {
		// turn off some analyzers
		setAnalysisOptions("Stack");
		setAnalysisOptions("Embedded Media");
		setAnalysisOptions("DWARF");
		setAnalysisOptions("Create Address Tables");

		AutoAnalysisManager analysisMgr = AutoAnalysisManager.getAnalysisManager(program);
		analysisMgr.reAnalyzeAll(null);

		Command cmd = new AnalysisBackgroundCommand(analysisMgr, false);
		tool.execute(cmd, program);
		waitForBusyTool(tool);
	}

	protected void setAnalysisOptions(String optionName) {
		int txId = program.startTransaction("Analyze");
		Options analysisOptions = program.getOptions(Program.ANALYSIS_PROPERTIES);
		analysisOptions.setBoolean(optionName, false);
		program.endTransaction(txId, true);
	}

	/**
	 * This tests that a pop to the pc with the lr register is changed to a return
	 *
	 * That the thunking function can be found with the constant reference analyzer
	 *
	 */
	@Test
	public void testDelayArmPopReturn1() throws Exception {

		builder = new ProgramBuilder("thunk", ProgramBuilder._ARM);

		builder.setBytes("0x00015d9c", "10 b5 03 48 10 bc 01 bc 00 47");
		builder.setRegisterValue("TMode", "0x00015d9c", "0x00015d9c", 1);
		builder.disassemble("0x00015d9c", 27, true);

		builder.createFunction("0x00015d9c");
		builder.createLabel("0x00015d9c", "func1");;

		program = builder.getProgram();

		analyze();

		Instruction instruction = program.getListing().getInstructionAt(builder.addr(0x00015da4));
		assertNotNull(instruction);

		assertTrue("pop turned into return", instruction.getFlowType().isTerminal());
	}
}


text:
<!DOCTYPE html>

			<title>TabBarGadget - Union Bytes - Codes & Documentation</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			<link rel="stylesheet" type="text/css" href="/general.css" />
			<link rel="icon" type="image/png" href="/images/icon.png" />

			Union Bytes
Codes & Documentation

				<form id="search" action="/tbg/" method="get">
					<input name="search" autocomplete="off" onFocus="ClearSearch(this)" onBlur="FillSearch(this)" value="Search ..." onkeydown="var obj=this; window.setTimeout(function(){UpdateInstantBox(obj)}, 1)">
				</form>

TabBarGadget

TabBarGadget
ConfigurationExamplesFunctionsHistory

TabBarGadgetPROJECT

 Description

The TabBarGadget creates a bar with tabs without its own container.
With different attributes and functions you can change the appearance of the bar and the tabs.
For example you can add a close button on each tab or icons and
you can swap tabs with the mouse easily and add or remove tabs.

 Features

Cross-platform include for Windows, Linux and MacOS

Horizontal and vertical tab bars

Text cutting, navigation or multiple rows with many tabs

Adding, closing, swapping or editing of tabs.

Customizable tabs with colors, fonts and icons

And many more ...

				Union Bytes | Login <form id="pwf" style="display: none;" method="post"> | <input name="password" type="password" value="" style="width:60px;"></form>


text:
package reverser

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"time"
)

func TestHello(t *testing.T) {
	input := "hello"
	expected := "olleh"
	time.Sleep(25 * time.Second)
	assert.Equal(t, expected, Reverse(input), "reversing empty string")
}


text:
FactoryBot.define do
  factory :league_division, class: League::Division do
    sequence(:name) { |n| "Div #{n}" }
    league
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/toolbar_top_padding"
            app:theme="@style/ToolbarStyle"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:id="@+id/toolbar" />

        <FrameLayout
            android:id="@+id/container"
            android:layout_below="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </RelativeLayout>

    <fragment
        android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.github.mobile.ui.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>


text:
module 'mock'
--------------------------------------------------------------------
local charCodes = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,:.?!{}()<>+_="
--------------------------------------------------------------------
-------font
local function loadFont( node )
	local font  = MOAIFont.new()
	local atype = node.type
	--TODO: support serialized font
	local attributes = node.attributes or {}
	if attributes[ 'serialized' ] then
		local sdataPath   = node.objectFiles['data']
		local texturePath = node.objectFiles['texture']
		font = dofile( sdataPath )
		-- load the font image back in
		local image = MOAIImage.new ()
		image:load ( texturePath, 0 )
		-- set the font image
		font:setCache()
		font:setReader()
		font:setImage( image )
	end

	if atype == 'font_bmfont' then
		local texPaths = {}
		for k, v in pairs( node.dependency ) do
			if k:sub(1,3) == 'tex' then
				local id = tonumber( k:sub(5,-1) )
				texPaths[ id ] = v
			end
		end
		local textures = {}
		for i, path in ipairs( texPaths ) do
			local tex, node = loadAsset( path )
			table.insert( textures, tex:getMoaiTexture() )
		end
		if #textures > 0 then
			font:loadFromBMFont( node.objectFiles['font'], textures )
		else
			_warn('bmfont texture not load', node:getNodePath() )
		end

	elseif atype == 'font_ttf' then
		local filename = node.objectFiles['font']
		font:getReader():enableAntiAliasing( true )
		font:getCache():setColorFormat( MOAIImage.COLOR_FMT_RGBA_8888 )
		font:load( filename, 0 )

	elseif atype == 'font_bdf' then
		font:load( node.objectFiles['font'] )

	else
		_error( 'failed to load font:', node.path )
		return getFontPlaceHolder()
	end

	local dpi           = 72
	local size          = attributes['size'] or 20
	local preloadGlyphs = attributes['preloadGlyphs']

	if preloadGlyphs then	font:preloadGlyphs( preloadGlyphs, size ) end
	font.size = size

	return font
end

--------------------------------------------------------------------
registerAssetLoader( 'font_ttf',    loadFont )
registerAssetLoader( 'font_bdf',    loadFont )
registerAssetLoader( 'font_bmfont', loadFont )

--preload font placeholder
getFontPlaceHolder()


text:
"use strict";

const ContainerObject = require('../lib/object/container-object');
const EmptyObject = require('../utils/empty-object');
const RSVP = require('rsvp');
const inject = require('../lib/object/inject');

module.exports = ContainerObject.compose({

    _records: null,
    _models: null,

    _createModel(modelName, Schema) {
        let Model = function() {};
        this._models[modelName] = Model;
    },

    modelFor(modelName) {
        if (this._models[modelName]) {
            return Promise.resolve(this._models[modelName]);
        }
        return this.container.lookup(`schema:${modelName}`)
            .then((Schema) => {
                this._createModel(modelName, Schema);
                return this._models[modelName];
            });
    },

    findRecord(modelName, id) {
        return this.modelFor(modelName).then(
            (Model) => {
                return new Model({ id: id })
                    .fetch({
                        require: true
                    });
            });
    },

    findRecords(modelName, ids) {
        return this.modelFor(modelName).then(
            (Model) => {
                const promises = ids.map((id) => {
                    return new Model({ id: id })
                        .fetch({ require: true });
                });
                return RSVP.allSettled(promises);
            });
    },

    query(modelName, query) {
        return this.modelFor(modelName).then(
            (Model) => {
                return new Model(query)
                    .fetch({});
            });
    },

    queryRecord(modelName, query) {
        return this.modelFor(modelName).then(
            (Model) => {
                return new Model(query)
                    .fetchOne({})
            });
    },

    updateRecord() {},
    removeRecord() {},
    createRecord() {},

    seed() {},

    init() {
        this._records = new EmptyObject();
        this._schema = new EmptyObject();
    }

});


text:
require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");

local function constructNew_frmWeaponListForm()
    local obj = GUI.fromHandle(_obj_newObject("form"));
    local self = obj;
    local sheet = nil;

    rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));

    function obj:setNodeObject(nodeObject)
        sheet = nodeObject;
        self.sheet = nodeObject;
        self:_oldSetNodeObjectFunction(nodeObject);
    end;

    function obj:setNodeDatabase(nodeObject)
        self:setNodeObject(nodeObject);
    end;

    _gui_assignInitialParentForForm(obj.handle);
    obj:beginUpdate();
    obj:setName("frmWeaponListForm");
    obj:setWidth(810);
    obj:setHeight(25);
    obj:setMargins({top=1});

    obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
    obj.rectangle1:setParent(obj);
    obj.rectangle1:setAlign("client");
    obj.rectangle1:setColor("#212121");
    obj.rectangle1:setName("rectangle1");

    obj.edit1 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit1:setParent(obj.rectangle1);
    obj.edit1:setLeft(0);
    obj.edit1:setTop(0);
    obj.edit1:setWidth(150);
    obj.edit1:setHeight(25);
    obj.edit1:setField("nome");
    obj.edit1:setName("edit1");

    obj.edit2 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit2:setParent(obj.rectangle1);
    obj.edit2:setLeft(150);
    obj.edit2:setTop(0);
    obj.edit2:setWidth(150);
    obj.edit2:setHeight(25);
    obj.edit2:setField("ataque");
    obj.edit2:setName("edit2");

    obj.edit3 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit3:setParent(obj.rectangle1);
    obj.edit3:setLeft(300);
    obj.edit3:setTop(0);
    obj.edit3:setWidth(50);
    obj.edit3:setHeight(25);
    obj.edit3:setField("bba");
    obj.edit3:setName("edit3");

    obj.edit4 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit4:setParent(obj.rectangle1);
    obj.edit4:setLeft(350);
    obj.edit4:setTop(0);
    obj.edit4:setWidth(50);
    obj.edit4:setHeight(25);
    obj.edit4:setField("habilidade");
    obj.edit4:setType("number");
    obj.edit4:setName("edit4");

    obj.edit5 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit5:setParent(obj.rectangle1);
    obj.edit5:setLeft(400);
    obj.edit5:setTop(0);
    obj.edit5:setWidth(50);
    obj.edit5:setHeight(25);
    obj.edit5:setField("outros");
    obj.edit5:setType("number");
    obj.edit5:setName("edit5");

    obj.edit6 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit6:setParent(obj.rectangle1);
    obj.edit6:setLeft(450);
    obj.edit6:setTop(0);
    obj.edit6:setWidth(50);
    obj.edit6:setHeight(25);
    obj.edit6:setField("dano");
    obj.edit6:setName("edit6");

    obj.edit7 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit7:setParent(obj.rectangle1);
    obj.edit7:setLeft(505);
    obj.edit7:setTop(0);
    obj.edit7:setWidth(50);
    obj.edit7:setHeight(25);
    obj.edit7:setField("tipo");
    obj.edit7:setName("edit7");

    obj.edit8 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit8:setParent(obj.rectangle1);
    obj.edit8:setLeft(555);
    obj.edit8:setTop(0);
    obj.edit8:setWidth(50);
    obj.edit8:setHeight(25);
    obj.edit8:setField("tamanho");
    obj.edit8:setName("edit8");

    obj.edit9 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit9:setParent(obj.rectangle1);
    obj.edit9:setLeft(605);
    obj.edit9:setTop(0);
    obj.edit9:setWidth(50);
    obj.edit9:setHeight(25);
    obj.edit9:setField("alcance");
    obj.edit9:setName("edit9");

    obj.edit10 = GUI.fromHandle(_obj_newObject("edit"));
    obj.edit10:setParent(obj.rectangle1);
    obj.edit10:setLeft(655);
    obj.edit10:setTop(0);
    obj.edit10:setWidth(110);
    obj.edit10:setHeight(25);
    obj.edit10:setField("qualidades");
    obj.edit10:setName("edit10");

    obj.button1 = GUI.fromHandle(_obj_newObject("button"));
    obj.button1:setParent(obj.rectangle1);
    obj.button1:setLeft(765);
    obj.button1:setTop(0);
    obj.button1:setWidth(25);
    obj.button1:setHeight(25);
    obj.button1:setText("X");
    obj.button1:setName("button1");

    obj._e_event0 = obj.button1:addEventListener("onClick",
        function (_)
            dialogs.confirmOkCancel("Tem certeza que quer apagar esse objeto?",
            					function (confirmado)
            						if confirmado then
            							ndb.deleteNode(sheet);
            						end;
            				end);
        end, obj);

    function obj:_releaseEvents()
        __o_rrpgObjs.removeEventListenerById(self._e_event0);
    end;

    obj._oldLFMDestroy = obj.destroy;

    function obj:destroy()
        self:_releaseEvents();

        if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
          self:setNodeDatabase(nil);
        end;

        if self.edit3 ~= nil then self.edit3:destroy(); self.edit3 = nil; end;
        if self.edit9 ~= nil then self.edit9:destroy(); self.edit9 = nil; end;
        if self.edit5 ~= nil then self.edit5:destroy(); self.edit5 = nil; end;
        if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end;
        if self.edit10 ~= nil then self.edit10:destroy(); self.edit10 = nil; end;
        if self.edit4 ~= nil then self.edit4:destroy(); self.edit4 = nil; end;
        if self.edit6 ~= nil then self.edit6:destroy(); self.edit6 = nil; end;
        if self.edit8 ~= nil then self.edit8:destroy(); self.edit8 = nil; end;
        if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
        if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end;
        if self.edit7 ~= nil then self.edit7:destroy(); self.edit7 = nil; end;
        if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
        self:_oldLFMDestroy();
    end;

    obj:endUpdate();

    return obj;
end;

function newfrmWeaponListForm()
    local retObj = nil;
    __o_rrpgObjs.beginObjectsLoading();

    __o_Utils.tryFinally(
      function()
        retObj = constructNew_frmWeaponListForm();
      end,
      function()
        __o_rrpgObjs.endObjectsLoading();
      end);

    assert(retObj ~= nil);
    return retObj;
end;

local _frmWeaponListForm = {
    newEditor = newfrmWeaponListForm,
    new = newfrmWeaponListForm,
    name = "frmWeaponListForm",
    dataType = "",
    formType = "undefined",
    formComponentName = "form",
    title = "",
    description=""};

frmWeaponListForm = _frmWeaponListForm;
Firecast.registrarForm(_frmWeaponListForm);

return _frmWeaponListForm;


text:
object RecursiveFunction {
class PathsTree(parent: Option[PathsTree]) {
  override def toString = /*start*/parent.map(pathsTree => pathsTree.toString)/*end*/.getOrElse("dfadf")
}
}
//Option[String]


text:
# ifndef H_STROMA_V_UT_METADATA_COMMON_AUX_ROUTINES_H
# define H_STROMA_V_UT_METADATA_COMMON_AUX_ROUTINES_H

# include <string>
# include <utility>
# include <vector>
# include <cassert>
# include "event.pb.h"
# include "metadata/traits.tcc"

namespace sV {
namespace test {

std::vector< std::pair<size_t, size_t> >
extract_words_positions( const char * const s );

void
copy_word_to_event( const std::string & word,
                    sV::events::Event & event );

std::string
get_word_from_event( const sV::events::Event & );

// Aux class keeping words obtained using metadata
class ExtractedWords : public aux::iEventSequence {
private:
    std::list<std::string> _words;
    std::list<std::string>::const_iterator _it;
    Event _rE;
    bool _isGood;
protected:
    virtual bool _V_is_good() override { return _isGood; }
    virtual void _V_next_event( Event *& eventPtrRef ) override {
        if( _it != _words.end() ) {
            copy_word_to_event( *_it, *eventPtrRef );
            ++_it;
        } else {
            _isGood = false;
            eventPtrRef = nullptr;
        }
    }
    /// Has to return a pointer to a valid event. Can invoke _V_next_event()
    /// internally.
    virtual Event * _V_initialize_reading() override {
        Event * _evPtr = &_rE;
        _it = _words.begin();
        _isGood = true;
        _V_next_event( _evPtr );
        return _evPtr;
    }
    virtual void _V_finalize_reading() override {
        _it = _words.end();
        _isGood = false;
    }
public:
    ExtractedWords() : iEventSequence(0x0) {}
    ExtractedWords( const std::list<std::string> & words_ ) :
                                iEventSequence(0x0),
                                _words(words_) {}
    void push_back_word( const std::string & w ) {
        _words.push_back( w );
    }
};

}  // namespace test
}  // namespace sV

# endif  // H_STROMA_V_UT_METADATA_COMMON_AUX_ROUTINES_H


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Management.Automation;
using System.Net;
using Microsoft.WindowsAzure.Commands.Common.Models;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Helpers;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Management.Compute.Models;

namespace Microsoft.WindowsAzure.Commands.ServiceManagement.HostedServices
{
    using PVM = Model;

    /// <summary>
    /// Create a new deployment. Note that there shouldn't be a deployment
    /// of the same name or in the same slot when executing this command.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureDeployment", DefaultParameterSetName = "PaaS"), OutputType(typeof(ManagementOperationContext))]
    public class NewAzureDeploymentCommand : ServiceManagementBaseCmdlet
    {
        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Cloud service name.")]
        [ValidateNotNullOrEmpty]
        public string ServiceName
        {
            get;
            set;
        }

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "Package location. This parameter specifies the path or URI to a .cspkg in blob storage. The storage account must belong to the same subscription as the deployment.")]
        [ValidateNotNullOrEmpty]
        public string Package
        {
            get;
            set;
        }

        [Parameter(Position = 2, Mandatory = true,  HelpMessage = "Configuration file path. This parameter should specifiy a .cscfg file on disk.")]
        [ValidateNotNullOrEmpty]
        public string Configuration
        {
            get;
            set;
        }

        [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Deployment slot [Staging | Production].")]
        [ValidateSet(Microsoft.WindowsAzure.Commands.ServiceManagement.Model.DeploymentSlotType.Staging, Microsoft.WindowsAzure.Commands.ServiceManagement.Model.DeploymentSlotType.Production, IgnoreCase = true)]
        public string Slot
        {
            get;
            set;
        }

        [Parameter(Position = 4, Mandatory = false, HelpMessage = "Label for the new deployment.")]
        [ValidateNotNullOrEmpty]
        public string Label
        {
            get;
            set;
        }

        [Parameter(Position = 5, HelpMessage = "Deployment name.")]
        [Alias("DeploymentName")]
        [ValidateNotNullOrEmpty]
        public string Name
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, HelpMessage = "Do not start deployment upon creation.")]
        public SwitchParameter DoNotStart
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, HelpMessage = "Indicates whether to treat package validation warnings as errors.")]
        public SwitchParameter TreatWarningsAsError
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Extension configurations.")]
        public ExtensionConfigurationInput[] ExtensionConfiguration
        {
            get;
            set;
        }

        public virtual void NewPaaSDeploymentProcess()
        {
            bool removePackage = false;

            AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Production);
            AssertNoPersistenVmRoleExistsInDeployment(PVM.DeploymentSlotType.Staging);

            var storageName = CurrentContext.Subscription.GetProperty(Commands.Common.Models.AzureSubscription.Property.StorageAccount);

            Uri packageUrl;
            if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                packageUrl = new Uri(this.Package);
            }
            else
            {
                var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage);
                WriteProgress(progress);
                removePackage = true;
                packageUrl = this.RetryCall(s =>
                    AzureBlob.UploadPackageToBlob(
                    this.StorageClient,
                    storageName,
                    this.Package,
                    null));
            }

            ExtensionConfiguration extConfig = null;
            if (ExtensionConfiguration != null)
            {
                string errorConfigInput = null;
                if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput))
                {
                    throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput));
                }

                foreach (ExtensionConfigurationInput context in ExtensionConfiguration)
                {
                    if (context != null && context.X509Certificate != null)
                    {
                        ExecuteClientActionNewSM(
                            null,
                            string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint),
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate)));
                    }
                }

                var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true);
                DeploymentGetResponse d = null;
                InvokeInOperationContext(() =>
                {
                    try
                    {
                        d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
                        {
                            this.WriteExceptionDetails(ex);
                        }
                    }
                });

                ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName);
                extConfig = extensionMgr.Set(d, ExtensionConfiguration, this.Slot);
            }

            var deploymentInput = new DeploymentCreateParameters
            {
                PackageUri = packageUrl,
                Configuration = GeneralUtilities.GetConfiguration(this.Configuration),
                ExtensionConfiguration = extConfig,
                Label = this.Label,
                Name = this.Name,
                StartDeployment = !this.DoNotStart.IsPresent,
                TreatWarningsAsError = this.TreatWarningsAsError.IsPresent,
            };

            InvokeInOperationContext(() =>
            {
                try
                {
                    var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.CreatingNewDeployment);
                    WriteProgress(progress);

                    ExecuteClientActionNewSM(
                        deploymentInput,
                        CommandRuntime.ToString(),
                        () => this.ComputeClient.Deployments.Create(
                            this.ServiceName,
                            (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                            deploymentInput));

                    if (removePackage == true)
                    {
                        this.RetryCall(s => AzureBlob.DeletePackageFromBlob(
                            this.StorageClient,
                            storageName,
                            packageUrl));
                    }
                }
                catch (CloudException ex)
                {
                    this.WriteExceptionDetails(ex);
                }
            });
        }

        private void AssertNoPersistenVmRoleExistsInDeployment(string slot)
        {
            InvokeInOperationContext(() =>
            {
                try
                {
                    var currentDeployment = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), slot, true));
                    if (currentDeployment.Roles != null)
                    {
                        if (string.Compare(currentDeployment.Roles[0].RoleType, "PersistentVMRole", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            throw new ArgumentException(String.Format(Resources.CanNotCreateNewDeploymentWhileVMsArePresent, slot));
                        }
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
                    {
                        this.WriteExceptionDetails(ex);
                    }
                }
            });
        }

        protected override void OnProcessRecord()
        {
            ServiceManagementProfile.Initialize();
            this.ValidateParameters();
            this.NewPaaSDeploymentProcess();
        }

        protected virtual void ValidateParameters()
        {
            if (string.IsNullOrEmpty(this.Slot))
            {
                this.Slot = PVM.DeploymentSlotType.Production;
            }

            if (string.IsNullOrEmpty(this.Name))
            {
                 this.Name = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrEmpty(this.Label))
            {
                this.Label = this.Name;
            }

            if (string.IsNullOrEmpty(this.CurrentContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount)))
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }
        }
    }
}