text:
#ifndef CPPBENCHMARK_H
#define CPPBENCHMARK_H

#include "benchmark/executor.h"
#include "benchmark/launcher_console.h"
#include "benchmark/reporter_console.h"
#include "benchmark/reporter_csv.h"
#include "benchmark/reporter_json.h"

namespace CppBenchmark {

//! @cond INTERNALS
namespace Internals {

class BenchmarkRegistrator
{
public:
    explicit BenchmarkRegistrator(const std::function<std::shared_ptr<BenchmarkBase>()>& builder)
    { LauncherConsole::GetInstance().AddBenchmarkBuilder(builder); }
};

} // namespace Internals
//! @endcond

} // namespace CppBenchmark

//! @cond INTERNALS
#define BENCHMARK_INTERNAL_UNIQUE_NAME_LINE2(name, line) name##line
#define BENCHMARK_INTERNAL_UNIQUE_NAME_LINE(name, line) BENCHMARK_INTERNAL_UNIQUE_NAME_LINE2(name, line)
#define BENCHMARK_INTERNAL_UNIQUE_NAME(name) BENCHMARK_INTERNAL_UNIQUE_NAME_LINE(name, __LINE__)
//! @endcond

//! Benchmark main entry point macro
/*!
    Main entry point definition for all benchmarks. Place this macro in some .cpp file to provide a main() function
    with registered LauncherConsole with \a argc & \a argv arguments parsing.
*/
#define BENCHMARK_MAIN()\
int main(int argc, char** argv)\
{\
    CppBenchmark::LauncherConsole::GetInstance().Initialize(argc, argv);\
    CppBenchmark::LauncherConsole::GetInstance().Execute();\
    CppBenchmark::LauncherConsole::GetInstance().Report();\
    return 0;\
}

//! Benchmark register macro
/*!
    Register a new benchmark with a given name and settings. Next to the definition you should provide a benchmark code.

    Example:
    \code{.cpp}
    // This benchmark will call MyTest() function in 1000000 operations
    BENCHMARK("MyTestBenchmark", 1000000)
    {
        MyTest();
    }
    \endcode
*/
#define BENCHMARK(...)\
namespace CppBenchmark {\
    class BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__) : public Benchmark\
    {\
    public:\
        using Benchmark::Benchmark;\
    protected:\
        void Run(Context& context) override;\
    };\
    Internals::BenchmarkRegistrator BENCHMARK_INTERNAL_UNIQUE_NAME(benchmark_registrator)([]() { return std::make_shared<BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)>(__VA_ARGS__); });\
}\
void CppBenchmark::BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)::Run(CppBenchmark::Context& context)

//! Benchmark with fixture register macro
/*!
    Register a new benchmark with a given \a fixture, name and settings. Next to the definition you should provide a benchmark
    code. In benchmark code you can access to public and protected fields and methods of the fixture.

    Benchmark static fixture is a user class that will be constructed before benchmarking and will be destructed after.

    Static fixture example:
    \code{.cpp}
    // Vector fixture will be created only once and its field will be visible in benchmark body!
    class VectorFixture
    {
    protected:
        std::vector<int> container;
    };

    // This benchmark will insert random value into std::vector<int> 1000000 times
    BENCHMARK_FIXTURE(VectorFixture, "VectorPushBackBenchmark", 1000000)
    {
        container.push_back(rand());
    }
    \endcode

    Benchmark dynamic fixture is a user class inherited from Fixture base class and overrides Initialize()/Cleanup() methods
    that will be called before/after each benchmark attempt.

    Dynamic fixture example:
    \code{.cpp}
    // Vector fixture will be created only once and its filed will be visible in benchmark body!
    class VectorFixture : public virtual CppBenchmark::Fixture
    {
    protected:
        std::vector<int> container;

        // Initialize method will called just before each benchmark attempt
        void Initialize(CppBenchmark::Context& context) override { container = std::vector<int>(); }
        // Cleanup method will called just after each benchmark attempt
        void Cleanup(CppBenchmark::Context& context) override { container.clear(); }
    };

    // This benchmark will insert random value into std::vector<int> 1000000 times
    BENCHMARK_FIXTURE(VectorFixture, "VectorPushBackBenchmark", 1000000)
    {
        container.push_back(rand());
    }
    \endcode
*/
#define BENCHMARK_FIXTURE(fixture, ...)\
namespace CppBenchmark {\
    class BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__) : public Benchmark, public fixture\
    {\
    public:\
        using Benchmark::Benchmark;\
    protected:\
        void Run(Context& context) override;\
    };\
    Internals::BenchmarkRegistrator BENCHMARK_INTERNAL_UNIQUE_NAME(benchmark_registrator)([]() { return std::make_shared<BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)>(__VA_ARGS__); });\
}\
void CppBenchmark::BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)::Run(Context& context)

//! Benchmark threads register macro
/*!
    Register a new threads benchmark with a given name and settings. Next to the definition you should provide
    a benchmark code that will be executed in multi-thread environment. You can use \a settings parameter to give
    threads count you want to measure with.

    Example:
    \code{.cpp}
    // This benchmark will output random value in std::cout 1000000 times in 4 concurrent threads environment
    BENCHMARK_THREADS("ThreadsConsoleBenchmark", 4, 1000000)
    {
        std::count << rand();
    }
    \endcode
*/
#define BENCHMARK_THREADS(...)\
namespace CppBenchmark {\
    class BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__) : public BenchmarkThreads\
    {\
    public:\
        using BenchmarkThreads::BenchmarkThreads;\
    protected:\
        void RunThread(ContextThreads& context) override;\
    };\
    Internals::BenchmarkRegistrator BENCHMARK_INTERNAL_UNIQUE_NAME(benchmark_registrator)([]() { return std::make_shared<BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)>(__VA_ARGS__); });\
}\
void CppBenchmark::BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)::RunThread(CppBenchmark::ContextThreads& context)

//! Benchmark threads with fixture register macro
/*!
    Register a new threads benchmark with a given \a fixture, name and settings. Next to the definition you should
    provide a benchmark code that will be executed in multi-thread environment. In benchmark code you can access to
    public and protected fields & methods of the fixture. You can use \a settings parameter to give threads count
    you want to measure with.

    Benchmark static threads fixture is a user class that will be constructed before benchmarking and destructed after.

    Static threads fixture example:
    \code{.cpp}
    // Atomic threads fixture will be created only once and its field will be visible in benchmark body!
    class AtomicPreset
    {
    protected:
        std::atomic<int> counter;
    };

    // This benchmark will increment atomic counter 1000000 times in 4 concurrent threads environment
    BENCHMARK_THREADS_PRESET(AtomicPreset, "ThreadsAtomicIncrementBenchmark", 4, 1000000)
    {
        counter++;
    }
    \endcode

    Benchmark dynamic threads fixture is a user class inherited from Fixture or FixtureThreads base class and
    overrides Initialize()/Cleanup()/InitializeThread()/CleanupThread() methods that will be called before/after
    each benchmark attempt and before/after each thread is started/finished.

    Dynamic threads fixture example:
    \code{.cpp}
    // Atomic threads fixture will be created only once and its field will be visible in benchmark body!
    class AtomicFixture : public virtual CppBenchmark::FixtureThreads
    {
    protected:
        std::atomic<int> counter;

        // Initialize method will called just before each benchmark attempt
        void Initialize(CppBenchmark::ContextThreads& context) override { counter = 123; }
        // Cleanup method will called just after each benchmark attempt
        void Cleanup(CppBenchmark::ContextThreads& context) override { counter = 987; }

        // Initialize thread method will called just before each benchmark thread is started
        void InitializeThread(CppBenchmark::ContextThreads& context) override { counter = context.threads(); }
        // Cleanup thread method will called just after each benchmark thread is finished
        void CleanupThread(CppBenchmark::ContextThreads& context) override { counter = 0; }
    };

    // This benchmark will increment atomic counter 1000000 times in 4 concurrent threads environment
    BENCHMARK_THREADS_FIXTURE(AtomicFixture, "ThreadsAtomicIncrementBenchmark", 4, 1000000)
    {
        counter++;
    }
    \endcode
*/
#define BENCHMARK_THREADS_FIXTURE(fixture, ...)\
namespace CppBenchmark {\
    class BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__) : public BenchmarkThreads, public fixture\
    {\
    public:\
        using BenchmarkThreads::BenchmarkThreads;\
    protected:\
        void RunThread(ContextThreads& context) override;\
    };\
    Internals::BenchmarkRegistrator BENCHMARK_INTERNAL_UNIQUE_NAME(benchmark_registrator)([]() { return std::make_shared<BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)>(__VA_ARGS__); });\
}\
void CppBenchmark::BENCHMARK_INTERNAL_UNIQUE_NAME(__benchmark__)::RunThread(ContextThreads& context)

//! Benchmark class register macro
/*!
    Register a new benchmark based on a child class of a \a type with a given name and \a settings. You should
    inherit \a type from Benchmark, BenchmarkThreads or BenchmarkPC and implement all necessary benchmark methods.

    Example:
    \code{.cpp}
    class VectorBenchmark
    {
    protected:
        std::vector<int> container;

        void Initialize(CppBenchmark::Context& context) { container.reserve(1000); }
        void Run(CppBenchmark::Context& context) override { container.push_back(rand()); }
        void Cleanup(CppBenchmark::Context& context) override { container.clear(); }
    };

    // This benchmark will measure VectorBenchmark with 1000000 operations
    BENCHMARK_CLASS(VectorBenchmark, "VectorPushBackBenchmark", 1000000)
    \endcode
*/
#define BENCHMARK_CLASS(type, ...)\
namespace CppBenchmark { Internals::BenchmarkRegistrator BENCHMARK_INTERNAL_UNIQUE_NAME(benchmark_registrator)([]() { return std::make_shared<type>(__VA_ARGS__); }); }

//! Dynamic benchmark scope register macro
/*!
    Create a scope guard for dynamic benchmark with the given \a name. It will be automatically registered in static
    Executor class.

    Example:
    \code{.cpp}
    // Some scope...
    {
        auto benchmark = BENCHCODE_SCOPE("My dynamic benchmark");

        // Here goes some code fragment you want to benchmark dynamically...
        ...
    }
    \endcode
*/
#define BENCHCODE_SCOPE(name) CppBenchmark::Executor::ScopeBenchmark(name);

//! Dynamic benchmark start macro
/*!
    Start dynamic benchmark with the given \a name. It will be automatically registered in static Executor class.
    Should be used in pair with BENCHCODE_STOP macro!

    Example:
    \code{.cpp}
    BENCHCODE_START("My dynamic benchmark");

    // Here goes some code fragment you want to benchmark dynamically...
    ...

    BENCHCODE_STOP("My dynamic benchmark");
    \endcode
*/
#define BENCHCODE_START(name) CppBenchmark::Executor::StartBenchmark(name);

//! Dynamic benchmark stop macro
/*!
    Stop dynamic benchmark with the given \a name. It will be automatically registered in static Executor class.
    Should be used in pair with BENCHCODE_START macro!

    Example:
    \code{.cpp}
    BENCHCODE_START("My dynamic benchmark");

    // Here goes some code fragment you want to benchmark dynamically...
    ...

    BENCHCODE_STOP("My dynamic benchmark");
    \endcode
*/
#define BENCHCODE_STOP(name) CppBenchmark::Executor::StopBenchmark(name);

//! Dynamic benchmarks report to console macro
/*!
    Prepare results of all dynamic benchmarks registered in static Executor class and show them using ReporterConsole.

    Example:
    \code{.cpp}
    int main(int argc, char** argv)
    {
        // Do some calculations or program run and measure code fragments with dynamic benchmarks...
        ...

        // Report benchmark results
        BENCHCODE_REPORT();

        return 0;
    }
    \endcode
*/
#define BENCHCODE_REPORT()\
{\
    CppBenchmark::ReporterConsole BENCHMARK_INTERNAL_UNIQUE_NAME(reporter);\
    CppBenchmark::Executor::Report(BENCHMARK_INTERNAL_UNIQUE_NAME(reporter));\
}

//! Dynamic benchmarks report as a string macro
/*!
    Prepare results of all dynamic benchmarks registered in static Executor class using ReporterConsole and store them
    in a string variable \a value.

    Example:
    \code{.cpp}
    // Report benchmark results
    std::string report;
    BENCHCODE_REPORT_STR(report);
    \endcode
*/
#define BENCHCODE_REPORT_STR(value)\
{\
    std::ostringstream BENCHMARK_INTERNAL_UNIQUE_NAME(output);\
    CppBenchmark::ReporterConsole BENCHMARK_INTERNAL_UNIQUE_NAME(reporter)(BENCHMARK_INTERNAL_UNIQUE_NAME(output));\
    CppBenchmark::Executor::Report(BENCHMARK_INTERNAL_UNIQUE_NAME(reporter));\
    value = BENCHMARK_INTERNAL_UNIQUE_NAME(output).str();\
}

//! Dynamic benchmarks report as a CSV format string macro
/*!
    Prepare results of all dynamic benchmarks registered in static Executor class using ReporterCSV and store them
    in a string variable \a value.

    Example:
    \code{.cpp}
    // Report benchmark results in CSV format
    std::string report;
    BENCHCODE_REPORT_CSV(report);
    \endcode
*/
#define BENCHCODE_REPORT_CSV(value)\
{\
    std::ostringstream BENCHMARK_INTERNAL_UNIQUE_NAME(output);\
    CppBenchmark::ReporterCSV BENCHMARK_INTERNAL_UNIQUE_NAME(reporter)(BENCHMARK_INTERNAL_UNIQUE_NAME(output));\
    CppBenchmark::Executor::Report(BENCHMARK_INTERNAL_UNIQUE_NAME(reporter));\
    value = BENCHMARK_INTERNAL_UNIQUE_NAME(output).str();\
}

//! Dynamic benchmarks report as a JSON format string macro
/*!
    Prepare results of all dynamic benchmarks registered in static Executor class using ReporterJSON and store them
    in a string variable \a value.

    Example:
    \code{.cpp}
    // Report benchmark results in JSON format
    std::string report;
    BENCHCODE_REPORT_JSON(report);
    \endcode
*/
#define BENCHCODE_REPORT_JSON(value)\
{\
    std::ostringstream BENCHMARK_INTERNAL_UNIQUE_NAME(output);\
    CppBenchmark::ReporterJSON BENCHMARK_INTERNAL_UNIQUE_NAME(reporter)(BENCHMARK_INTERNAL_UNIQUE_NAME(output));\
    CppBenchmark::Executor::Report(BENCHMARK_INTERNAL_UNIQUE_NAME(reporter));\
    value = BENCHMARK_INTERNAL_UNIQUE_NAME(output).str();\
}

#endif // CPPBENCHMARK_H


text:
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <link type="text/css" rel="stylesheet" href="style.css" />

<input type="checkbox" name="onOff" id="onOff" checked>Clustering

redpajama_set_name: RedPajamaGithub


text:
A repository to hold programs that rely heavily on classic data structures. Programs in this folder are mainly written to practice/demonstrate particular data structures.

- Spell checker (Hash table)
    - Reads in a dictionary and stores as a hash table. Can check for misspellings when given text.


text:
'use strict';

/**
 * @ngdoc directive
 * @name foodReportsApp.directive:foodSearch
 * @description
 * # foodSearch
 */
angular.module('foodReportsApp')
  .directive('foodReport', function($location) {
    return {
      templateUrl: 'scripts/directives/food-report/food-report.html',
      scope: {
        foodReport: '='
      },
      restrict: 'E',
      replace: true,
      link: function postLink(scope, element, attrs) {
        scope.gotToReport = function(item){
          $location.path('/report/'+item.ndbno);
        };

        scope.getMeasure = function(item, label){
          var value = 0;
          for(var i = 0, len =item.measures.length;i<len;i++){
            if(item.measures[i].label === label){
              return item.measures[i].value;
            }
          }
          return value;
        };

        scope.getEquivalent = function(label){
          var value = '--';
          for(var i = 0, len = scope.foodReport.food.nutrients[0].measures.length;i<len;i++){
            if(scope.foodReport.food.nutrients[0].measures[i].label === label){
              return scope.foodReport.food.nutrients[0].measures[i].eqv + ' g';
            }
          }
          return value;
        };

      }
    };
  });


text:
using System;
using Elasticsearch.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public interface IBulkOperation
	{
		string Operation { get; }
		Type ClrType { get; }

		[JsonProperty("_index")]
		IndexName Index { get; set; }

		[JsonProperty("_type")]
		TypeName Type { get; set; }

		[JsonProperty("_id")]
		Id Id { get; set; }

		[JsonProperty("_version")]
		long? Version { get; set; }

		[JsonProperty("_version_type")]
		[JsonConverter(typeof(StringEnumConverter))]
		VersionType? VersionType { get; set; }

		[JsonProperty("_routing")]
		string Routing { get; set; }

		[JsonProperty("_parent")]
		Id Parent { get; set; }

		[JsonProperty("_timestamp")]
		[Obsolete("This feature is no longer supported on indices created in Elasticsearch 5.0.0 and up")]
		long? Timestamp { get; set; }

		[JsonProperty("_ttl")]
		[Obsolete("This feature is no longer supported on indices created in Elasticsearch 5.0.0 and up")]
		Time Ttl { get; set; }

		[JsonProperty("_retry_on_conflict")]
		int? RetriesOnConflict { get; set; }

		object GetBody();

		Id GetIdForOperation(Inferrer inferrer);
	}
}


text:
{% extends "base.html" %}

{% set active_page = "index" %}

{% block title %}Underground Garage Underground{% endblock %}

{% block content %}

underground.AlexKerney.com

It's Alive, It's Alive  Podcast Feed

              This site provides a podcast of Little Steven's Underground Garage Radio Show.

              Some of us just prefer to listen on the go, but not always towards midnight when it's usually syndicated.

                Plus it is an experiment with a few technologies.

                  BeautifulSoup to scrape the radioshow page and extract the mp3s from JavaScript and Flash.

                  Celery task queues to manage the scraping and converting mp3 playlists to a single file.

                  Pydub to combine the mp3s into a single file.

                  Flask-Cloudy and Amazon S3 to store and host the combined show files.

                    Kubernetes and Google Container Engine to manage the Docker Containers that make up the infrastructure.

                    A nice feature of Kubernetes and Google Container Engine is the ability to autoscale.
                    It takes a few minutes for the Celery containers to process the task of combining the parts of a show into a single file.
                    In the process they use a large amount of RAM, max out a CPU, and spend some time uploading and downloading.

                    As Kubernetes detects the Celery containers are busy it can scale out to more containers, and Container Engine can scale out onto additional hosts.

            Files that are current avaliable have a headphone icon.

            Files that haven't been downloaded yet have an X instead. Click to trigger processing.

            Don't worry about your podcast player, most will trigger the server to start processing the file.

            The file will most likely be avaliable by the next time it retries to download it.

            Shows

                  Episode
                  Name
                  Description
                  File

              {% for show in Show.query.order_by(Show.episode.desc()).all() %}

                      {% if show.episode %}{{ show.episode }}{% endif %}
                      {% if show.name %}{{ show.name }}{% endif %}
                      {% if show.description %}{{ show.description }}{% else %}{{ show.url }}{% endif %}
                      {% if show.episode %}{% endif %}{% if show.file %}{% else %}{% endif %}{% if show.episode %}{% endif %}

              {% endfor %}

{% endblock %}


text:
@implementation NSString (MinFontSizeBinarySearch)

- (CGFloat)fittingFontSizeForFont:(UIFont *)font minFontSize:(CGFloat)minFontSize maxFontSize:(CGFloat)maxFontSize inSize:(CGSize)size {
    if (maxFontSize < minFontSize) {
        return 0;
    }

    //Find middle value
    NSInteger fontSize = (NSInteger) ((minFontSize + maxFontSize) / 2);

    //Create font
    UIFont *tempFont = [UIFont fontWithName:font.fontName size:fontSize];

    //Calculate dimentions
    CGSize dimension = [self sizeWithAttributes:@{NSFontAttributeName : tempFont}];

    if (dimension.height >= (size.height + 10) && dimension.width >= (size.width + 10) && dimension.height <= size.height && dimension.width <= size.width){
        return fontSize;
    }
    else if (dimension.height > size.height || dimension.width > size.width) {
        return [self fittingFontSizeForFont:font minFontSize:minFontSize maxFontSize:fontSize - 1 inSize:size];
    }
    else {
        return [self fittingFontSizeForFont:font minFontSize:fontSize + 1 maxFontSize:maxFontSize inSize:size];
    }
}

@end


text:
package com.cidic.design.dao;

import java.util.List;

import com.cidic.design.model.VideoCourse;

public interface VideoCourseDao {

	public void insertVideoCourse(VideoCourse videoCourse);

	public VideoCourse selectVideoCourse(int id);

	public void updateVideoCourse(VideoCourse videoCourse);

	public void deleteVideoCourse(VideoCourse videoCourse);

	public List<VideoCourse> getTopVideoCourse();

	public List<VideoCourse> getDataByPage(int limit, int offset, String sEcho);

	public List<VideoCourse> getFrontDataByPage(int limit, int offset, int choice);

	public int getCountData();
}


text:
Lista de Usuarios cadastrados

	<?php
		$this->table->set_heading('Nome','Empresa','Telefone','Celular','Email','Opção');
		foreach ($contato->result() as $linha)
		{
			$this->table->add_row($linha->nome, $linha->empresa, $linha->telefone, $linha->celular, $linha->email,anchor("principal/editar/$linha->id",'Editar').' -
				'.anchor("principal/excluir/$linha->id",'Deletar'));
		}
		echo '
';
		echo '
';
		echo $this->table->generate();

		/*PAGINAÇÃO
	 	$this->pagination->initialize($config);
		echo $this->pagination->create_links();
		*/

	?>


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Workspace.order'
        db.add_column('ddsc_site_workspace', 'order',
                      self.gf('django.db.models.fields.IntegerField')(default=0),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Workspace.order'
        db.delete_column('ddsc_site_workspace', 'order')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'ddsc_site.collage': {
            'Meta': {'object_name': 'Collage'},
            'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'visibility': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'})
        },
        'ddsc_site.collageitem': {
            'Meta': {'object_name': 'CollageItem'},
            'collage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ddsc_site.Collage']"}),
            'graph_index': ('django.db.models.fields.IntegerField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'timeseries': ('jsonfield.fields.JSONField', [], {'default': '[]', 'null': 'True', 'blank': 'True'})
        },
        'ddsc_site.proxyhostname': {
            'Meta': {'object_name': 'ProxyHostname'},
            'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
        },
        'ddsc_site.workspace': {
            'Meta': {'ordering': "(u'order',)", 'object_name': 'Workspace'},
            'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'lon_lat_zoom': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'visibility': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'})
        },
        'ddsc_site.workspaceitem': {
            'Meta': {'ordering': "(u'order',)", 'object_name': 'WorkspaceItem'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'visibility': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'wms_source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_wms.WMSSource']"}),
            'workspace': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ddsc_site.Workspace']"})
        },
        'lizard_maptree.category': {
            'Meta': {'ordering': "('index', 'name')", 'object_name': 'Category'},
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'index': ('django.db.models.fields.IntegerField', [], {'default': '1000'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_maptree.Category']", 'null': 'True', 'blank': 'True'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '20'})
        },
        'lizard_wms.wmsconnection': {
            'Meta': {'object_name': 'WMSConnection'},
            'category': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['lizard_maptree.Category']", 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'options': ('django.db.models.fields.TextField', [], {'default': 'u\'{"buffer": 0, "isBaseLayer": false, "opacity": 0.5}\''}),
            'params': ('django.db.models.fields.TextField', [], {'default': 'u\'{"height": "256", "width": "256", "styles": "", "format": "image/png", "tiled": "true", "transparent": "true"}\''}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
            'version': ('django.db.models.fields.CharField', [], {'default': "u'1.3.0'", 'max_length': '20'}),
            'xml': ('django.db.models.fields.TextField', [], {'default': "u''", 'blank': 'True'})
        },
        'lizard_wms.wmssource': {
            'Meta': {'ordering': "(u'index', u'display_name')", 'object_name': 'WMSSource'},
            '_params': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
            'bbox': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'category': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['lizard_maptree.Category']", 'null': 'True', 'blank': 'True'}),
            'connection': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lizard_wms.WMSConnection']", 'null': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'display_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'enable_search': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'index': ('django.db.models.fields.IntegerField', [], {'default': '1000'}),
            'layer_name': ('django.db.models.fields.TextField', [], {}),
            'legend_url': ('django.db.models.fields.CharField', [], {'max_length': '2048', 'null': 'True', 'blank': 'True'}),
            'metadata': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
            'options': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'show_legend': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200'})
        }
    }

    complete_apps = ['ddsc_site']


text:
layout: post
title: Integrating GoCD with GitHub
status: public
type: post
published: true
author: Go Team
---

With the upcoming 15.2 release we're announcing some new API endpoints that will make integrating with GoCD with GitHub easier and fun.

In this blog we will show you how you can integrate GoCD with GitHub using a few plugins for profit and fun.

# Login using the [GitHub OAuth Plugin](https://github.com/srinivasupadhya/gocd-oauth-login)

This plugin allows you to login, search and add existing github users to GoCD.

Login Page with GitHub icon

Search and Add User

---

# Build pull requests with [GitHub Pull Request Poller](https://github.com/ashwanthkumar/gocd-build-github-pull-requests) & [GitHub Status Notifier](https://github.com/srinivasupadhya/gocd-build-status-notifier)

The combination of these plugins will help you configure GoCD such that any pull-requests that are submitted will automatically be built, and their statuses updated on the pull request on GitHub.

GitHub PR page gets updated

GitHub PR listing page gets updated

---

# GitHub Issues Integration with [Custom Project Management Setup](http://www.go.cd/documentation/user/current/integration/go_integration.html#integration-with-bug-tracking-and-story-management-tools)

Any commit messages that contain references to issues or pull requests using the popular means to mention issue (#42) can is something that Go already understands.

To configure this, edit the pipeline material and setup a pattern and a link under "Project Management" tab.

GitHub Issue Tracker Integration

Any commit messages with issue numbers will be linked to the correct GitHub issues:

Comment with GitHub issue link (build cause pop-up)

You can also compare pipelines and get the release notes or changelog straight out of Go.

Comment with GitHub issue link (compare pipeline page)

---

If you think Go CD can provide more integrations to GitHub or provide similar integrations with other tools/services please do leave a comment or ask on the [mailing list](https://groups.google.com/forum/#!forum/go-cd).

---


text:
> random comments in a blockquote because I don't know how to be creative when I'm writing fixtures.

<%= _.toc("fixtures/[a-b].md") %>

## A 1

A content.

## A 2

B content.

### A 3

C content.

### A 4


text:
#define	TARGET_PAGE_SIZE	4096
#define	SEGMENT_SIZE	TARGET_PAGE_SIZE
#define TEXT_START_ADDR 0

/* Do not "beautify" the CONCAT* macro args.  Traditional C will not
   remove whitespace added here, and thus will fail to concatenate
   the tokens.  */
#define MY(OP) CONCAT2 (newsos3_,OP)
#define TARGETNAME "a.out-newsos3"
#define ENTRY_CAN_BE_ZERO
#define DEFAULT_ARCH bfd_arch_m68k
#define TARGET_IS_BIG_ENDIAN_P
#define N_HEADER_IN_TEXT(x) 0

#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "aout/aout64.h"
#include "aout/stab_gnu.h"
#include "aout/ar.h"
#include "libaout.h"           /* BFD a.out internal data structures */

#include "aout-target.h"


text:
FOUNDATION_EXPORT double MaterialLoaderVersionNumber;

//! Project version string for MaterialLoader.
FOUNDATION_EXPORT const unsigned char MaterialLoaderVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <MaterialLoader/PublicHeader.h>


text:
package org.infinispan.interceptors.distribution;

import org.infinispan.CacheException;
import org.infinispan.commands.FlagAffectedCommand;
import org.infinispan.commands.read.GetCacheEntryCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
import org.infinispan.factories.annotations.Start;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;

import java.util.List;
import java.util.Map;

/**
 * Handles the distribution of the non-transactional caches.
 *
 * @author Mircea Markus
 * @since 5.2
 */
public class NonTxDistributionInterceptor extends BaseDistributionInterceptor {

   private static Log log = LogFactory.getLog(NonTxDistributionInterceptor.class);
   private static final boolean trace = log.isTraceEnabled();

   private boolean useLockForwarding;

   @Start
   public void start() {
      useLockForwarding = cacheConfiguration.locking().supportsConcurrentUpdates();
   }

   @Override
   public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
      try {
         Object returnValue = invokeNextInterceptor(ctx, command);
         if (returnValue == null) {
            Object key = command.getKey();
            if (needsRemoteGet(ctx, command)) {
               returnValue = remoteGet(ctx, key, command);
            }
            if (returnValue == null) {
               returnValue = localGet(ctx, key, false, command);
            }
         }
         return returnValue;
      } catch (SuspectException e) {
         // retry
         return visitGetKeyValueCommand(ctx, command);
      }
   }

   @Override
   public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
      SingleKeyRecipientGenerator skrg = new SingleKeyRecipientGenerator(command.getKey());
      return handleWriteCommand(ctx, command, skrg, command.hasFlag(Flag.PUT_FOR_STATE_TRANSFER), false, false);
   }

   /**
    * Don't forward in the case of clear commands, just acquire local locks and broadcast.
    */
   @Override
   public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
      if (ctx.isOriginLocal() && !isLocalModeForced(command)) {
         rpcManager.broadcastRpcCommand(command, isSynchronous(command), false);
      }
      return invokeNextInterceptor(ctx, command);
   }

   protected Object handleWriteCommand(InvocationContext ctx, WriteCommand command, RecipientGenerator recipientGenerator, boolean skipRemoteGet, boolean skipL1Invalidation, boolean remove) throws Throwable {
      // see if we need to load values from remote sources first
      remoteGetBeforeWrite(ctx, command, recipientGenerator);

      // if this is local mode then skip distributing
      if (isLocalModeForced(command)) {
         return invokeNextInterceptor(ctx, command);
      }

      if (!ctx.isOriginLocal()) {
         Object returnValue = invokeNextInterceptor(ctx, command);
         handleRemoteWrite(ctx, command, recipientGenerator, skipL1Invalidation, isSynchronous(command));
         return returnValue;
      } else {
         return handleLocalWrite(ctx, command, recipientGenerator, skipL1Invalidation, isSynchronous(command));
      }
   }

   private void remoteGetBeforeWrite(InvocationContext ctx, WriteCommand command, KeyGenerator keygen) throws Throwable {
      // this should only happen if:
      //   a) unsafeUnreliableReturnValues is false
      //   b) unsafeUnreliableReturnValues is true, the command is conditional
      if (isNeedReliableReturnValues(command) || command.isConditional()) {
         for (Object k : keygen.getKeys()) {
            Object returnValue = remoteGetBeforeWrite(ctx, k, command);
            if (returnValue == null && (!useLockForwarding || cdl.localNodeIsPrimaryOwner(k))) {
               // We either did not go remotely (because the value should be local now) or we did but the remote value is null.
               // Then it makes sense to try a local get and wrap again. This will compensate the fact the the entry was not local
               // earlier when the EntryWrappingInterceptor executed during current invocation context but it should be now.
               localGet(ctx, k, true, command);
            }
         }
      }
   }

   private Object remoteGetBeforeWrite(InvocationContext ctx, Object key, FlagAffectedCommand command) throws Throwable {
      // During state transfer it is possible for an entry to map to the local node, but not have been brought locally yet
      // (not present in data container yet). In that case we fetch the value remotely first. If the value exists remotely (non-null)
      // then we use it. Otherwise if remote value is null it's possible that the state transfer finished in between
      // the "isAffectedByRehash" and "retrieveFromRemoteSource" so the caller can hope to find the value in the local data container.
      if (dm.isAffectedByRehash(key) && !dataContainer.containsKey(key, null)) {
         if (trace) log.tracef("Doing a remote get for key %s", key);

         // attempt a remote lookup
         InternalCacheEntry ice = retrieveFromRemoteSource(key, ctx, false, command);
         if (ice != null) {
            if (!ctx.replaceValue(key, ice)) {
               entryFactory.wrapEntryForPut(ctx, key, ice, false, command);
            }
            return ice.getValue();
         }
      } else {
         if (trace) log.tracef("Not doing a remote get for key %s since entry is not affected by rehash or is already in data container. We are %s, owners are %s", key, rpcManager.getAddress(), dm.locate(key));
      }
      return null;
   }

   private Object localGet(InvocationContext ctx, Object key, boolean isWrite, FlagAffectedCommand command) throws Throwable {
      InternalCacheEntry ice = dataContainer.get(key, null);
      if (ice != null) {
         if (!ctx.replaceValue(key, ice))  {
            if (isWrite)
               entryFactory.wrapEntryForPut(ctx, key, ice, false, command);
            else
               ctx.putLookedUpEntry(key, ice);
         }
         return command instanceof GetCacheEntryCommand ? ice : ice.getValue();
      }
      return null;
   }

   protected Object handleLocalWrite(InvocationContext ctx, WriteCommand command, RecipientGenerator rg, boolean skipL1Invalidation, boolean sync) throws Throwable {
      Object returnValue = invokeNextInterceptor(ctx, command);
      if (!isSingleOwnerAndLocal(rg)) {
         List<Address> recipients = rg.generateRecipients();
         if (!command.isSuccessful() && recipients.contains(rpcManager.getAddress())) {
            log.tracef("Skipping remote invocation as the command hasn't executed correctly on owner %s", rpcManager.getAddress());
         } else {
            Map<Address, Response> responseMap = rpcManager.invokeRemotely(recipients, command, sync, false);
            if (sync && !recipients.isEmpty()) {
               Address primaryOwner = recipients.get(0);
               if (!primaryOwner.equals(rpcManager.getAddress())) {
                  returnValue = getResponseFromPrimaryOwner(primaryOwner, responseMap);
               }
            }
         }
      }
      return returnValue;
   }

   protected void handleRemoteWrite(InvocationContext ctx, WriteCommand command, RecipientGenerator recipientGenerator, boolean skipL1Invalidation, boolean sync) throws Throwable {}

   private Object remoteGet(InvocationContext ctx, Object key, GetKeyValueCommand command) throws Throwable {
      if (trace) log.tracef("Doing a remote get for key %s", key);
      InternalCacheEntry ice = retrieveFromRemoteSource(key, ctx, false, command);
      command.setRemotelyFetchedValue(ice);
      if (ice != null) {
         return ice.getValue();
      }
      return null;
   }

   protected Object getResponseFromPrimaryOwner(Address primaryOwner, Map<Address, Response> addressResponseMap) {
      Response fromPrimaryOwner = addressResponseMap.get(primaryOwner);
      if (fromPrimaryOwner == null) {
         log.tracef("Primary owner %s returned null", primaryOwner);
         return null;
      }
      if (!fromPrimaryOwner.isSuccessful()) {
         Throwable cause = fromPrimaryOwner instanceof ExceptionResponse ? ((ExceptionResponse)fromPrimaryOwner).getException() : null;
         throw new CacheException("Got unsuccessful response from primary owner: " + fromPrimaryOwner, cause);
      } else {
         return ((SuccessfulResponse) fromPrimaryOwner).getResponseValue();
      }
   }
}


text:
package com.example.authsample;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import android.accounts.AccountManager;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.cloud.backend.android.CloudBackendActivity;
import com.google.cloud.backend.android.CloudBackendMessaging;
import com.google.cloud.backend.android.CloudCallbackHandler;
import com.google.cloud.backend.android.CloudEntity;
import com.google.cloud.backend.android.Consts;
import com.google.cloud.backend.android.CloudQuery.Order;
import com.google.cloud.backend.android.CloudQuery.Scope;

/**
 * Sample Guestbook app with Mobile Backend Starter.
 *
 */
public class MainActivity extends CloudBackendActivity {

    private static final int REQUEST_ACCOUNT_PICKER = 2;

    private static final String PREF_KEY_ACCOUNT_NAME = "PREF_KEY_ACCOUNT_NAME";

    private static final String BROADCAST_PROP_DURATION = "duration";
    private static final String BROADCAST_PROP_MESSAGE = "message";

    private GoogleAccountCredential credential;

    // UI components
    private EditText mEditText;
    private View mSendBtn;

    // a list of posts on the UI
    List<CloudEntity> posts = new LinkedList<CloudEntity>();

    // initialize UI
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CloudBackendMessaging cloudBackend = getCloudBackend();

        // create credential
        credential = GoogleAccountCredential.usingAudience(this, Consts.AUTH_AUDIENCE);
        cloudBackend.setCredential(credential);

        // get account name from the shared pref
        String accountName = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_KEY_ACCOUNT_NAME, null);
        if (accountName == null) {
            // let user pick an account
            startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
            return; // continue init in onActivityResult
        } else {
            credential.setSelectedAccountName(accountName);
        }

        mEditText = (EditText) findViewById(R.id.edit_text);
        mSendBtn = findViewById(R.id.send_btn);
    }

    /**
     * Returns account name selected by user, or null if any account is
     * selected.
     */
    protected String getAccountName() {
        return credential == null ? null : credential.getSelectedAccountName();
    }

    @Override
    protected void onDestroy() {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        gcm.close();
        super.onDestroy();
    }

    @Override
    protected void onPostCreate() {
        super.onPostCreate();
        listAllPosts();
    }

    /**
     * Handles callback from Intents like authorization request or account
     * picking.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_ACCOUNT_PICKER:
                if (data != null && data.getExtras() != null) {
                    // set the picked account name to the credential
                    String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    credential.setSelectedAccountName(accountName);

                    // save account name to shared pref
                    SharedPreferences.Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
                    e.putString(PREF_KEY_ACCOUNT_NAME, accountName);
                    e.commit();
                }

                // post create initialization
                onPostCreate();
                break;
        }
    }

    // execute query "SELECT * FROM Guestbook ORDER BY _createdAt DESC LIMIT 50"
    // this query will be re-executed when matching entity is updated
    private void listAllPosts() {

        // create a response handler that will receive the query result or an
        // error
        CloudCallbackHandler<List<CloudEntity>> handler = new CloudCallbackHandler<List<CloudEntity>>() {
            @Override
            public void onComplete(List<CloudEntity> results) {
                posts = results;
                updateGuestbookUI();
            }

            @Override
            public void onError(IOException exception) {
                handleEndpointException(exception);
            }
        };

        // execute the query with the handler
        getCloudBackend().listByKind("Guestbook", CloudEntity.PROP_CREATED_AT, Order.DESC, 50, Scope.FUTURE_AND_PAST,
                handler);
    }

    private void handleEndpointException(IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        mSendBtn.setEnabled(true);
    }

    // convert posts into string and update UI
    private void updateGuestbookUI() {
        FragmentManager manager = getFragmentManager();
        PostListFragment f = (PostListFragment) manager.findFragmentById(R.id.fragment_list);
        f.setEntities(posts);
    }

    // post a new message to server
    public void onSendButtonPressed(View view) {

        // create a CloudEntity with the new post
        CloudEntity newPost = new CloudEntity("Guestbook");
        newPost.put("message", mEditText.getText().toString());

        // create a response handler that will receive the result or an error
        CloudCallbackHandler<CloudEntity> handler = new CloudCallbackHandler<CloudEntity>() {
            @Override
            public void onComplete(final CloudEntity result) {
                posts.add(0, result);
                updateGuestbookUI();
                mEditText.setText("");
                mSendBtn.setEnabled(true);
            }

            @Override
            public void onError(final IOException exception) {
                handleEndpointException(exception);
            }
        };

        // execute the insertion with the handler
        getCloudBackend().insert(newPost, handler);
        mSendBtn.setEnabled(false);
    }

    // handles broadcast message and show a toast
    @Override
    public void onBroadcastMessageReceived(List<CloudEntity> l) {
        for (CloudEntity e : l) {
            String message = (String) e.get(BROADCAST_PROP_MESSAGE);
            int duration = Integer.parseInt((String) e.get(BROADCAST_PROP_DURATION));
            Toast.makeText(this, message, duration).show();
        }
    }
}


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.ins.auto.autoinsprod.policy.cancel response.
 *
 * @author auto create
 * @since 1.0, 2017-12-13 11:31:43
 */
public class AlipayInsAutoAutoinsprodPolicyCancelResponse extends AlipayResponse {

	private static final long serialVersionUID = 4473892137224846535L;

	/**
	 * 操作结果 true/false
	 */
	@ApiField("cancel_result")
	private String cancelResult;

	public void setCancelResult(String cancelResult) {
		this.cancelResult = cancelResult;
	}
	public String getCancelResult( ) {
		return this.cancelResult;
	}

}


text:
/**
 */
package isistan.edu.carcha.model.carcha;

import org.eclipse.emf.ecore.EFactory;

/**
 *
 * The Factory for the model.
 * It provides a create method for each non-abstract class of the model.
 *
 * @see isistan.edu.carcha.model.carcha.CarchaPackage
 * @generated
 */
public interface CarchaFactory extends EFactory {
	/**
	 * The singleton instance of the factory.
	 *
	 *
	 * @generated
	 */
	CarchaFactory eINSTANCE = isistan.edu.carcha.model.carcha.impl.CarchaFactoryImpl.init();

	/**
	 * Returns a new object of class 'Project'.
	 *
	 *
	 * @return a new object of class 'Project'.
	 * @generated
	 */
	CarchaProject createCarchaProject();

	/**
	 * Returns a new object of class 'Crosscutting Concern'.
	 *
	 *
	 * @return a new object of class 'Crosscutting Concern'.
	 * @generated
	 */
	CrosscuttingConcern createCrosscuttingConcern();

	/**
	 * Returns a new object of class 'Design Decision'.
	 *
	 *
	 * @return a new object of class 'Design Decision'.
	 * @generated
	 */
	DesignDecision createDesignDecision();

	/**
	 * Returns a new object of class 'Traceability Link'.
	 *
	 *
	 * @return a new object of class 'Traceability Link'.
	 * @generated
	 */
	TraceabilityLink createTraceabilityLink();

	/**
	 * Returns the package supported by this factory.
	 *
	 *
	 * @return the package supported by this factory.
	 * @generated
	 */
	CarchaPackage getCarchaPackage();

} //CarchaFactory


text:
package com.google.common.io;

import static com.google.common.io.SourceSinkFactory.ByteSinkFactory;
import static com.google.common.io.SourceSinkFactory.CharSinkFactory;
import static org.junit.Assert.assertArrayEquals;

import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;

import junit.framework.TestSuite;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * A generator of {@code TestSuite} instances for testing {@code ByteSink} implementations.
 * Generates tests of a all methods on a {@code ByteSink} given various inputs written to it as well
 * as sub-suites for testing the {@code CharSink} view in the same way.
 *
 * @author Colin Decker
 */
public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkFactory> {

  private static final ImmutableList<Method> testMethods
      = getTestMethods(ByteSinkTester.class);

  static TestSuite tests(String name, ByteSinkFactory factory) {
    TestSuite suite = new TestSuite(name);
    for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) {
      String desc = entry.getKey();
      TestSuite stringSuite = suiteForString(name, factory, entry.getValue(), desc);
      suite.addTest(stringSuite);
    }
    return suite;
  }

  private static TestSuite suiteForString(String name, ByteSinkFactory factory,
      String string, String desc) {
    byte[] bytes = string.getBytes(Charsets.UTF_8);
    TestSuite suite = suiteForBytes(name, factory, desc, bytes);
    CharSinkFactory charSinkFactory = SourceSinkFactories.asCharSinkFactory(factory);
    suite.addTest(CharSinkTester.suiteForString(name + ".asCharSink[Charset]", charSinkFactory,
        string, desc));
    return suite;
  }

  private static TestSuite suiteForBytes(String name, ByteSinkFactory factory,
      String desc, byte[] bytes) {
    TestSuite suite = new TestSuite(name + " [" + desc + "]");
    for (final Method method : testMethods) {
      suite.addTest(new ByteSinkTester(factory, bytes, name, desc, method));
    }
    return suite;
  }

  private ByteSink sink;

  ByteSinkTester(ByteSinkFactory factory, byte[] data, String suiteName,
      String caseDesc, Method method) {
    super(factory, data, suiteName, caseDesc, method);
  }

  @Override
  protected void setUp() throws Exception {
    sink = factory.createSink();
  }

  public void testOpenStream() throws IOException {
    OutputStream out = sink.openStream();
    try {
      ByteStreams.copy(new ByteArrayInputStream(data), out);
    } finally {
      out.close();
    }

    assertContainsExpectedBytes();
  }

  public void testOpenBufferedStream() throws IOException {
    OutputStream out = sink.openBufferedStream();
    try {
      ByteStreams.copy(new ByteArrayInputStream(data), out);
    } finally {
      out.close();
    }

    assertContainsExpectedBytes();
  }

  public void testWrite() throws IOException {
    sink.write(data);

    assertContainsExpectedBytes();
  }

  public void testWriteFrom_inputStream() throws IOException {
    sink.writeFrom(new ByteArrayInputStream(data));

    assertContainsExpectedBytes();
  }

  private void assertContainsExpectedBytes() throws IOException {
    assertArrayEquals(expected, factory.getSinkContents());
  }
}


text:
<?php namespace AssetCompressor\Drivers\MinifyJS;

/**
 * Class JSCompress
 *
 * JS minifier and compressor based on the Google Closure API
 *
 * @package Minify
 * @author JonoB
 */
class JSCompress {

	private $_srcs = array();
	private $_mode = "SIMPLE_OPTIMIZATIONS";
	private $_warning_level = "DEFAULT";
	private $_compress = true;
	private $_pretty_print = false;
	private $_debug = false;
	private $_cache_dir = "";
	private $_code_url_prefix = "";

	private $_start_time = '';

	private $_out = array();

  	public function __construct()
  	{
  		$this->_start_time = microtime(true);
  		return $this;
  	}

	/**
	* Adds a source file to the list of files to compile.  Files will be
	* concatenated in the order they are added.
	*/
	public function add($file)
	{
		$this->_srcs[] = $file;
		return $this;
	}

	/**
	* Sets the URL prefix to use with the Closure Compiler service's code_url
	* parameter.
	*
	* By default PHP-Closure posts the scripts to the compiler service, however,
	* this is subject to a 200000-byte size limit for the whole post request.
	*
	* Using code_url tells the compiler service the URLs of the scripts to
	* fetch.  The file paths added in add() must therefore be relative to this
	* URL.
	*
	*  ->useCodeUrl('http://www.example.com/app/')
	*
	*/
	public function use_code_url($code_url_prefix)
	{
		$this->_code_url_prefix = $code_url_prefix;
		return $this;
	}

	/**
	* Pretty print the output.
	*/
	public function pretty_print($print = true)
	{
		$this->_pretty_print = $print;
		return $this;
	}

	/**
	* Turns on the debug info.
	*/
	public function debug($debug = true)
	{
		$this->_debug = $debug;
		return $this;
	}

	/**
	 * Sets the compilation mode
	 * @param string $mode
	 * @return class
	 */
	public function mode($mode)
	{
		$this->_mode = $mode;
	}

	/**
	* Sets the compilation mode to optimize whitespace only.
	*/
	public function whitespace_only()
	{
		$this->mode('WHITESPACE_ONLY');
		return $this;
	}

	/**
	* Sets the compilation mode to simple optimizations.
	*/
	public function simple_mode()
	{
		$this->mode('SIMPLE_OPTIMIZATIONS');
		return $this;
	}

	/**
	* Sets the compilation mode to advanced optimizations.
	*/
	public function advanced_mode()
	{
		$this->mode('ADVANCED_OPTIMIZATIONS');
		return $this;
	}

	public function set_warning($level)
	{
		$this->_warning_level = $level;
		return $this;
	}

	/**
	* Sets the warning level to QUIET.
	*/
	public function quiet_warnings()
	{
		$this->set_warning('QUIET');
		return $this;
	}

	/**
	* Sets the default warning level.
	*/
	public function default_warnings()
	{
		$this->set_warning('DEFAULT');
		return $this;
	}

	/**
	* Sets the warning level to VERBOSE.
	*/
	public function verbose_warnings()
	{
		$this->set_warning('VERBOSE');
		return $this;
	}

	public function compress()
	{
		// get the result from the closure compiler
		$closure = json_decode($this->make_request());

    	$result = '';

    	if ($this->_debug) {
	      	$result = "if(window.console&&window.console.log){\r\n";
	      	$result .= "window.console.log('Closure Compiler Stats:\\n";
	        $result .= "-----------------------\\n";
	        $result .= "Original Size: " . (isset($closure->statistics->originalSize)) ? $closure->statistics->originalSize : '' . "\\n";
	        $result .= "Original Gzip Size: " . (isset($closure->statistics->originalGzipSize)) ? $closure->statistics->originalGzipSize : '' . "\\n";
	        $result .= "Compressed Size: " . (isset($closure->statistics->compressedSize)) ? $closure->statistics->compressedSize : '' . "\\n";
	        $result .= "Compressed Gzip Size: " . (isset($closure->statistics->compressedGzipSize)) ? $closure->statistics->compressedGzipSize : '' . "\\n";
	        $result .= "Compile Time: " . (isset($closure->statistics->compileTime)) ? $closure->statistics->compileTime : '' . "\\n";
	       	$result .= "Generated: " . Date("Y/m/d H:i:s T") . "');\r\n";

	      	if (isset($closure->errors)) {
	      		$result .= $this->print_warnings($closure->errors, 'error');
	      	}
	      	if (isset($closure->warnings)) {
	      		$result .= $this->print_warnings($closure->warnings, 'warn');
	      	}

	      	$result .= "}\r\n\r\n";
	    }

	    $result .= $closure->compiledCode . "\r\n";

	    return $result;
	}

	private function print_warnings($warnings, $level = 'log')
	{
		$result = '';
		foreach ($warnings as $warning) {
			$desc = addslashes($warning["value"]);
			$type = $warning["attributes"]["type"];
			$lineno = $warning["attributes"]["lineno"];
			$charno = $warning["attributes"]["charno"];
			$line = addslashes($warning["attributes"]["line"]);
			$result .= "window.console.$level('$type: $desc\\nLine: $lineno\\nChar: $charno\\nLine: $line');\r\n";
		}
		return $result;
	}

	function make_request()
	{
		$data = $this->get_params();
		$referer = @$_SERVER["HTTP_REFERER"] or "";

		$fp = fsockopen("closure-compiler.appspot.com", 80) or die("Unable to open socket");;

		if ($fp) {
			fputs($fp, "POST /compile HTTP/1.1\r\n");
			fputs($fp, "Host: closure-compiler.appspot.com\r\n");
			fputs($fp, "Referer: $referer\r\n");
			fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
			fputs($fp, "Content-length: ". strlen($data) ."\r\n");
			fputs($fp, "Connection: close\r\n\r\n");
			fputs($fp, $data);

			$result = "";
			while ( ! feof($fp)) {
				$result .= fgets($fp, 128);
			}

			fclose($fp);
		}

		$data = substr($result, (strpos($result, "\r\n\r\n")+4));
		if (strpos(strtolower($result), "transfer-encoding: chunked") !== FALSE) {
			$data = $this->unchunk($data);
		}

		return $data;
	}

	private function unchunk($data)
	{
		$fp = 0;
		$outData = "";
		while ($fp < strlen($data)) {
			$rawnum = substr($data, $fp, strpos(substr($data, $fp), "\r\n") + 2);
			$num = hexdec(trim($rawnum));
			$fp += strlen($rawnum);
			$chunk = substr($data, $fp, $num);
			$outData .= $chunk;
			$fp += strlen($chunk);
		}
		return $outData;
	}

	private function get_params()
	{
		$params = array();
		foreach ($this->get_param_list() as $key => $value) {
	  		$params[] = preg_replace("/_[0-9]$/", "", $key) . "=" . urlencode($value);
		}
		return implode("&", $params);
	}

	private function get_param_list()
	{
		$params = array();
		if ($this->_code_url_prefix) {
			// Send the URL to each source file instead of the raw source.
			$i = 0;
			foreach($this->_srcs as $file) {
				$params["code_url_$i"] = $this->_code_url_prefix . $file;
				$i++;
			}
		}
		else {
			$params["js_code"] = $this->read_sources();
		}

		$params['compilation_level'] = $this->_mode;
		$params['output_format'] = 'json';
		$params['warning_level'] = $this->_warning_level;
		$params['output_info_1'] = 'compiled_code';
		$params['output_info_2'] = 'statistics';
		$params['output_info_3'] = 'warnings';
		$params['output_info_4'] = 'errors';

		if ($this->_pretty_print) {
			$params["formatting"] = "pretty_print";
		}

		if ($this->_compress) {
			$params["use_closure_library"] = "true";
		}

		return $params;
	}

	private function read_sources()
	{
		$code = '';
		foreach ($this->_srcs as $src) {
	  		$code .= file_get_contents($src) . "\n\n";
		}
		return $code;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NUnit.Framework;
using ZendeskApi_v2.Models.Requests;

namespace Tests.Models.Requests
{
    [TestFixture]
    public class RequestTests
    {
        private const string BodyJsonFormat = "{{\"request\":{0}}}";
        private const string RequestJsonFormat = "{{\"url\":\"{0}\",\"id\":{1},\"status\":\"{2}\",\"priority\":null,\"type\":null,\"subject\":\"{3}\",\"description\":\"{4}\",\"organization_id\":{5},\"via\":{6},\"custom_fields\":{7},\"requester_id\":{8},\"collaborator_ids\":[],\"due_at\":null,\"can_be_solved_by_me\":{9},\"created_at\":\"2015-11-09T19:38:40Z\",\"updated_at\":\"2015-11-11T20:02:27Z\",\"assignee_id\":5,\"ticket_form_id\":6,\"fields\":[{{\"id\":2,\"value\":\"custom_1\"}}]}}";
        private const string ToJson = "{}";
        private const string FromJson = "{}";
        private const string SourceJsonFormat = "{{\"from\":{0},\"to\":{1},\"rel\":null}}";
        private const string ViaJsonFormat = "{{\"channel\":\"api\",\"source\":{0}}}";
        private const string CustomFieldsJsonFormat = "[{{\"id\":{0},\"value\":\"{1}\"}}]";
        private const long Id = 1;
        private const string UrlFormat = "https://example.zendesk.com/api/v2/requests/{0}.json";
        private const string OpenStatus = "open";
        private const string SolvedStatus = "solved";
        private const string Subject = "Example Subject";
        private const string Description = "Example Description";
        private const long OrganizationId = 2005;
        private const long FieldId = 1;
        private const string FieldValue = "custom_field_value";
        private const int RequesterId = 10000;
        private const bool OpenCanBeSolvedByMe = true;
        private const bool SolvedCanBeSolvedByMe = false;

        private static readonly string Url = string.Format(UrlFormat, Id);
        private static readonly string SourceJson = string.Format(SourceJsonFormat, FromJson, ToJson);
        private static readonly string ViaJson = string.Format(ViaJsonFormat, SourceJson);
        private static readonly string CustomFieldsJson = string.Format(CustomFieldsJsonFormat, FieldId, FieldValue);

        private static readonly string OpenRequestJson = string.Format(RequestJsonFormat, Url, Id, OpenStatus, Subject, Description, OrganizationId, ViaJson, CustomFieldsJson, RequesterId, OpenCanBeSolvedByMe.ToString().ToLower());
        private static readonly string SolvedRequestJson = string.Format(RequestJsonFormat, Url, Id, SolvedStatus, Subject, Description, OrganizationId, ViaJson, CustomFieldsJson, RequesterId, SolvedCanBeSolvedByMe.ToString().ToLower());

        [Test]
        public void TestDeserialize()
        {
            var openRequest = JsonConvert.DeserializeObject<Request>(OpenRequestJson);

            Assert.NotNull(openRequest);
            Assert.AreEqual(Url, openRequest.Url);
            Assert.AreEqual(Id, openRequest.Id);
            Assert.AreEqual(OpenStatus, openRequest.Status);
            Assert.AreEqual(Subject, openRequest.Subject);
            Assert.AreEqual(Description, openRequest.Description);
            Assert.AreEqual(RequesterId, openRequest.RequesterId);
            Assert.AreEqual(OpenCanBeSolvedByMe, openRequest.CanBeSolvedByMe);

            var solvedRequest = JsonConvert.DeserializeObject<Request>(SolvedRequestJson);

            Assert.NotNull(solvedRequest);
            Assert.AreEqual(SolvedStatus, solvedRequest.Status);
            Assert.AreEqual(SolvedCanBeSolvedByMe, solvedRequest.CanBeSolvedByMe);
        }
    }
}


text:
package com.xht.android.serverhelp.ceche;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;
import com.xht.android.serverhelp.util.LogHelper;

/**
 * Created by Administrator on 2016/11/17.
 */

public class BitmapCache implements ImageLoader.ImageCache {
    private LruCache<String, Bitmap> mCache;

    public BitmapCache() {
        int maxSize = 4 * 1024 * 1024;
        mCache = new LruCache<String, Bitmap>(maxSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        LogHelper.i("leslie", "get cache " + url);
        return mCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        LogHelper.i("leslie", "add cache " + url);
        if (bitmap != null) {
            mCache.put(url, bitmap);
        }
    }
}


text:
import java.util.*;

public class Main {
  private Map<Integer, List<String>> test(String... list) {
    Map<Integer, List<String>> map = new HashMap<>();
    for(String s : li<caret>st) {
      if(s != null) {
        map.computeIfAbsent(s.length(), k -> new LinkedList<>()).add(s.trim());
      }
    }
    return map;
  }

  public static void main(String[] args) {
    System.out.println(new Main().test("a", "bbb", null, "cc", "dd", "eedasfasdfs", "dd"));
  }
}


text:
<form novalidate name="contentForm"
      ng-controller="UmbracoForms.Editors.Form.EntriesController as vm"
      ng-show="loaded && (security.userSecurity.manageForms && hasAccessToCurrentForm)"
      ng-submit="save()">
    <umb-panel>
        <umb-header>

{{form.name}} form entries

        </umb-header>

                        <button class="btn pull-right" ng-click="edit(records.schema)" ng-if="records.totalNumberOfResults > 0">
                            Export
                        </button>

                        <input
                            type="text"
                            placeholder="Filter entries..."
                            ng-model="filter.filter"
                            ng-change="filterChanged()"
                            prevent-enter-submit
                            no-dirty-check
                            class="pull-left">

                                <input type="checkbox"
                                    name="selectedrecordStates[]"
                                    value="{{recordState}}"
                                    ng-model="recordState.isChecked"
                                    ng-change="vm.toggleRecordState(recordState)">
                                    {{recordState.name}}

                            No submissions added yet in this date range

We couldn't find any submissions, are you sure you published the form? Or try expanding the date range

                            We couldn't find any submissions matching your search

Try searching for something else, maybe you're lucky next time

 0">
                        {{selectedRows.length}} entries selected

                            Loading Results

 0 && !loading">

                                        <input type="checkbox"
                                            ng-click="toggleAllLegacy($event)"
                                            ng-checked="allIsChecked">

                                    {{field.name}}

                                        <input type="checkbox" ng-model="row.selected" ng-change="toggleRowLegacy(row)">

                                                    {{ field |  fileName }}

                                                        {{ field.Name }}

                                                        {{field.Email}}

                                                    {{ field | momentDateTimeZone : 'LLL' }}

                                                    {{ field | truncate:20:true }}

 1">

                                                <li ng-class="{disabled:filter.startIndex <= 1}">

                                                        <localize key="general_previous">Previous</localize>

                                                    {{$index+1}}

= records.totalNumberOfPages}">

                                                        <localize key="general_next">Next</localize>

    </umb-panel>
</form>


text:
class GameSkeleton
  attr_reader :new_game

  def initialize(name="default", user_ids, number_of_rounds)
    @new_game = Game.create(name: name)
    @game_users = user_ids.map { |user_id| user = User.find_by_id(user_id) }
    populate_seats
    deal_cards_to_seats
    make_rounds(number_of_rounds)
    return @new_game.id
  end

  private

  def populate_seats
    @game_users.each do |user|
      user.seats << Seat.create(game_id: @new_game.id)
      user.save
    end
  end

  def deal_cards_to_seats()
    @new_game.seats.each do |seat|
      10.times do
        PlayableCard.create(seat_id: seat.id, whitecard_id: Helper.random_whitecard.id)
      end
    end
  end

  def make_rounds(number_of_rounds)
    user_array = @new_game.seats.to_a
    for round_num in (1..number_of_rounds)
      new_round = Round.create( game_id: @new_game.id,
        leader_id: user_array.first.id,
        blackcard_id: Helper.random_blackcard.id,
        round_num: round_num)
      @new_game.rounds << new_round
      @new_game.save
      user_array.rotate!
    end
  end
end


text:
package com.samsarin.gatu.op;

import com.samsarin.gatu.primitive.Candidate;

/**
 * An operation that determines when the engine should finish.
 *
 * @author chris@samsarin.com
 */
public interface TerminationOp {

    /**
     * Returns {@code true} if the engine should terminate. Otherwise the
     * engine will continue with the next generation.
     *
     * @param generationNum the current generation, starting with 0
     * @param bestCandidate the best candidate from this generation
     * @return {@code true} if the engine should terminate
     */
    boolean shouldTerminate(int generationNum, Candidate bestCandidate);
}


text:
package de.tourenplaner.computecore;

import de.tourenplaner.computeserver.Responder;

/**
 * This class is used to represent a request for computation
 *
 * @author Christoph Haag, Sascha Meusel, Niklas Schnelle, Peter Vollmer
 */
public class ComputeRequest {

	private final Responder responder;
    private final RequestData requestData;
    private FormattedStreamWriter resultObject;
	/**
	 * Constructs a new ComputeRequest using the given Responder
	 *
     * @param responder The to this compute request corresponding Responder
     */
	public ComputeRequest(Responder responder, RequestData requestData) {
		this.responder = responder;
        this.requestData = requestData;
	}

    /**
     * Gets the RequestData object holding the data of this compute Request
     */
    public RequestData getRequestData(){
        return requestData;
    }

	/**
	 * Gets the responder object which is used to send the result to the correct
	 * client connection
	 *
	 * @return Returns the Responder object
	 */
	public Responder getResponder() {
		return responder;
	}

    /**
     * Sets the object storing the result of this computation
     *
     * @param ro the object which will hold the result
     */
    public void setResultObject(FormattedStreamWriter ro){
        this.resultObject = ro;
    }

    /**
     * Gets the StreamJsonWriter object that can write the result of this
     * ComputeRequest
     * @return the StreamJsonWriter that will write the result
     */
    public FormattedStreamWriter getResultObject() {
        return this.resultObject;
    }

}