text:
$( document ).ready(function() {
	var socket = io.connect();

	//Variables del chat
	var $messageForm = $('#send-message');
	var $messageBox = $('#message');
	var $chat = $('#chat');

	//Variables del nick
	var $nickForm = $('#setNick');
	var $nickError = $('#nickError');
	var $nickBox = $('#nickname');
	var $users =  $('#users');

	//Nuevo nick
	$nickForm.submit(function (e){
		e.preventDefault();
		socket.emit('new user', $nickBox.val(), function (data){
			if(data){
				$('#nickWrap').hide();
				$('#contentWrap').show();
			} else {
				$nickError.html('Ese usuario ya esta cogido. Prueba con otro');
			}
		});
		$nickBox.val('');
	})

	//Envioo de un mensaje
	$messageForm.submit(function (e){
		e.preventDefault();
		//Si hay un mensaje escrito
		if($messageBox.val()){

            //Recuperamos el mensaje y eliminamos los espacios en blanco al principio y al final
            var message = $messageBox.val();

            socket.emit('send message', $messageBox.val(), function(data){
                if(data.error){
                    $chat.append("
"+ data.error + "

");
                } else {
                    $chat.append("
"+ $messageBox.val() + "

");
                }
            });

			$messageBox.val('');
		}
        $("#chat").animate({ scrollTop: $(document).height() }, "slow");
	});

	//Nuevo mensaje
	socket.on('new message', function (data){
		//Si recibimos un mensaje
		if(data.msg){
			$chat.append("
"+ data.nick + ": " + data.msg + "

");
		}
	});

	//Todos los usuarios
	socket.on('usernames', function (data){
		var html= '';
		for (i=0; i< data.length; i++){
			html += data[i] + '
';
		}
		$users.html(html);
	});

    //Susurro
    socket.on('whisper', function (data){
        if(data.msg){
            $chat.append("
"+ data.nick + ": " + data.msg + "

");
        }
    });
});


text:
;(function(window, $, undefined){

	var arduino = (function(){
		var defaults = {};
		//var location = "ws://localhost:8080/arduino";
		var _arduino = function(options){
			if(!(this instanceof _arduino)){
				return new _arduino(options);
			}

			var self = this;
			self.config = $.extend({}, defaults, options);
			self._ws=undefined;
			self._status=0;
			return self;
		};

		return _arduino;
	})();

	arduino.fn = arduino.prototype = {
		_onmessage: function(self,m){
			if (m.data){
				if (self.config.onReceive && $.isFunction(self.config.onReceive)){
					self.config.onReceive(m);
				}
	        }
		},
		_onclose: function(self){
			self._ws=null;
			self._status=0;
			if (self.config.onClose && $.isFunction(self.config.onClose)){
				self.config.onClose();
			}
		},
		connect: function(){
			var self = this;
			try{
				self._ws=new WebSocket(self.config.location);
				self._ws.onmessage=self._onmessage(self);
				self._ws.onclose=self._onclose(self);
				self._status=1;
				if (self.config.onConnect && $.isFunction(self.config.onConnect)){
					self.config.onConnect(self);
				}
			}catch(error){
				if(self.config.onError && $.isFunction(self.config.onError)){
					self.config.onError(self,error);
				}
			}

		},
		send: function(m){
			var self = this;
			if(self._ws){
	    		self._ws.send(m);
	    		if (self.config.onSend && $.isFunction(self.config.onSend)){
					self.config.onSend(m);
				}
	    	}
		}
	};
	$.arduino = arduino;
})(window, jQuery);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Workflow\Dumper;

use Symfony\Component\Workflow\Definition;
use Symfony\Component\Workflow\Marking;

/**
 * GraphvizDumper dumps a workflow as a graphviz file.
 *
 * You can convert the generated dot file with the dot utility (http://www.graphviz.org/):
 *
 *   dot -Tpng workflow.dot > workflow.png
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
class GraphvizDumper implements DumperInterface
{
    protected static $defaultOptions = [
        'graph' => ['ratio' => 'compress', 'rankdir' => 'LR'],
        'node' => ['fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'fillcolor' => 'lightblue', 'fixedsize' => 'false', 'width' => 1],
        'edge' => ['fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'arrowhead' => 'normal', 'arrowsize' => 0.5],
    ];

    /**
     * {@inheritdoc}
     *
     * Dumps the workflow as a graphviz graph.
     *
     * Available options:
     *
     *  * graph: The default options for the whole graph
     *  * node: The default options for nodes (places + transitions)
     *  * edge: The default options for edges
     */
    public function dump(Definition $definition, Marking $marking = null, array $options = [])
    {
        $places = $this->findPlaces($definition, $marking);
        $transitions = $this->findTransitions($definition);
        $edges = $this->findEdges($definition);

        $options = array_replace_recursive(self::$defaultOptions, $options);

        return $this->startDot($options)
            .$this->addPlaces($places)
            .$this->addTransitions($transitions)
            .$this->addEdges($edges)
            .$this->endDot();
    }

    /**
     * @internal
     */
    protected function findPlaces(Definition $definition, Marking $marking = null)
    {
        $places = [];

        foreach ($definition->getPlaces() as $place) {
            $attributes = [];
            if ($place === $definition->getInitialPlace()) {
                $attributes['style'] = 'filled';
            }
            if ($marking && $marking->has($place)) {
                $attributes['color'] = '#FF0000';
                $attributes['shape'] = 'doublecircle';
            }
            $places[$place] = [
                'attributes' => $attributes,
            ];
        }

        return $places;
    }

    /**
     * @internal
     */
    protected function findTransitions(Definition $definition)
    {
        $transitions = [];

        foreach ($definition->getTransitions() as $transition) {
            $transitions[] = [
                'attributes' => ['shape' => 'box', 'regular' => true],
                'name' => $transition->getName(),
            ];
        }

        return $transitions;
    }

    /**
     * @internal
     */
    protected function addPlaces(array $places)
    {
        $code = '';

        foreach ($places as $id => $place) {
            $code .= sprintf("  place_%s [label=\"%s\", shape=circle%s];\n", $this->dotize($id), $this->escape($id), $this->addAttributes($place['attributes']));
        }

        return $code;
    }

    /**
     * @internal
     */
    protected function addTransitions(array $transitions)
    {
        $code = '';

        foreach ($transitions as $place) {
            $code .= sprintf("  transition_%s [label=\"%s\", shape=box%s];\n", $this->dotize($place['name']), $this->escape($place['name']), $this->addAttributes($place['attributes']));
        }

        return $code;
    }

    /**
     * @internal
     */
    protected function findEdges(Definition $definition)
    {
        $dotEdges = [];

        foreach ($definition->getTransitions() as $transition) {
            foreach ($transition->getFroms() as $from) {
                $dotEdges[] = [
                    'from' => $from,
                    'to' => $transition->getName(),
                    'direction' => 'from',
                ];
            }
            foreach ($transition->getTos() as $to) {
                $dotEdges[] = [
                    'from' => $transition->getName(),
                    'to' => $to,
                    'direction' => 'to',
                ];
            }
        }

        return $dotEdges;
    }

    /**
     * @internal
     */
    protected function addEdges(array $edges)
    {
        $code = '';

        foreach ($edges as $edge) {
            $code .= sprintf("  %s_%s -> %s_%s [style=\"solid\"];\n",
                'from' === $edge['direction'] ? 'place' : 'transition',
                $this->dotize($edge['from']),
                'from' === $edge['direction'] ? 'transition' : 'place',
                $this->dotize($edge['to'])
            );
        }

        return $code;
    }

    /**
     * @internal
     */
    protected function startDot(array $options)
    {
        return sprintf("digraph workflow {\n  %s\n  node [%s];\n  edge [%s];\n\n",
            $this->addOptions($options['graph']),
            $this->addOptions($options['node']),
            $this->addOptions($options['edge'])
        );
    }

    /**
     * @internal
     */
    protected function endDot()
    {
        return "}\n";
    }

    /**
     * @internal
     */
    protected function dotize($id)
    {
        return hash('sha1', $id);
    }

    /**
     * @internal
     */
    protected function escape($value): string
    {
        return \is_bool($value) ? ($value ? '1' : '0') : \addslashes($value);
    }

    private function addAttributes(array $attributes): string
    {
        $code = [];

        foreach ($attributes as $k => $v) {
            $code[] = sprintf('%s="%s"', $k, $this->escape($v));
        }

        return $code ? ', '.implode(', ', $code) : '';
    }

    private function addOptions(array $options): string
    {
        $code = [];

        foreach ($options as $k => $v) {
            $code[] = sprintf('%s="%s"', $k, $v);
        }

        return implode(' ', $code);
    }
}


text:
package org.apache.hadoop.hive.ql.exec.vector.expressions;

import org.apache.hadoop.hive.ql.exec.vector.ColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.metadata.HiveException;

public class IfExprNullNull extends VectorExpression {

  private static final long serialVersionUID = 1L;

  public IfExprNullNull(int outputColumnNum) {
    super(outputColumnNum);
  }

  public IfExprNullNull() {
    super();
  }

  @Override
  public void evaluate(VectorizedRowBatch batch) throws HiveException {

    if (childExpressions != null) {
      super.evaluateChildren(batch);
    }

    final ColumnVector outputColVector = batch.cols[outputColumnNum];

    // We do not need to do a column reset since we are carefully changing the output.

    outputColVector.isNull[0] = true;
    outputColVector.noNulls = false;
    outputColVector.isRepeating = true;
  }

  @Override
  public String vectorExpressionParameters() {
    return "null, null";
  }

  @Override
  public VectorExpressionDescriptor.Descriptor getDescriptor() {
    throw new UnsupportedOperationException("Undefined descriptor");
  }
}


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

<!-- This file is used only to enable IntelliJ JPA console -->

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="authPersistenceUnit">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5435/flowcolab-test"/>
            <property name="javax.persistence.jdbc.account" value="postgres"/>
            <property name="javax.persistence.jdbc.password" value="postgres"/>
        </properties>
    </persistence-unit>
</persistence>


text:
@interface User : NSObject
@property(nonatomic,retain) NSString *name;
@property(nonatomic,retain) NSString *mail;
@property(nonatomic) int age;
@end


text:
typedef std::function<const char*(const char *type)> elf_symbol_colorize_fn;

const char* elf_null_symbol_colorize(const char *type);
const char* elf_ei_class_name(int v);
const char* elf_ei_data_name(int v);
const char* elf_e_type_name(int v);
const char* elf_e_machine_name(int v);
const char* elf_p_type_name(int v);
const std::string elf_p_flags_name(int v);
const char* elf_sh_type_name(int v);
const std::string elf_sh_shndx_name(int v);
const std::string elf_sh_flags_name(int v);
const char* elf_st_bind_name(int v);
const char* elf_st_type_name(int v);
const char* elf_st_other_name(int v);
const char* elf_rela_type_name(int v);
const std::string elf_file_info(elf_file &elf);
const std::string elf_phdr_info(elf_file &elf, int i,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
const std::string elf_shdr_info(elf_file &elf, int i,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
const std::string elf_sym_info(elf_file &elf, int i,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_header_info(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_header_ext_info(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_section_headers(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_program_headers(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_symbol_table(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);
void elf_print_relocations(elf_file &elf,
	elf_symbol_colorize_fn colorize = elf_null_symbol_colorize);

#endif


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

namespace ESolutions.Web.UI
{
	[AttributeUsage(AttributeTargets.Property)]
	public class UrlParameterAttribute : Attribute
	{
		//Properties
		#region SuppoertedValues
		/// <summary>
		/// Gets or sets the supported values.
		/// </summary>
		/// <value>The supported values.</value>
		public String[] SupportedValues
		{
			get;
			set;
		}
		#endregion

		#region IsOptional
		public Boolean IsOptional
		{
			get;
			set;
		}
		#endregion

		//Constructors
		#region UrlParameterAttribute
		public UrlParameterAttribute ( )
		{
			this.SupportedValues = null;
			this.IsOptional = false;
		}
		#endregion
	}
}


text:
:no_entry: [DEPRECATED]

**markdownjs-rails** wraps the [markdown-js](https://github.com/evilstreak/markdown-js) library for silky smooth use with the asset pipeline provided by Rails 3.1. The gem includes the development (non-minified) source for ease of exploration. The asset pipeline will handle minification in your production environment or if you set `config.assets.debug = false` in other environments.

I should also mention that markdown-js hasn't seen much active development in recent years - partially because it works pretty well - but if you're interested in using a JavaScript Markdown converter that's more actively maintained I recommend looking into [Showdown](https://github.com/showdownjs/showdown). I've actually used both but in more recent projects I go with Showdown. And there's a similar Rails gem available [here](https://github.com/joshmcarthur/showdown-rails).

## Installation

Add this line to your application's Gemfile:

    gem 'markdownjs-rails'

Add the following directive to your Javascript manifest file (eg: application.js):

    //= require markdown

## Basic usage:
```
md_content = "Hello.\n\n* This is markdown.\n* It is fun\n* Love it or leave it."
html_content = markdown.toHTML( md_content );
```

And the complete documentation can be found on the [markdonw-js readme](https://github.com/evilstreak/markdown-js).


text:
package org.lastaflute.db.jta;

import java.util.Date;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;

import org.lastaflute.core.magic.TransactionTimeContext;
import org.lastaflute.core.time.TimeManager;
import org.lastaflute.core.util.ContainerUtil;
import org.lastaflute.db.dbflute.accesscontext.PreparedAccessContext;
import org.lastaflute.jta.core.LaUserTransaction;

/**
 * @author jflute
 */
public class HookedUserTransaction extends LaUserTransaction {

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public HookedUserTransaction(TransactionManager transactionManager) {
        super(transactionManager);
    }

    // ===================================================================================
    //                                                                               Begin
    //                                                                               =====
    @Override
    public void begin() throws NotSupportedException, SystemException {
        hookBeforeBegin();
        doBegin();
    }

    protected void hookBeforeBegin() {
        prepareContext();
    }

    protected void doBegin() throws NotSupportedException, SystemException {
        superBegin();
    }

    protected final void superBegin() throws NotSupportedException, SystemException {
        super.begin();
    }

    // ===================================================================================
    //                                                                              Commit
    //                                                                              ======
    @Override
    public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException,
            SecurityException, SystemException {
        doCommit();
        hookAfterCommit();
    }

    protected void doCommit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException {
        superCommit();
    }

    protected final void superCommit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException {
        super.commit();
    }

    protected void hookAfterCommit() {
        clearContext();
    }

    // ===================================================================================
    //                                                                           Roll-back
    //                                                                           =========
    @Override
    public void rollback() throws IllegalStateException, SecurityException, SystemException {
        doRollback();
        hookAfterRollback();
    }

    protected void doRollback() throws SystemException {
        superRollback();
    }

    protected void superRollback() throws SystemException {
        super.rollback();
    }

    protected void hookAfterRollback() {
        clearContext();
    }

    // ===================================================================================
    //                                                                           Side Menu
    //                                                                           =========
    protected void prepareContext() {
        // including dicon gives you the unnatural error in cool deploy
        // (action's container have this dicon's container only in cool deploy)
        // so it gets dependencies in the extension class
        // by directly getting component from singleton container
        // *see the blog for the details:
        //   http://d.hatena.ne.jp/jflute/20130129/1359432974
        final TimeManager timeManager = getTimeManager();
        final Date transactionTime = timeManager.flashDate();
        TransactionTimeContext.setTransactionTime(transactionTime);
        if (PreparedAccessContext.existsAccessContextOnThread()) {
            PreparedAccessContext.beginAccessContext();
        }
    }

    protected TimeManager getTimeManager() {
        return ContainerUtil.getComponent(TimeManager.class);
    }

    protected void clearContext() {
        if (PreparedAccessContext.existsAccessContextOnThread()) {
            PreparedAccessContext.endAccessContext();
        }
        TransactionTimeContext.clear();
    }
}


text:
#include "SkGr.h"
#include "SkColorFilter.h"
#include "SkConfig8888.h"
#include "SkData.h"
#include "SkMessageBus.h"
#include "SkPixelRef.h"
#include "GrResourceCache.h"
#include "GrGpu.h"
#include "GrDrawTargetCaps.h"

#ifndef SK_IGNORE_ETC1_SUPPORT
#  include "ktx.h"
#  include "etc1.h"
#endif

/*  Fill out buffer with the compressed format Ganesh expects from a colortable
 based bitmap. [palette (colortable) + indices].

 At the moment Ganesh only supports 8bit version. If Ganesh allowed we others
 we could detect that the colortable.count is <= 16, and then repack the
 indices as nibbles to save RAM, but it would take more time (i.e. a lot
 slower than memcpy), so skipping that for now.

 Ganesh wants a full 256 palette entry, even though Skia's ctable is only as big
 as the colortable.count says it is.
 */
static void build_compressed_data(void* buffer, const SkBitmap& bitmap) {
    SkASSERT(SkBitmap::kIndex8_Config == bitmap.config());

    SkAutoLockPixels alp(bitmap);
    if (!bitmap.readyToDraw()) {
        SkDEBUGFAIL("bitmap not ready to draw!");
        return;
    }

    SkColorTable* ctable = bitmap.getColorTable();
    char* dst = (char*)buffer;

    const int count = ctable->count();

    SkDstPixelInfo dstPI;
    dstPI.fColorType = kRGBA_8888_SkColorType;
    dstPI.fAlphaType = kPremul_SkAlphaType;
    dstPI.fPixels = buffer;
    dstPI.fRowBytes = count * sizeof(SkPMColor);

    SkSrcPixelInfo srcPI;
    srcPI.fColorType = kN32_SkColorType;
    srcPI.fAlphaType = kPremul_SkAlphaType;
    srcPI.fPixels = ctable->lockColors();
    srcPI.fRowBytes = count * sizeof(SkPMColor);

    srcPI.convertPixelsTo(&dstPI, count, 1);

    ctable->unlockColors();

    // always skip a full 256 number of entries, even if we memcpy'd fewer
    dst += kGrColorTableSize;

    if ((unsigned)bitmap.width() == bitmap.rowBytes()) {
        memcpy(dst, bitmap.getPixels(), bitmap.getSize());
    } else {
        // need to trim off the extra bytes per row
        size_t width = bitmap.width();
        size_t rowBytes = bitmap.rowBytes();
        const char* src = (const char*)bitmap.getPixels();
        for (int y = 0; y < bitmap.height(); y++) {
            memcpy(dst, src, width);
            src += rowBytes;
            dst += width;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

static void generate_bitmap_cache_id(const SkBitmap& bitmap, GrCacheID* id) {
    // Our id includes the offset, width, and height so that bitmaps created by extractSubset()
    // are unique.
    uint32_t genID = bitmap.getGenerationID();
    SkIPoint origin = bitmap.pixelRefOrigin();
    int16_t width = SkToS16(bitmap.width());
    int16_t height = SkToS16(bitmap.height());

    GrCacheID::Key key;
    memcpy(key.fData8 +  0, &genID,     4);
    memcpy(key.fData8 +  4, &origin.fX, 4);
    memcpy(key.fData8 +  8, &origin.fY, 4);
    memcpy(key.fData8 + 12, &width,     2);
    memcpy(key.fData8 + 14, &height,    2);
    static const size_t kKeyDataSize = 16;
    memset(key.fData8 + kKeyDataSize, 0, sizeof(key) - kKeyDataSize);
    GR_STATIC_ASSERT(sizeof(key) >= kKeyDataSize);
    static const GrCacheID::Domain gBitmapTextureDomain = GrCacheID::GenerateDomain();
    id->reset(gBitmapTextureDomain, key);
}

static void generate_bitmap_texture_desc(const SkBitmap& bitmap, GrTextureDesc* desc) {
    desc->fFlags = kNone_GrTextureFlags;
    desc->fWidth = bitmap.width();
    desc->fHeight = bitmap.height();
    desc->fConfig = SkImageInfo2GrPixelConfig(bitmap.info());
    desc->fSampleCnt = 0;
}

namespace {

// When the SkPixelRef genID changes, invalidate a corresponding GrResource described by key.
class GrResourceInvalidator : public SkPixelRef::GenIDChangeListener {
public:
    explicit GrResourceInvalidator(GrResourceKey key) : fKey(key) {}
private:
    GrResourceKey fKey;

    virtual void onChange() SK_OVERRIDE {
        const GrResourceInvalidatedMessage message = { fKey };
        SkMessageBus<GrResourceInvalidatedMessage>::Post(message);
    }
};

}  // namespace

static void add_genID_listener(GrResourceKey key, SkPixelRef* pixelRef) {
    SkASSERT(NULL != pixelRef);
    pixelRef->addGenIDChangeListener(SkNEW_ARGS(GrResourceInvalidator, (key)));
}

#ifndef SK_IGNORE_ETC1_SUPPORT
static GrTexture *load_etc1_texture(GrContext* ctx,
                                    const GrTextureParams* params,
                                    const SkBitmap &bm, GrTextureDesc desc) {
    SkAutoTUnref<SkData> data(bm.pixelRef()->refEncodedData());

    // Is this even encoded data?
    if (NULL == data) {
        return NULL;
    }

    // Is this a valid PKM encoded data?
    const uint8_t *bytes = data->bytes();
    if (etc1_pkm_is_valid(bytes)) {
        uint32_t encodedWidth = etc1_pkm_get_width(bytes);
        uint32_t encodedHeight = etc1_pkm_get_height(bytes);

        // Does the data match the dimensions of the bitmap? If not,
        // then we don't know how to scale the image to match it...
        if (encodedWidth != static_cast<uint32_t>(bm.width()) ||
            encodedHeight != static_cast<uint32_t>(bm.height())) {
            return NULL;
        }

        // Everything seems good... skip ahead to the data.
        bytes += ETC_PKM_HEADER_SIZE;
        desc.fConfig = kETC1_GrPixelConfig;
    } else if (SkKTXFile::is_ktx(bytes)) {
        SkKTXFile ktx(data);

        // Is it actually an ETC1 texture?
        if (!ktx.isETC1()) {
            return NULL;
        }

        // Does the data match the dimensions of the bitmap? If not,
        // then we don't know how to scale the image to match it...
        if (ktx.width() != bm.width() || ktx.height() != bm.height()) {
            return NULL;
        }

        bytes = ktx.pixelData();
        desc.fConfig = kETC1_GrPixelConfig;
    } else {
        return NULL;
    }

    // This texture is likely to be used again so leave it in the cache
    GrCacheID cacheID;
    generate_bitmap_cache_id(bm, &cacheID);

    GrResourceKey key;
    GrTexture* result = ctx->createTexture(params, desc, cacheID, bytes, 0, &key);
    if (NULL != result) {
        add_genID_listener(key, bm.pixelRef());
    }
    return result;
}
#endif   // SK_IGNORE_ETC1_SUPPORT

static GrTexture* sk_gr_create_bitmap_texture(GrContext* ctx,
                                              bool cache,
                                              const GrTextureParams* params,
                                              const SkBitmap& origBitmap) {
    SkBitmap tmpBitmap;

    const SkBitmap* bitmap = &origBitmap;

    GrTextureDesc desc;
    generate_bitmap_texture_desc(*bitmap, &desc);

    if (SkBitmap::kIndex8_Config == bitmap->config()) {
        // build_compressed_data doesn't do npot->pot expansion
        // and paletted textures can't be sub-updated
        if (ctx->supportsIndex8PixelConfig(params, bitmap->width(), bitmap->height())) {
            size_t imagesize = bitmap->width() * bitmap->height() + kGrColorTableSize;
            SkAutoMalloc storage(imagesize);

            build_compressed_data(storage.get(), origBitmap);

            // our compressed data will be trimmed, so pass width() for its
            // "rowBytes", since they are the same now.

            if (cache) {
                GrCacheID cacheID;
                generate_bitmap_cache_id(origBitmap, &cacheID);

                GrResourceKey key;
                GrTexture* result = ctx->createTexture(params, desc, cacheID,
                                                       storage.get(), bitmap->width(), &key);
                if (NULL != result) {
                    add_genID_listener(key, origBitmap.pixelRef());
                }
                return result;
            } else {
                GrTexture* result = ctx->lockAndRefScratchTexture(desc,
                                                            GrContext::kExact_ScratchTexMatch);
                result->writePixels(0, 0, bitmap->width(),
                                    bitmap->height(), desc.fConfig,
                                    storage.get());
                return result;
            }
        } else {
            origBitmap.copyTo(&tmpBitmap, kN32_SkColorType);
            // now bitmap points to our temp, which has been promoted to 32bits
            bitmap = &tmpBitmap;
            desc.fConfig = SkImageInfo2GrPixelConfig(bitmap->info());
        }
    }

    // Is this an ETC1 encoded texture?
#ifndef SK_IGNORE_ETC1_SUPPORT
    else if (
        // We do not support scratch ETC1 textures, hence they should all be at least
        // trying to go to the cache.
        cache
        // Make sure that the underlying device supports ETC1 textures before we go ahead
        // and check the data.
        && ctx->getGpu()->caps()->isConfigTexturable(kETC1_GrPixelConfig)
        // If the bitmap had compressed data and was then uncompressed, it'll still return
        // compressed data on 'refEncodedData' and upload it. Probably not good, since if
        // the bitmap has available pixels, then they might not be what the decompressed
        // data is.
        && !(bitmap->readyToDraw())) {
        GrTexture *texture = load_etc1_texture(ctx, params, *bitmap, desc);
        if (NULL != texture) {
            return texture;
        }
    }
#endif   // SK_IGNORE_ETC1_SUPPORT

    SkAutoLockPixels alp(*bitmap);
    if (!bitmap->readyToDraw()) {
        return NULL;
    }
    if (cache) {
        // This texture is likely to be used again so leave it in the cache
        GrCacheID cacheID;
        generate_bitmap_cache_id(origBitmap, &cacheID);

        GrResourceKey key;
        GrTexture* result = ctx->createTexture(params, desc, cacheID,
                                               bitmap->getPixels(), bitmap->rowBytes(), &key);
        if (NULL != result) {
            add_genID_listener(key, origBitmap.pixelRef());
        }
        return result;
   } else {
        // This texture is unlikely to be used again (in its present form) so
        // just use a scratch texture. This will remove the texture from the
        // cache so no one else can find it. Additionally, once unlocked, the
        // scratch texture will go to the end of the list for purging so will
        // likely be available for this volatile bitmap the next time around.
        GrTexture* result = ctx->lockAndRefScratchTexture(desc, GrContext::kExact_ScratchTexMatch);
        result->writePixels(0, 0,
                            bitmap->width(), bitmap->height(),
                            desc.fConfig,
                            bitmap->getPixels(),
                            bitmap->rowBytes());
        return result;
    }
}

bool GrIsBitmapInCache(const GrContext* ctx,
                       const SkBitmap& bitmap,
                       const GrTextureParams* params) {
    GrCacheID cacheID;
    generate_bitmap_cache_id(bitmap, &cacheID);

    GrTextureDesc desc;
    generate_bitmap_texture_desc(bitmap, &desc);
    return ctx->isTextureInCache(desc, cacheID, params);
}

GrTexture* GrLockAndRefCachedBitmapTexture(GrContext* ctx,
                                           const SkBitmap& bitmap,
                                           const GrTextureParams* params) {
    GrTexture* result = NULL;

    bool cache = !bitmap.isVolatile();

    if (cache) {
        // If the bitmap isn't changing try to find a cached copy first.

        GrCacheID cacheID;
        generate_bitmap_cache_id(bitmap, &cacheID);

        GrTextureDesc desc;
        generate_bitmap_texture_desc(bitmap, &desc);

        result = ctx->findAndRefTexture(desc, cacheID, params);
    }
    if (NULL == result) {
        result = sk_gr_create_bitmap_texture(ctx, cache, params, bitmap);
    }
    if (NULL == result) {
        GrPrintf("---- failed to create texture for cache [%d %d]\n",
                    bitmap.width(), bitmap.height());
    }
    return result;
}

void GrUnlockAndUnrefCachedBitmapTexture(GrTexture* texture) {
    SkASSERT(NULL != texture->getContext());

    texture->getContext()->unlockScratchTexture(texture);
    texture->unref();
}

///////////////////////////////////////////////////////////////////////////////

GrPixelConfig SkBitmapConfig2GrPixelConfig(SkBitmap::Config config) {
    switch (config) {
        case SkBitmap::kA8_Config:
            return kAlpha_8_GrPixelConfig;
        case SkBitmap::kIndex8_Config:
            return kIndex_8_GrPixelConfig;
        case SkBitmap::kRGB_565_Config:
            return kRGB_565_GrPixelConfig;
        case SkBitmap::kARGB_4444_Config:
            return kRGBA_4444_GrPixelConfig;
        case SkBitmap::kARGB_8888_Config:
            return kSkia8888_GrPixelConfig;
        default:
            // kNo_Config, kA1_Config missing
            return kUnknown_GrPixelConfig;
    }
}

// alphatype is ignore for now, but if GrPixelConfig is expanded to encompass
// alpha info, that will be considered.
GrPixelConfig SkImageInfo2GrPixelConfig(SkColorType ct, SkAlphaType) {
    switch (ct) {
        case kUnknown_SkColorType:
            return kUnknown_GrPixelConfig;
        case kAlpha_8_SkColorType:
            return kAlpha_8_GrPixelConfig;
        case kRGB_565_SkColorType:
            return kRGB_565_GrPixelConfig;
        case kARGB_4444_SkColorType:
            return kRGBA_4444_GrPixelConfig;
        case kRGBA_8888_SkColorType:
            return kRGBA_8888_GrPixelConfig;
        case kBGRA_8888_SkColorType:
            return kBGRA_8888_GrPixelConfig;
        case kIndex_8_SkColorType:
            return kIndex_8_GrPixelConfig;
    }
    SkASSERT(0);    // shouldn't get here
    return kUnknown_GrPixelConfig;
}

bool GrPixelConfig2ColorType(GrPixelConfig config, SkColorType* ctOut) {
    SkColorType ct;
    switch (config) {
        case kAlpha_8_GrPixelConfig:
            ct = kAlpha_8_SkColorType;
            break;
        case kIndex_8_GrPixelConfig:
            ct = kIndex_8_SkColorType;
            break;
        case kRGB_565_GrPixelConfig:
            ct = kRGB_565_SkColorType;
            break;
        case kRGBA_4444_GrPixelConfig:
            ct = kARGB_4444_SkColorType;
            break;
        case kRGBA_8888_GrPixelConfig:
            ct = kRGBA_8888_SkColorType;
            break;
        case kBGRA_8888_GrPixelConfig:
            ct = kBGRA_8888_SkColorType;
            break;
        default:
            return false;
    }
    if (ctOut) {
        *ctOut = ct;
    }
    return true;
}

///////////////////////////////////////////////////////////////////////////////

void SkPaint2GrPaintNoShader(GrContext* context, const SkPaint& skPaint, bool justAlpha,
                             bool constantColor, GrPaint* grPaint) {

    grPaint->setDither(skPaint.isDither());
    grPaint->setAntiAlias(skPaint.isAntiAlias());

    SkXfermode::Coeff sm;
    SkXfermode::Coeff dm;

    SkXfermode* mode = skPaint.getXfermode();
    GrEffectRef* xferEffect = NULL;
    if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
        if (NULL != xferEffect) {
            grPaint->addColorEffect(xferEffect)->unref();
            sm = SkXfermode::kOne_Coeff;
            dm = SkXfermode::kZero_Coeff;
        }
    } else {
        //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
        // Fall back to src-over
        sm = SkXfermode::kOne_Coeff;
        dm = SkXfermode::kISA_Coeff;
    }
    grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));

    if (justAlpha) {
        uint8_t alpha = skPaint.getAlpha();
        grPaint->setColor(GrColorPackRGBA(alpha, alpha, alpha, alpha));
        // justAlpha is currently set to true only if there is a texture,
        // so constantColor should not also be true.
        SkASSERT(!constantColor);
    } else {
        grPaint->setColor(SkColor2GrColor(skPaint.getColor()));
    }

    SkColorFilter* colorFilter = skPaint.getColorFilter();
    if (NULL != colorFilter) {
        // if the source color is a constant then apply the filter here once rather than per pixel
        // in a shader.
        if (constantColor) {
            SkColor filtered = colorFilter->filterColor(skPaint.getColor());
            grPaint->setColor(SkColor2GrColor(filtered));
        } else {
            SkAutoTUnref<GrEffectRef> effect(colorFilter->asNewEffect(context));
            if (NULL != effect.get()) {
                grPaint->addColorEffect(effect);
            }
        }
    }
}

/**
 * Unlike GrContext::AutoMatrix, this doesn't require setting a new matrix. GrContext::AutoMatrix
 * likes to set the new matrix in its constructor because it is usually necessary to simulataneously
 * update a GrPaint. This AutoMatrix is used while initially setting up GrPaint, however.
 */
class AutoMatrix {
public:
    AutoMatrix(GrContext* context) {
        fMatrix = context->getMatrix();
        fContext = context;
    }
    ~AutoMatrix() {
        SkASSERT(NULL != fContext);
        fContext->setMatrix(fMatrix);
    }
private:
    GrContext* fContext;
    SkMatrix fMatrix;
};

void SkPaint2GrPaintShader(GrContext* context, const SkPaint& skPaint,
                           bool constantColor, GrPaint* grPaint) {
    SkShader* shader = skPaint.getShader();
    if (NULL == shader) {
        SkPaint2GrPaintNoShader(context, skPaint, false, constantColor, grPaint);
        return;
    }

    // SkShader::asNewEffect() may do offscreen rendering. Save off the current RT, clip, and
    // matrix. We don't reset the matrix on the context because SkShader::asNewEffect may use
    // GrContext::getMatrix() to know the transformation from local coords to device space.
    GrContext::AutoRenderTarget art(context, NULL);
    GrContext::AutoClip ac(context, GrContext::AutoClip::kWideOpen_InitialClip);
    AutoMatrix am(context);

    // setup the shader as the first color effect on the paint
    SkAutoTUnref<GrEffectRef> effect(shader->asNewEffect(context, skPaint, NULL));
    if (NULL != effect.get()) {
        grPaint->addColorEffect(effect);
        // Now setup the rest of the paint.
        SkPaint2GrPaintNoShader(context, skPaint, true, false, grPaint);
    } else {
        // We still don't have SkColorShader::asNewEffect() implemented.
        SkShader::GradientInfo info;
        SkColor                color;

        info.fColors = &color;
        info.fColorOffsets = NULL;
        info.fColorCount = 1;
        if (SkShader::kColor_GradientType == shader->asAGradient(&info)) {
            SkPaint copy(skPaint);
            copy.setShader(NULL);
            // modulate the paint alpha by the shader's solid color alpha
            U8CPU newA = SkMulDiv255Round(SkColorGetA(color), copy.getAlpha());
            copy.setColor(SkColorSetA(color, newA));
            SkPaint2GrPaintNoShader(context, copy, false, constantColor, grPaint);
        } else {
            SkPaint2GrPaintNoShader(context, skPaint, false, constantColor, grPaint);
        }
    }
}


text:
import React from 'react'
import { storiesOf } from '@storybook/react'
import {
  Autopilot,
  ConnectionType,
  ConnectionDetails,
  ConnectionConfirm,
  Login,
  Name,
  Network,
  Password,
  Recover,
  SeedConfirm,
  SeedView,
  WalletCreate,
} from 'components/Onboarding/Steps'

const setConnectionHost = () => ({})
const setConnectionCert = () => ({})
const setConnectionMacaroon = () => ({})
const stopLnd = () => ({})
const resetOnboarding = () => ({})
const wizardApi = { next() {} }

storiesOf('Containers.Onboarding.Forms', module)
  .add('ConnectionType', () => (
    <ConnectionType resetOnboarding={resetOnboarding} stopLnd={stopLnd} />
  ))
  .add('ConnectionDetails', () => (
    <ConnectionDetails
      setConnectionCert={setConnectionCert}
      setConnectionHost={setConnectionHost}
      setConnectionMacaroon={setConnectionMacaroon}
    />
  ))
  .add('ConnectionConfirm', () => <ConnectionConfirm connectionHost="example.com:10009" />)
  .add('Login', () => <Login />)
  .add('Password', () => <Password />)
  .add('Recover', () => <Recover seed={[]} />)
  .add('Name', () => <Name />)
  .add('Network', () => <Network />)
  .add('Autopilot', () => <Autopilot />)
  .add('Creating', () => <WalletCreate isCreatingWallet wizardApi={wizardApi} />)
  .add('SeedConfirm', () => (
    <SeedConfirm
      seed={[
        'idle',
        'fork',
        'derive',
        'idea',
        'pony',
        'exercise',
        'balance',
        'squirrel',
        'around',
        'sustain',
        'outdoor',
        'beach',
        'thrive',
        'fringe',
        'broom',
        'sea',
        'sick',
        'bacon',
        'card',
        'palace',
        'slender',
        'blue',
        'day',
        'fix',
      ]}
    />
  ))
  .add('SeedView', () => (
    <SeedView
      seed={[
        'idle',
        'fork',
        'derive',
        'idea',
        'pony',
        'exercise',
        'balance',
        'squirrel',
        'around',
        'sustain',
        'outdoor',
        'beach',
        'thrive',
        'fringe',
        'broom',
        'sea',
        'sick',
        'bacon',
        'card',
        'palace',
        'slender',
        'blue',
        'day',
        'fix',
      ]}
    />
  ))


text:
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="nelmio_api_doc.formatter.abstract_formatter.class">Nelmio\ApiDocBundle\Formatter\AbstractFormatter</parameter>
        <parameter key="nelmio_api_doc.formatter.markdown_formatter.class">Nelmio\ApiDocBundle\Formatter\MarkdownFormatter</parameter>
        <parameter key="nelmio_api_doc.formatter.simple_formatter.class">Nelmio\ApiDocBundle\Formatter\SimpleFormatter</parameter>
        <parameter key="nelmio_api_doc.formatter.html_formatter.class">Nelmio\ApiDocBundle\Formatter\HtmlFormatter</parameter>
        <parameter key="nelmio_api_doc.sandbox.authentication">null</parameter>
    </parameters>

    <services>
        <service id="nelmio_api_doc.formatter.abstract_formatter" class="%nelmio_api_doc.formatter.abstract_formatter.class%" />
        <service id="nelmio_api_doc.formatter.markdown_formatter" class="%nelmio_api_doc.formatter.markdown_formatter.class%"
            parent="nelmio_api_doc.formatter.abstract_formatter" />
        <service id="nelmio_api_doc.formatter.simple_formatter" class="%nelmio_api_doc.formatter.simple_formatter.class%"
            parent="nelmio_api_doc.formatter.abstract_formatter" />
        <service id="nelmio_api_doc.formatter.html_formatter" class="%nelmio_api_doc.formatter.html_formatter.class%"
            parent="nelmio_api_doc.formatter.abstract_formatter">
            <call method="setTemplatingEngine">
                <argument type="service" id="templating" />
            </call>
            <call method="setMotdTemplate">
                <argument>%nelmio_api_doc.motd.template%</argument>
            </call>
            <call method="setApiName">
                <argument>%nelmio_api_doc.api_name%</argument>
            </call>
            <call method="setEnableSandbox">
                <argument>%nelmio_api_doc.sandbox.enabled%</argument>
            </call>
            <call method="setEndpoint">
                <argument>%nelmio_api_doc.sandbox.endpoint%</argument>
            </call>
            <call method="setRequestFormatMethod">
                <argument>%nelmio_api_doc.sandbox.request_format.method%</argument>
            </call>
            <call method="setRequestFormats">
                <argument>%nelmio_api_doc.sandbox.request_format.formats%</argument>
            </call>
            <call method="setDefaultRequestFormat">
                <argument>%nelmio_api_doc.sandbox.request_format.default_format%</argument>
            </call>
            <call method="setAcceptType">
                <argument>%nelmio_api_doc.sandbox.accept_type%</argument>
            </call>
            <call method="setBodyFormat">
                <argument>%nelmio_api_doc.sandbox.body_format%</argument>
            </call>
            <call method="setAuthentication">
                <argument>%nelmio_api_doc.sandbox.authentication%</argument>
            </call>
        </service>
    </services>

</container>


text:
export class ScoreSystem {
  public scores: Map<any, number>;
  constructor() {
    this.scores = new Map();
  }

  static standard() {
    return new ScoreSystem();
  }

  initialize(player) {
    this.setScore(player, 0)
  }

  getScore(player) {
      return this.scores.get(player);
  }

  setScore(player, score) {
    if (player) {
      this.scores.set(player, score);
    }
  }

  updateScore(player, dscore) {
    return this.setScore(player, this.getScore(player)+dscore);
  }

  onLevelChange(player, level, timeleft) {
    this.updateScore(player, (timeleft+2000) / 10);
  }

  onEnemyKilled(player, enemy) {
    this.updateScore(player, 10);
  }
}


text:
A Haxe port of the [FlashPunk](http://useflashpunk.net) AS3 library. There are a few additions/differences from the original.

* Builds for Flash, Windows, Mac, Linux, iOS, Android, and Ouya
* Circle/Polygon masks
* Hardware acceleration for native targets
* Joystick and multi-touch input
* Texture atlases for native targets (supports TexturePacker xml)

[![Build Status](https://travis-ci.org/Punkiversal/Punkiversal.png?branch=dev)](https://travis-ci.org/Punkiversal/Punkiversal)

## Release build

First, make sure you have [Haxe](http://haxe.org) 3.0 or higher, we recommend you to update to Haxe 3.1.3 if you haven't already. Then execute the following commands below to get started with your first Punkiversal project.
If you are using Haxe 2 the last version supporting it was [v2.3.0](https://github.com/Punkiversal/Punkiversal/releases/tag/v2.3.0) `haxelib install Punkiversal 2.3.0`.

```bash
haxelib install Punkiversal
haxelib run Punkiversal setup
haxelib run Punkiversal new MyProject # creates a new project
```

## Development build

You need to have ant installed to build a development version of Punkiversal. Make sure you set a default program for swf files to view the debug output. You will also need a C++ compiler for native builds (Xcode, Visual Studio, g++).

```bash
git clone https://github.com/Punkiversal/Punkiversal.git
ant
```

This will install a dev version of Punkiversal through haxelib, run unit tests, and build an example project for flash/neko/native. If you fix an issue, feel free to create a pull request.

Generating documentation is just as simple. Run the commands below to create a new set of docs with haxedoc
The documentation will be located in doc/docs/, simply open doc/docs/index.html with your web browser to see the doc.

```bash
ant doc
```

## Have questions or looking to get involved?

There are a few ways you can get involved with Punkiversal.

*	Drop by the [Punkiversal forum](http://forum.punkiversal.com) to ask a question or show off what you've created.
*	Create an issue or pull request or take part in the discussion.
*	Follow us on Twitter: [@Punkiversal](https://twitter.com/intent/user?screen_name=Punkiversal)

## Credits

*	Chevy Ray Johnston for creating the original FlashPunk.
*	[OpenFL](http://www.openfl.org/) makes native targets possible and simplifies asset management in Flash. Thanks guys!
*	All the awesome people who have [contributed](https://github.com/Punkiversal/Punkiversal/graphs/contributors) to Punkiversal and joined in the discussions on the [forum](http://forum.punkiversal.com).

## MIT License

Copyright (C) 2012-2014 Matt Tuttle

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<?php

namespace Oro\Bundle\TestFrameworkBundle\Test\Doctrine\ORM\Mocks;

use Oro\Component\TestUtils\ORM\Mocks\ConnectionMock as BaseConnectionMock;

/**
 * @deprecated since 1.9. use {@see Oro\Component\TestUtils\ORM\Mocks\ConnectionMock}
 */
class ConnectionMock extends BaseConnectionMock
{
}


text:
/*
 * Testcase: Test the CS prefetch behaviour on batches
 *
 * Historically the batch prefetcher doesn't check whether it's crossing page
 * boundaries and likes to throw up when it gets a pagefault in return for his
 * over-eager behaviour. Check for this.
 *
 * This test for a bug where we've failed to plug a scratch pte entry into the
 * very last gtt pte.
 */
#include "igt.h"

IGT_TEST_DESCRIPTION("Test the CS prefetch behaviour on batches.");

#define BATCH_SIZE 4096

struct shadow {
	uint32_t handle;
	struct drm_i915_gem_relocation_entry reloc;
};

static void gem_require_store_dword(int fd, unsigned ring)
{
	int gen = intel_gen(intel_get_drm_devid(fd));
	ring &= ~(3 << 13);
	igt_skip_on_f(gen == 6 && ring == I915_EXEC_BSD,
		      "MI_STORE_DATA broken on gen6 bsd\n");
}

static void setup(int fd, int gen, struct shadow *shadow)
{
	uint32_t buf[16];
	int i;

	shadow->handle = gem_create(fd, 4096);

	i = 0;
	buf[i++] = MI_STORE_DWORD_IMM | (gen < 6 ? 1 << 22 : 0);
	if (gen >= 8) {
		buf[i++] = BATCH_SIZE - sizeof(uint32_t);
		buf[i++] = 0;
	} else if (gen >= 4) {
		buf[i++] = 0;
		buf[i++] = BATCH_SIZE - sizeof(uint32_t);
	} else {
		buf[i-1]--;
		buf[i++] = BATCH_SIZE - sizeof(uint32_t);
	}
	buf[i++] = MI_BATCH_BUFFER_END;
	buf[i++] = MI_BATCH_BUFFER_END;
	gem_write(fd, shadow->handle, 0, buf, sizeof(buf));

	memset(&shadow->reloc, 0, sizeof(shadow->reloc));
	if (gen >= 8 || gen < 4)
		shadow->reloc.offset = sizeof(uint32_t);
	else
		shadow->reloc.offset = 2*sizeof(uint32_t);
	shadow->reloc.delta = BATCH_SIZE - sizeof(uint32_t);
	shadow->reloc.read_domains = I915_GEM_DOMAIN_INSTRUCTION;
	shadow->reloc.write_domain = I915_GEM_DOMAIN_INSTRUCTION;
}

static void can_test_ring(unsigned ring)
{
	int master = drm_open_driver_master(DRIVER_INTEL);
	int fd = drm_open_driver(DRIVER_INTEL);

	/* Dance to avoid dying with master open */
	close(master);
	gem_require_ring(fd, ring);
	gem_require_store_dword(fd, ring);
	close(fd);
}

static void test_ring(unsigned ring)
{
	struct drm_i915_gem_execbuffer2 execbuf;
	struct drm_i915_gem_exec_object2 obj[2];
	struct shadow shadow;
	uint64_t i, count;
	int fd, gen;

	can_test_ring(ring);

	fd = drm_open_driver_master(DRIVER_INTEL);
	gen = intel_gen(intel_get_drm_devid(fd));
	setup(fd, gen, &shadow);

	count = gem_aperture_size(fd) / BATCH_SIZE;
	intel_require_memory(count, BATCH_SIZE, CHECK_RAM);
	/* Fill the entire gart with batches and run them. */
	memset(obj, 0, sizeof(obj));
	obj[1].handle = shadow.handle;
	obj[1].relocs_ptr = (uintptr_t)&shadow.reloc;
	obj[1].relocation_count = 1;

	memset(&execbuf, 0, sizeof(execbuf));
	execbuf.buffers_ptr = (uintptr_t)obj;
	execbuf.flags = ring;
	if (gen < 6)
		execbuf.flags |= I915_EXEC_SECURE;

	for (i = 0; i < count; i++) {
		/* Create the new batch using the GPU */
		obj[0].handle = gem_create(fd, BATCH_SIZE);
		shadow.reloc.target_handle = obj[0].handle;
		execbuf.buffer_count = 2;
		gem_execbuf(fd, &execbuf);

		/* ...then execute the new batch */
		execbuf.buffer_count = 1;
		gem_execbuf(fd, &execbuf);

		/* ...and leak the handle to consume the GTT */
	}

	close(fd);
}

igt_main
{
	const struct intel_execution_engine *e;

	igt_skip_on_simulation();

	for (e = intel_execution_engines; e->name; e++)
		igt_subtest_f("%s", e->name)
			test_ring(e->exec_id | e->flags);
}


text:
Check distances with latitude and longitude using PostgreSQL special indexes.
This gem enables your model to query the database using the earthdistance extension. This should be much faster than using trigonometry functions over standard indexes.

##Requirements

Postgresql 9.1+ with contrib and Rails 3.1+
On Ubuntu, this is easy: `sudo apt-get install postgresql-contrib-9.1`

On Mac you have a couple of options:

* [the binary package kindly provided by EnterpriseDB](http://www.enterprisedb.com/products-services-training/pgdownload#osx)
* [Homebrew's](https://github.com/mxcl/homebrew) Postgres installation also includes the contrib packages: `brew install postgres`
* [Postgres.app](http://postgresapp.com/)

##Install

Earthdistance is a PostgreSQL contrib module, [check it out first](http://www.postgresql.org/docs/9.2/static/earthdistance.html).

Then, just add this to your Gemfile:

`gem 'activerecord-postgres-earthdistance'`

And run your bundler:

`bundle install`

Now you need to create a migration that adds earthdistance support for your
PostgreSQL database:

`rails g earth_distance:setup`

Run it:

`rake db:migrate`

Now let's add some gist indexes to make queries ultra-fast.
For the model Place we could create an index over the lat and lng fields:

`rails g migration add_index_to_places`

Edit the created migration:

```ruby
class AddIndexToPlaces < ActiveRecord::Migration
  def up
    add_earthdistance_index :places
  end

  def down
    remove_earthdistance_index :places
  end
end
```

This will create the index with a SQL like this:
```sql
CREATE INDEX places_earthdistance_ix ON places USING GIST (ll_to_earth(lat, lng));
```

##Usage

This gem only provides a custom serialization coder.
If you want to use it just put in your Gemfile:

    gem 'activerecord-postgres-earthdistance'

Now add a line (for each earthdistance column) on the model you have your earthdistance columns.
Assuming a model called **Person**, with a **data** field on it, the
code should look like:

```ruby
class Place < ActiveRecord::Base
  acts_as_geolocated
end
```

This way, you will automatically look for columns with names such as lat/latitude and lng/longitude.
But you can use alternative names passing them as:

```ruby
class Place < ActiveRecord::Base
  acts_as_geolocated lat: 'latitude_column_name', lng: 'longitude_column_name'
end
```

###Querying the database

To query for all places within a given radius of 100 meters from the origin -22.951916,-43.210487 just use:
```ruby
Place.within_radius(100, -22.951916, -43.210487).all
```

You can also order the records based on the distance from a point
```ruby
Place.within_radius(100, -22.951916,-43.210487).order_by_distance(-22.951916,-43.210487)
```

The `within_radius` query performs two checks: first against the *bounding box*, followed by computing the exact distance for
all contained elements. The latter might be computationally expensive for big ranges.
So if precision is not an issue but query speed is, you might want to query against the bounding box only:
```ruby
Place.within_box(1_000_000, -22.951916,-43.210487)
```

Select the distance from a point:
```ruby
point = [-22.951916, -43.210487]
closest = Place.within_radius(100, *point).order_by_distance(*point).selecting_distance_from(*point).first
closest.distance
```

##Test Database

To have earthdistance enabled when you load your database schema (as happens in rake db:test:prepare), you
have two options.

The first option is creating a template database with earthdistance installed and set the template option
in database.yml to that database.

The second option is to uncomment or add the following line in config/application.rb

    config.active_record.schema_format = :sql

This will change your schema dumps from Ruby to SQL. If you're
unsure about the implications of this change, we suggest reading this
[Rails Guide](http://guides.rubyonrails.org/migrations.html#schema-dumping-and-you).

##Help

You can use issues in github for that. Or else you can reach us at
twitter: [@dbiazus](https://twitter.com/#!/dbiazus)

##Note on Patches/Pull Requests

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Commit, do not mess with rakefile, version, or history.  (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.

##Copyright

Copyright © 2010 Diogo Biazus. See LICENSE for details.


text:
<?php

/**
 * @namespace
 */
namespace Zend\Crypt\Math\BigInteger;

/**
 * @see Zend_Crypt_Math_Exception
 */
require_once 'Zend/Crypt/Math/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Crypt
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Exception extends \Zend\Crypt\Math\Exception
{
}


text:
<?php
function header_background(){
    $background_color = get_theme_mod('header_background_color');
    echo $background_color;
}
add_action('wp_ajax_header_background', 'header_background');
add_action('wp_ajax_nopriv_header_background', 'header_background');
?>


text:
package com.jk.db.dynamic.query;

/**
 * The Interface Join.
 *
 * @author Jalal Kiswani
 */
public interface Join extends QueryComponent {

}


text:
<!DOCTYPE html>

		<title>Pattern Lab Sub-type Style Guide</title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width" />
		<link rel="stylesheet" href="../../styleguide/css/styleguide.css" media="all" />
		<link rel="stylesheet" href="../../css/style.css" media="all" />

Header

		Search
	Menu

Home

About

Blog

Contact

	<form action="#" method="post" class="inline-form search-form">
	    <fieldset>
		    <legend class="is-vishidden">Search</legend>
		    Search
		    <input type="search" placeholder="Search" id="search-field" class="search-field" />
		    <button class="search-submit">

		    	Search
		    </button>
	    </fieldset>
	</form>

										This pattern contains:
											atoms-logo
											molecules-primary-nav
											molecules-search

HTML

										<!-- Begin .header -->
<header class="header cf" role="banner">
	<a href="#"><img src="../../images/logo.png" class="logo" alt="Logo Alt Text" /></a>	<a href="#search-form" class="nav-toggle nav-toggle-search icon-search"><span class="is-vishidden">Search</span></a>
	<a href="#nav" class="nav-toggle nav-toggle-menu icon-menu"><span class="is-vishidden">Menu</span></a>
	<nav id="nav" class="nav">
		<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Blog</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
	</nav><!--end .nav-->
	<form action="#" method="post" class="inline-form search-form">
	    <fieldset>
		    <legend class="is-vishidden">Search</legend>
		    <label for="search-field" class="is-vishidden">Search</label>
		    <input type="search" placeholder="Search" id="search-field" class="search-field" />
		    <button class="search-submit">
		    	<span class="icon-search" aria-hidden="true"></span>
		    	<span class="is-vishidden">Search</span>
		    </button>
	    </fieldset>
	</form></header>
<!-- End .header -->

Footer

© 2013 Company Name. All rights reserved.

HTML

										<!-- Begin Footer -->
<footer class="footer" role="contentinfo">
	<div class="lc">
		<p class="copyright">&copy; 2013 Company Name. All rights reserved.</p>
	</div>
</footer>
<!-- End Footer -->


text:
%% DEMO 12: Understanding different Forward projections
%
%
%  In this more advanced demo, an explanation of the differecne between the
%  forward projections will be given.
%
%  While there are 2 backprojectors, these are less different, they just
%  have different weigths. One of the has a FDK weigtht and the other on has
%  a weight that makes it mathematically very close to the transpose of
%  matrix A.
%
%
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% This file is part of the TIGRE Toolbox
%
% Copyright (c) 2015, University of Bath and
%                     CERN-European Organization for Nuclear Research
%                     All rights reserved.
%
% License:            Open Source under BSD.
%                     See the full license at
%                     https://github.com/CERN/TIGRE/blob/master/LICENSE
%
% Contact:            tigre.toolbox@gmail.com
% Codes:              https://github.com/CERN/TIGRE/
% Coded by:           Ander Biguri
%--------------------------------------------------------------------------
%% Initialize
clear;
close all;

%% Define Geometry
%
geo=defaultGeometry('nVoxel',[128;128;128]);

%% This parameter is key for the accuracy of the interpolated FWD projection.
geo.accuracy=0.5;                           % Accuracy of FWD proj          (vx/sample)

%% Description
% The difference between them is that `Siddon` will compute the
% intersection of a ray crossing each voxel, and the `interpolated` will
% sample the voxels at a given sample rate.

%% Main difference

shepp=sheppLogan3D(geo.nVoxel);
tic
projInterp=Ax(shepp,geo,0,'interpolated');
interptime=toc;
tic
projray   =Ax(shepp,geo,0,'Siddon');
raytime=toc;
% It is relatively clear that discretization artefacts appear with the
% ray-voxel approach
plotProj([projInterp projray abs(projInterp-projray)],0);
% But also the ray voxel approach is faster (more obvious at bigger sizes)
disp(['Time interpolated: ' num2str(interptime)]);
disp(['Time Siddon      : ' num2str(raytime)]);
disp('Press enter to continue')
pause
%% We can play with the accuracy value

% With small voxel the errors are more obvious
geo.nVoxel=[32;32;32];                      % number of voxels              (vx)
geo.sVoxel=[256;256;256];                   % total size of the image       (mm)
geo.dVoxel=geo.sVoxel./geo.nVoxel;          % size of each voxel            (mm)
shepp=sheppLogan3D(geo.nVoxel);

geo.accuracy=3;
projInterp3=Ax(shepp,geo,0,'interpolated');
geo.accuracy=1;
projInterp1=Ax(shepp,geo,0,'interpolated');
geo.accuracy=0.5;
projInterp05=Ax(shepp,geo,0,'interpolated');
geo.accuracy=0.2;
projInterp02=Ax(shepp,geo,0,'interpolated');
geo.accuracy=0.05;
projInterp3005=Ax(shepp,geo,0,'interpolated');
geo.accuracy=0.01;
projInterp3001=Ax(shepp,geo,0,'interpolated');

% the error varies, at big accuracy values because interpolated option
% samples too few, but at small values because ray-voxel creates
% discretization artefacts
% ---------------------------------------------------------------------

% However It looks like while there is a big difference between the biggest
% and smallers, from accuracy from 1 to 0.01 there is no much change
plotProj([abs(projInterp02-projray) abs(projInterp3005-projray) abs(projInterp3001-projray);...
          abs(projInterp3-projray) abs(projInterp1-projray) abs(projInterp05-projray)],0,'CLims',[0 20]);

disp('Press enter to continue')
pause
% lets test the all accuracys against the smalles geo.accuracy value
% ---------------------------------------------------------------------
%
% Observe the colorbars. Note that themaximum value of the projection is
% around 60~, meaning a value of error of 14, is very relevant, while a
% value of error of 0.1 is less.
plotProj(abs(projInterp3-projInterp3001),0);
title('geo.accuracy=3')

plotProj(abs(projInterp1-projInterp3001),0);
title('geo.accuracy=1')

plotProj(abs(projInterp05-projInterp3001),0);
title('geo.accuracy=0.5')

plotProj(abs(projInterp02-projInterp3001),0);
title('geo.accuracy=0.2')

plotProj(abs(projInterp3005-projInterp3001),0);
title('geo.accuracy=0.05')

% From these plots we can conclude that  a value of 1 or less of
% geo.accuracy i srasonable. The smaller the better, but eventually the
% error will be so small that the imporvement is unperceptible. we
% reccomend something in the range [0.1-0.5]


text:
const fs = require('fs');
const Path = require('Path');

const deleteFolderRecursive = function(path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach((file, index) => {
            const curPath = Path.join(path, file);
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

const resetOutput = (path) =>{
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function(file, index){
            var curPath = path + "/" + file;
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
    fs.mkdirSync(path);
};

const outputJsonFile = ( path, filename, data, reset) => {
    if( reset ) resetOutput(path);
    if( data ) data = JSON.parse(JSON.stringify(data));
    fs.writeFile(`${path}/${filename}.json`, JSON.stringify(data), function (err) {
        if (err) return console.log(err);
        console.log('saved-> ',filename);
    });
};

module.exports = outputJsonFile;


text:
package org.sakaiproject.jpa;

public class Address
{
	private int addressId;
	private String street;
	private String city;
	private String state;
	private Employee employee;

	public Employee getEmployee()
	{
		return employee;
	}

	public void setEmployee(Employee employee)
	{
		this.employee = employee;
	}

	public int getAddressId()
	{
		return addressId;
	}

	public void setAddressId(int addressId)
	{
		this.addressId = addressId;
	}

	public String getStreet()
	{
		return street;
	}

	public void setStreet(String street)
	{
		this.street = street;
	}

	public String getCity()
	{
		return city;
	}

	public void setCity(String city)
	{
		this.city = city;
	}

	public String getState()
	{
		return state;
	}

	public void setState(String state)
	{
		this.state = state;
	}
}


text:
package org.onetwo.common.utils;

import static org.assertj.core.api.Assertions.assertThat;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.tuple.Pair;
import org.junit.Assert;
import org.junit.Test;

import com.google.common.collect.Lists;

public class LangOpsTest {
	public UserEntity createUser(String userName, int age){
		UserEntity user = new UserEntity();
		user.setUserName(userName);
		user.setAge(age);
		user.setHeight(Integer.valueOf(age).floatValue());
		user.setId(Long.valueOf(age));
		return user;
	}

	public List<UserEntity> createUserList(String userName, int count){
		List<UserEntity> users = LangUtils.newArrayList(count);
		for (int i = 0; i < count; i++) {
			users.add(createUser(userName, i));
		}
		return users;
	}

	@Test
	public void testArrayToMap(){
		Object[] arrays = new Object[]{"key1", 1, "key2", "value2"};
		Map<String, Object> map = LangOps.arrayToMap(arrays);
		System.out.println("map:"+map);
		Assert.assertNotNull(map);
		Assert.assertEquals(Integer.valueOf(1), map.get("key1"));
		Assert.assertEquals("value2", map.get("key2"));

		arrays = new Object[]{"key1", 1, "key2", "value2", "key3"};
		map = LangOps.arrayToMap(arrays);
		System.out.println("map:"+map);
		Assert.assertTrue(map.size()==2);
		Assert.assertNotNull(map);
		Assert.assertEquals(Integer.valueOf(1), map.get("key1"));
		Assert.assertEquals("value2", map.get("key2"));
		Assert.assertFalse(map.containsKey("key3"));

		String[] keys = new String[]{"test1", "test3"};
		Map<String, Integer> arrayMap = LangOps.kvArrayToMap(keys,
															new Integer[]{111, 333});
		assertThat(arrayMap.size()).isEqualTo(keys.length);
		assertThat(arrayMap).containsKeys(keys[0], keys[1]);
	}

	@Test
	public void testSum(){
		BigDecimal total = LangOps.sumBigDecimal(null, BigDecimalBox::getValue);
		Assert.assertEquals(BigDecimal.valueOf(0.0), total);

		List<BigDecimalBox> datas = Lists.newArrayList();
		total = LangOps.sumBigDecimal(datas, BigDecimalBox::getValue);
		Assert.assertEquals(BigDecimal.valueOf(0.0), total);

		datas.add(new BigDecimalBox(1.5));
		datas.add(new BigDecimalBox(3.5));
		datas.add(new BigDecimalBox(5.0));
		datas.add(new BigDecimalBox(5.0));
		total = LangOps.sumBigDecimal(datas, BigDecimalBox::getValue);
		Assert.assertEquals(BigDecimal.valueOf(15.0), total);
	}

	@Test
	public void testParseTimeUnit(){
		Pair<Integer, TimeUnit> tu = LangOps.parseTimeUnit("11mis");
		assertThat(tu.getLeft()).isEqualTo(11);
		assertThat(tu.getRight()).isEqualTo(TimeUnit.MILLISECONDS);

		tu = LangOps.parseTimeUnit("11s");
		assertThat(tu.getLeft()).isEqualTo(11);
		assertThat(tu.getRight()).isEqualTo(TimeUnit.SECONDS);

		tu = LangOps.parseTimeUnit("11m");
		assertThat(tu.getLeft()).isEqualTo(11);
		assertThat(tu.getRight()).isEqualTo(TimeUnit.MINUTES);

		tu = LangOps.parseTimeUnit("101h");
		assertThat(tu.getLeft()).isEqualTo(101);
		assertThat(tu.getRight()).isEqualTo(TimeUnit.HOURS);

		tu = LangOps.parseTimeUnit("11d");
		assertThat(tu.getLeft()).isEqualTo(11);
		assertThat(tu.getRight()).isEqualTo(TimeUnit.DAYS);
	}

	@Test
	public void testParseSize(){
		int size = LangOps.parseSize("1kb");
		assertThat(size).isEqualTo(1024);

		size = LangOps.parseSize("1mb");
		assertThat(size).isEqualTo(1024*1024);

		size = LangOps.parseSize("1GB");
		assertThat(size).isEqualTo(1024*1024*1024);

		size = LangOps.parseSize("1k");
		assertThat(size).isEqualTo(1024);

		size = LangOps.parseSize("1M");
		assertThat(size).isEqualTo(1024*1024);

		size = LangOps.parseSize("1g");
		assertThat(size).isEqualTo(1024*1024*1024);
	}

	@Test
	public void testSort() {
		List<Integer> datas = Lists.newArrayList(3, 2, 44, 22, 77, 0, -23);
		// 升序
		datas.sort((d1, d2) -> d1 - d2);
		System.out.println("升序: " + datas);

		// 降序
		datas.sort((d1, d2) -> -(d1 - d2));
		System.out.println("降序: " + datas);

		// 升序
		datas.sort(Comparator.comparingInt(d->(Integer)d));
		System.out.println("升序: " + datas);

		// 降序
		datas.sort(Comparator.comparingInt(d->(Integer)d).reversed());
		System.out.println("降序: " + datas);
	}

	class BigDecimalBox {
		private BigDecimal value;

		public BigDecimalBox(double val) {
			super();
			this.value = BigDecimal.valueOf(val);
		}

		public BigDecimal getValue() {
			return value;
		}

	}
}


text:
ion is a multi-purpose, statically-typed programming language with a focus on productivity.

## Specification and examples

### Hello world

Here is a classic hello world in ion:
```
import "std/io"

func main() {
	std::io::println("Hello world!")
}
```

Any ion program starts at the main entry point and then executes linearly.

### Variable declaration
The syntax for variable declarations is:
```
var my_variable: string = "Hello"
```

The assignment part is optional only if the type is a primitive with a default value:

| Type   | Default value |
|--------|---------------|
| string | ""            |
| int    | 0             |
| bool   | false         |
| char   | '\0'          |

### Types

Along with the 4 primitive types previously cited and custom structs, the built-in types are:

| Type      | Syntax               |
|-----------|----------------------|
| array     | []type               |
| map       | [key_type]value_type |
| const ref | &type                |
| mut ref   | @type                |

### Var assignment
```
my_variable = "new text"
my_array[4] = "another value"
my_array[] = "new item in array"
my_ref = @some_var
*my_ref = "new content"
```

### Func declaration
```
func my_function(param1: Type1, param2: Type2 = "default_value") -> ReturnType {
	...
}
```

### Struct declaration
```
struct MyStruct {
	field1: Type1,
	field2: Type2
}
```

### Struct init
```
var my_var: MyStruct = new MyStruct {
	field1: value1,
	field2: value2
}
```

### Func call
```
var my_return: ReturnType = my_function(arg1, arg2)
```

### Struct field access
```
std::io::println(my_struct.field1)
```

### If/else if/else
```
if condition {
	...
} else if other_condition {
	...
} else {
	...
}
```

### While
```
while condition {
	...
}
```

### For..in
```
for item in my_array {
	...
}

for char in my_string {
	...
}
```

### Imports
```
import "relative/path/to/file"

func main {
	relative::path::to::file::my_function()
}
```

### Standard library

#### Global/built-in
 * `print(any)`
 * `readln() -> string`

#### std::io
 * `std::io::println(string)`
 * `std::io::read_int() -> int`

#### std::conv
 * `std::conv::char_to_int(char) -> int`
 * `std::conv::str_to_int(string) -> int`

#### std::math
 * `std::math::pow(int, int) -> int`

## Usage
```
ion my_source_file.ion
```

Note: for now, your files have to be placed alongside the executable, as well as the std folder.


text:
package br.org.piblimeira.app.view;

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
import javax.xml.bind.ValidationException;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import br.org.piblimeira.domain.Pessoa;
import br.org.piblimeira.domain.TipoMembro;
import br.org.piblimeira.enuns.EnumCaminhoPagina;
import br.org.piblimeira.form.TipoMembroForm;
import br.org.piblimeira.repository.PessoaRepository;
import br.org.piblimeira.repository.TipoMembroRepository;

@Named
@ViewScoped
public class TipoMembroCtrl extends BaseController {

	private static final long serialVersionUID = -4524378806386943530L;

	private TipoMembroForm tipoMembroForm;

	@Autowired
	private TipoMembroRepository tipoMembroRepository;

	@Autowired
	private PessoaRepository pessoaRepository;

	@PostConstruct
    public void init() {
		instanciarTipoMembro();
		listarTiposMembros();

		TipoMembro tipoMembro = getFromSession("tipoMembro");
		if(tipoMembro != null){
			tipoMembroForm.setTipoMembro(tipoMembro);
			removeFromSession("tipoMembro");
		}
	}

	public void listarTiposMembros(){
		tipoMembroForm.setListaTiposMembros(tipoMembroRepository.buscarTodos());
	}
	private void instanciarTipoMembro(){
		tipoMembroForm = new TipoMembroForm();
		tipoMembroForm.setTipoMembro(new TipoMembro());
		tipoMembroForm.setListaTiposMembros(new ArrayList<>());
	}

	public void editar(TipoMembro tipo){
		addToSession("tipoMembro", tipo);
		irParaIncluir();
	}

	public void excluir(TipoMembro tipo){
		try{
			validarExclusao(tipo);
			tipoMembroRepository.delete(tipo.getId());
			listarTiposMembros();
		}catch(ValidationException e){
			exibeMensagem("Atenção!", e.getMessage());
		}
	}
	 private void validarExclusao(TipoMembro tipo) throws ValidationException{
		 List<Pessoa> membros = pessoaRepository.buscarPessoaPorTipoMembro(tipo.getId());
		 if(membros != null && !membros.isEmpty()){
			 throw new ValidationException(getMessageByKey("msg.tipo.membro.nao.pode.excluir"));
		 }

	 }
	public void irParaManter(){
		redirect(EnumCaminhoPagina.MANTER_TP_MEMBRO.getCaminho());
	}

	public void irParaIncluir(){
		redirect(EnumCaminhoPagina.EDITAR_TP_MEMBRO.getCaminho());
	}

	private void validarSalvar() throws ValidationException{
		if(StringUtils.isEmpty(tipoMembroForm.getTipoMembro().getTpMembro().trim())){
			throw new ValidationException(getMessageByKey("msg.tipo.membro.obrigatorio"));
		}
		TipoMembro tipo = tipoMembroRepository.buscarPorNome(tipoMembroForm.getTipoMembro().getTpMembro().trim().toUpperCase());
		if((tipoMembroForm.getTipoMembro().getId() == null && tipo != null) ||
			(tipo != null && !tipoMembroForm.getTipoMembro().getId().equals(tipo.getId()))){
			throw new ValidationException(getMessageByKey("tipo.membro.ja.cadastrado"));
		}
	}

	public void salvar(){
		try{
				validarSalvar();
				tipoMembroRepository.save(tipoMembroForm.getTipoMembro());
				setMensagemOk(getMessageByKey("msg.informacoes.salvas.com.sucesso"));
				setHeader(getMessageByKey("msg.confirmacao"));
				RequestContext.getCurrentInstance().execute("PF('modalOk').show()");
		}catch(ValidationException e){
			exibeMensagem(getMessageByKey("msg.atencao"), e.getMessage());
		}
	}

	public TipoMembroForm getTipoMembroForm() {
		return tipoMembroForm;
	}

	public void setTipoMembroForm(TipoMembroForm tipoMembroForm) {
		this.tipoMembroForm = tipoMembroForm;
	}

}


text:
class Estimate < ActiveRecord::Base
  belongs_to :candidate

  def self.latest_dem_chart
    Pollster::Chart.where(:topic => '2016-president-dem-primary').first.estimates
  end

  def self.latest_gop_chart
    Pollster::Chart.where(:topic => '2016-president-gop-primary').first.estimates
  end

  def self.load_iowa
    Pollster::Chart.where(:topic => '2016-president-dem-primary')[1]
  end

  #Add all poll dates to hash
  def self.populate_date_hash(state_estimate, candidates)
  return_hash = {}
   self.load_iowa.estimates_by_date.each do |estimate|
      return_hash[estimate[:date]] = candidates.collect {|candidate| {candidate.to_sym => nil}}
      return_hash[estimate[:date]]
    end
    self.convert_to_hash(return_hash)
  end

  #Takes a hash with values that are an array of hashes and converts to one hash
  def self.convert_to_hash(input_hash)
     return_hash = {}
     input_hash.each do |date, can_array|
      return_hash[date] = can_array.reduce Hash.new, :merge
    end
    return_hash
  end

  #candidates is an array
  def self.custom_matchup(candidates)
    state = self.load_iowa
    return_hash = self.populate_date_hash(state, candidates)

    #add polls numbers for the candidates to the hash
    candidates.each do |candidate|
      state.estimates_by_date.each do |estimate|
        return_hash.each do |k,v|
          if k == estimate[:date]
             estimate[:estimates].each do |hash|
              if hash[:choice] == candidate
                return_hash[estimate[:date]][candidate.to_sym] = hash[:value]
              end
            end
          end
        end
      end
    end
    return_hash
  end

  #must be uppercase
  def self.make_chart_array(candidate, custom_matchup)
    holder = []
    custom_matchup.each do |date,can_hash|
      can_hash.each do |k,v|
        if k == candidate.to_sym
          holder << v.to_f
        end
      end
    end
    holder.push(candidate).reverse
  end

end


text:
public function setCroppable<?php echo $image_column; ?>($data)
{
    if (!is_array($data)) {
        $data = array();
    }

    if (!isset($data['image'])) {
        $data['image'] = null;
    }

    if (!isset($data['coordinates'])) {
        $data['coordinates'] = null;
    }

    $this->set<?php echo $image_column; ?>($data['image']);
    $this->set<?php echo $coordinates_column; ?>($data['coordinates']);
}


text:
package com.google.gwt.inject.rebind.adapter;

import com.google.gwt.inject.client.binder.GinAnnotatedBindingBuilder;
import com.google.gwt.inject.client.binder.GinLinkedBindingBuilder;
import com.google.gwt.inject.client.binder.GinScopedBindingBuilder;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;

import java.lang.annotation.Annotation;

import javax.inject.Provider;

class AnnotatedBindingBuilderAdapter<T> implements GinAnnotatedBindingBuilder<T> {
  private final AnnotatedBindingBuilder<T> annotatedBindingBuilder;

  public AnnotatedBindingBuilderAdapter(AnnotatedBindingBuilder<T> annotatedBindingBuilder) {
    this.annotatedBindingBuilder = annotatedBindingBuilder;
  }

  public <I extends T> GinScopedBindingBuilder to(Class<I> implementation) {
    return new ScopedBindingBuilderAdapter(annotatedBindingBuilder.to(implementation));
  }

  public <I extends T> GinScopedBindingBuilder to(TypeLiteral<I> implementation) {
    return new ScopedBindingBuilderAdapter(annotatedBindingBuilder.to(implementation));
  }

  public <I extends T> GinScopedBindingBuilder to(Key<I> targetKey) {
    return new ScopedBindingBuilderAdapter(annotatedBindingBuilder.to(targetKey));
  }

  public <I extends Provider<? extends T>> GinScopedBindingBuilder toProvider(Key<I> providerKey) {
    return new ScopedBindingBuilderAdapter(annotatedBindingBuilder.toProvider(providerKey));
  }

  public <I extends Provider<? extends T>> GinScopedBindingBuilder toProvider(
      Class<I> provider) {
    return new ScopedBindingBuilderAdapter(annotatedBindingBuilder.toProvider(provider));
  }

  public GinLinkedBindingBuilder<T> annotatedWith(Class<? extends Annotation> annotation) {
    return new LinkedBindingBuilderAdapter<T>(
        annotatedBindingBuilder.annotatedWith(annotation));
  }

  public GinLinkedBindingBuilder<T> annotatedWith(Annotation annotation) {
    return new LinkedBindingBuilderAdapter<T>(
        annotatedBindingBuilder.annotatedWith(annotation));
  }

  public void asEagerSingleton() {
    GwtDotCreateProvider.bind(annotatedBindingBuilder).asEagerSingleton();
  }

  public void in(Class<? extends Annotation> scopeAnnotation) {
    GwtDotCreateProvider.bind(annotatedBindingBuilder).in(scopeAnnotation);
  }

}


text:
Courses = new Meteor.Collection("courses");

Rounds = new Meteor.Collection("rounds", {
    transform: function(round) {
        round.code = getRoundCourseCode(round);
        return round;
    }
});

Appointments = new Meteor.Collection("appointments", {
    transform: function (appointment) {
        //normal users are not abble to reserve/cancell this appointment after
        // previous day clock 18
        var editEnds = moment(appointment.start).subtract('days', 1).startOf('day').hour(18).toDate();
        appointment.editEnds = editEnds;
        appointment.code = getAppointmentCourseCode(appointment);
        if(appointment.student) {
            appointment.color = 'red';
            appointment.reserved = true;
        }
        return appointment;
    }
});

var getAppointmentCourseCode = function(appointment) {
    var round = Rounds.findOne(appointment.round);
    if (round) {
        var course = Courses.findOne(round.course);
        return course.code;
    }
};

var getRoundCourseCode = function(round) {
    var course = Courses.findOne(round.course);
    if (course) {
        return course.code;
    }
    return null;
};


text:
'use strict';

var program = require('commander'),
	cli = {};

var createCommand = function( command ){

	program.command(command._info.flags[0])
		.action(command)
		.description(command._info.shortDesc);

	// has short
	if ( command._info.Short ) {
		cli[command._info.Short] = command;
		program.command(command._info.flags[0].replace( command._info.name, command._info.Short))
			.action(command)
			.description('like `'+command._info.name+'`, just short');
	}

};

cli.init = require('./init.js');
createCommand(cli.init);

cli.lib = require('./lib.js');
createCommand(cli.lib);

cli.widget = require('./widget.js');
createCommand(cli.widget);

cli.common = require('./common.js');
createCommand(cli.common);

cli.biz = require('./biz.js');
createCommand(cli.biz);

cli.build = require('./build.js');
createCommand(cli.build);

cli.timestamp = require('./timestamp.js');
createCommand(cli.timestamp);

cli.dev = require('./dev.js');
createCommand(cli.dev);

cli.config = require('./config.js');
createCommand(cli.config);

cli.ver = require('./ver.js');
createCommand(cli.ver);

cli.fix = require('./fix.js');
createCommand(cli.fix);

cli.open = require('./open.js');
createCommand(cli.open);

// cli.cache = require('./cache.js');
// createCommand(cli.cache);

cli.help = require('./help.js');
createCommand(cli.help);

module.exports = cli;


text:
var myLayout;

$(document).ready(function () {
	// this layout could be created with NO OPTIONS - but showing some here just as a sample...
	// myLayout = $('body').layout(); -- syntax with No Options
	myLayout = $('div.container').layout({

	//	reference only - these options are NOT required because 'true' is the default
		closable:					true	// pane can open & close
	,	resizable:					true	// when open, pane can be resized
	,	slidable:					true	// when closed, pane can 'slide' open over other panes - closes on mouse-out
	,	livePaneResizing:			true
	//	enable state management - saves the size of the pane if resized
	,	stateManagement__enabled:	false // automatic cookie load & save enabled by default
	,	showDebugMessages:			true // log and/or display messages from debugging & testing code

	,	center__paneSelector:	".outer-center"
	,	east__paneSelector:		".outer-east"

		// INNER-LAYOUT (child of middle-center-pane)
	,	center__childOptions: {
			center__paneSelector:	".inner-center"
		,	south__paneSelector:	".inner-south"
		,	south__size:			.2
		,	south__maxSize:			.75
		,	south__minSize:			.10
		,	spacing_open:			10  // ALL panes
		,	spacing_closed:			10  // ALL panes
		,	south__spacing_closed:	12
		}

		// OUTER-LAYOUT spacing options (size of the resize bars)
	,	spacing_open:			10  // ALL panes
	,	spacing_closed:			12  // ALL panes

	//	some pane-size settings
	,	east__size:					410
	,	east__minSize:				.1
	,	east__maxSize:				.75 // 50% of layout width
	});
});


text:
/**
 * Created by long on 15-3-6.
 */

var UIInput = BaseScene.extend({
    onEnter:function(){
        this._super();
        var ui = flax.assetsManager.createDisplay(res.uiInput, "InputPanel",{parent:this});
        //password input
        ui['pswTxt'].setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD);
        ui['pswTxt'].setMaxLength(12);
        //set the placeholder font color
        ui['telTxt'].setPlaceholderFontColor(cc.color(51, 51, 51));
        //The input text is just EditBox, so you can do anything the EditBox can do
        ui['telTxt'].setDelegate(this);
    },
    editBoxEditingDidBegin: function (editBox) {
        cc.log(editBox.name + " DidBegin!");
    },
    editBoxEditingDidEnd: function (editBox) {
        cc.log(editBox.name + " DidEnd: " + editBox.getString());
    },
    editBoxTextChanged: function (editBox, text) {
        cc.log(editBox.name + " , TextChanged, text: " + text);
    },
    editBoxReturn: function (editBox) {
        cc.log(editBox.name + " was returned!");
    }
})


text:
package com.datastax.driver.core;

/**
 * A value for a User Defined Type.
 */
public class UDTValue extends AbstractData<UDTValue> {

    private final UserType definition;

    UDTValue(UserType definition) {
        // All things in a UDT are encoded with the protocol v3
        super(ProtocolVersion.V3, definition.size());
        this.definition = definition;
    }

    protected DataType getType(int i) {
        return definition.byIdx[i].getType();
    }

    protected String getName(int i) {
        return definition.byIdx[i].getName();
    }

    protected int[] getAllIndexesOf(String name) {
        int[] indexes = definition.byName.get(Metadata.handleId(name));
        if (indexes == null)
            throw new IllegalArgumentException(name + " is not a field defined in this UDT");
        return indexes;
    }

    /**
     * The UDT this is a value of.
     *
     * @return the UDT this is a value of.
     */
    public UserType getType() {
        return definition;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof UDTValue))
            return false;

        UDTValue that = (UDTValue) o;
        if (!definition.equals(that.definition))
            return false;

        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                sb.append(", ");

            sb.append(getName(i));
            sb.append(":");
            DataType dt = getType(i);
            sb.append(values[i] == null ? "null" : dt.format(dt.deserialize(values[i], ProtocolVersion.V3)));
        }
        sb.append("}");
        return sb.toString();
    }
}