text:
package net.glowstone.block.blocktype;

import net.glowstone.EventFactory;
import net.glowstone.GlowWorld;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.entity.GlowPlayer;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Vine;
import org.bukkit.util.Vector;

import java.util.Arrays;
import java.util.Collection;

public class BlockVine extends BlockClimbable {

    private static final BlockFace[] FACES = {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.DOWN, BlockFace.UP};
    private static final BlockFace[] HORIZONTAL_FACES = {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};

    private static BlockFace getClockwiseFace(BlockFace face) {
        switch (face) {
            case NORTH:
                return BlockFace.EAST;
            case SOUTH:
                return BlockFace.WEST;
            case EAST:
                return BlockFace.SOUTH;
            case WEST:
                return BlockFace.NORTH;
            default:
                return BlockFace.NORTH;
        }
    }

    private static BlockFace getCounterClockwiseFace(BlockFace face) {
        switch (face) {
            case NORTH:
                return BlockFace.WEST;
            case SOUTH:
                return BlockFace.EAST;
            case EAST:
                return BlockFace.NORTH;
            case WEST:
                return BlockFace.SOUTH;
            default:
                return BlockFace.NORTH;
        }
    }

    @Override
    public boolean canPlaceAt(GlowBlock block, BlockFace against) {
        switch (against) {
            case NORTH:
            case SOUTH:
            case EAST:
            case WEST:
                return block.getRelative(against.getOppositeFace()).getType().isSolid();
            case UP:
                return block.getRelative(against).getType().isSolid();
            default:
                return false;
        }
    }

    @Override
    public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) {
        super.placeBlock(player, state, face, holding, clickedLoc);

        MaterialData data = state.getData();
        if (data instanceof Vine) {
            if (face == BlockFace.DOWN || face == BlockFace.UP) {
                return;
            } else {
                ((Vine) data).putOnFace(face.getOppositeFace());
            }
            state.setData(data);
        } else {
            warnMaterialData(Vine.class, data);
        }
    }

    @Override
    public boolean canAbsorb(GlowBlock block, BlockFace face, ItemStack holding) {
        return true;
    }

    @Override
    public boolean canOverride(GlowBlock block, BlockFace face, ItemStack holding) {
        return true;
    }

    @Override
    public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
        if (tool != null && tool.getType() == Material.SHEARS)
            return Arrays.asList(new ItemStack(Material.VINE));

        return BlockDropless.EMPTY_STACK;
    }

    @Override
    public boolean canTickRandomly() {
        return true;
    }

    @Override
    public void updateBlock(GlowBlock block) {
        if (random.nextInt(4) == 0) {
            GlowBlockState state = block.getState();
            MaterialData data = state.getData();
            if (data instanceof Vine) {
                Vine vine = (Vine) data;
                boolean hasNearVineBlocks = hasNearVineBlocks(block);
                BlockFace face = FACES[random.nextInt(FACES.length)];
                if (block.getY() < 255 && face == BlockFace.UP && block.getRelative(face).isEmpty()) {
                    if (!hasNearVineBlocks) {
                        Vine v = (Vine) data;
                        for (BlockFace f : HORIZONTAL_FACES) {
                            if (random.nextInt(2) == 0 || !block.getRelative(f).getRelative(face).getType().isSolid()) {
                                v.removeFromFace(f);
                            }
                        }
                        putVineOnHorizontalBlockFace(block.getRelative(face), v, block);
                    }
                } else if (Arrays.asList(HORIZONTAL_FACES).contains(face) && !vine.isOnFace(face)) {
                    if (!hasNearVineBlocks) {
                        GlowBlock b = block.getRelative(face);
                        if (b.isEmpty()) {
                            BlockFace fcw = getClockwiseFace(face);
                            BlockFace fccw = getCounterClockwiseFace(face);
                            GlowBlock bcw = b.getRelative(fcw);
                            GlowBlock bccw = b.getRelative(fccw);
                            boolean isOnCWFace = vine.isOnFace(fcw);
                            boolean isOnCCWFace = vine.isOnFace(fccw);
                            if (isOnCWFace && bcw.getType().isSolid()) {
                                putVine(b, new Vine(fcw), block);
                            } else if (isOnCCWFace && bccw.getType().isSolid()) {
                                putVine(b, new Vine(fccw), block);
                            } else if (isOnCWFace && bcw.isEmpty() && block.getRelative(fcw).getType().isSolid()) {
                                putVine(bcw, new Vine(face.getOppositeFace()), block);
                            } else if (isOnCCWFace && bccw.isEmpty() && block.getRelative(fccw).getType().isSolid()) {
                                putVine(bccw, new Vine(face.getOppositeFace()), block);
                            } else if (b.getRelative(BlockFace.UP).getType().isSolid()) {
                                putVine(b, new Vine(), block);
                            }
                        } else if (b.getType().isOccluding()) {
                            vine.putOnFace(face);
                            putVine(block, vine, null);
                        }
                    }
                } else if (block.getY() > 1) {
                    GlowBlock b = block.getRelative(BlockFace.DOWN);
                    Vine v = (Vine) data;
                    if (b.getType() == Material.VINE || b.isEmpty()) {
                        for (BlockFace f : HORIZONTAL_FACES) {
                            if (random.nextInt(2) == 0) {
                                v.removeFromFace(f);
                            }
                        }
                        putVineOnHorizontalBlockFace(b, v, b.isEmpty() ? block : null);
                    }
                }
            } else {
                warnMaterialData(Vine.class, data);
            }
        }
    }

    private void putVine(GlowBlock block, Vine vine, GlowBlock fromBlock) {
        GlowBlockState state = block.getState();
        state.setType(Material.VINE);
        state.setData(vine);
        if (fromBlock != null) {
            BlockSpreadEvent spreadEvent = new BlockSpreadEvent(block, fromBlock, state);
            EventFactory.callEvent(spreadEvent);
            if (!spreadEvent.isCancelled()) {
                state.update(true);
            }
        } else {
            state.update(true);
        }
    }

    private void putVineOnHorizontalBlockFace(GlowBlock block, Vine vine, GlowBlock fromBlock) {
        boolean isOnHorizontalFace = false;
        for (BlockFace f : HORIZONTAL_FACES) {
            if (vine.isOnFace(f)) {
                isOnHorizontalFace = true;
                break;
            }
        }
        if (isOnHorizontalFace) {
            putVine(block, vine, fromBlock);
        }
    }

    private boolean hasNearVineBlocks(GlowBlock block) {
        GlowWorld world = block.getWorld();
        int vineCount = 0;
        for (int x = 0; x < 9; x++) {
            for (int z = 0; z < 9; z++) {
                for (int y = 0; y < 3; y++) {
                    if (world.getBlockAt(block.getLocation().add(x - 4, y - 1, z - 4)).getType() == Material.VINE) {
                        if (++vineCount >= 5) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}


text:
  Arbin est
       un village
       géographiquement positionné dans le département de Savoie en Rhône-Alpes. On dénombrait 752 habitants en 2008.

À coté de Arbin sont localisées les communes de
Montmélian située à 0 km, 3 933 habitants,
Les Mollettes localisée à 4 km, 636 habitants,
Saint-Pierre-de-Soucy à 3 km, 380 habitants,
Sainte-Hélène-du-Lac localisée à 2 km, 646 habitants,
Francin localisée à 2 km, 816 habitants,
Villard-d'Héry localisée à 5 km, 233 habitants,
 entre autres. De plus, Arbin est située à seulement treize km de Chambéry.

Le nombre d'habitations, à Arbin, se décomposait en 2011 en 84 appartements et 286 maisons soit
 un marché plutôt équilibré.

À Arbin, la valorisation moyenne à l'achat d'un appartement s'évalue à 2 283 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 117 € du m². À la location la valeur moyenne se situe à 11,15 € du m² par mois.

Si vous pensez demenager à Arbin, vous pourrez facilement trouver une maison à vendre.

redpajama_set_name: RedPajamaGithub


text:
package top.littlerich.virtuallocation.listener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;

import top.littlerich.virtuallocation.activity.MainActivity;

import static top.littlerich.virtuallocation.activity.MainActivity.myGpslatitude;
import static top.littlerich.virtuallocation.activity.MainActivity.myGpslongitude;
import static top.littlerich.virtuallocation.activity.MainActivity.setCurrentMapLatLng;

/**
 * 定位结果回调
 * API: http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/getloc
 * Created by xuqingfu on 2017/5/3.
 */

public class AsyncLocationResultListener implements BDLocationListener {

    private MapView mMapView;
    boolean isFirstLoc = true;// 是否首次定位
    //private double myGpslatitude, myGpslongitude;

    public AsyncLocationResultListener(MapView mapView, boolean isFirstLoc) {
        mMapView = mapView;
        this.isFirstLoc = isFirstLoc;
        //this.myGpslatitude = myGpslatitude;
      //  this.myGpslongitude = myGpslongitude;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        // map view 销毁后不在处理新接收的位置
        if (location == null || mMapView == null) {
            return;
        }

        if (isFirstLoc) {
            isFirstLoc = false;
            MainActivity.myGpslatitude = location.getLatitude();
            MainActivity.myGpslongitude = location.getLongitude();
            LatLng ll = new LatLng(myGpslatitude, myGpslongitude);
            setCurrentMapLatLng(ll);
        }
    }
}


text:
<?php

namespace MEMORAe\TextBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class MediaEntityType extends AbstractType
{
    private $type;
    private $pageId;
    private $language;
    public function __construct($type, $pageId, $language = null){
        $this->type = $type;
        $this->pageId = $pageId;
        $this->language = $language;
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        if($this->type != "text"){
            $builder->add('name', 'text');

            if($this->type == "video"){
                $builder->add('path', 'text', array('required' => false));
            }

            if($this->type == "file" || $this->type == "img"){
                $builder->add('file', 'file', array('required' => false));
            }
        }

        if($this->pageId != null && $this->pageId != 100 && $this->pageId >= 5){
            $builder->add('section', 'entity', array(
                'class' => 'MEMORAeTextBundle:SectionEntity',
                'property' => 'name',
                'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('s')
                        ->where('s.page = :id and s.language = :language')
                        ->setParameter('id', $this->pageId)
                        ->setParameter('language', $this->language)
                        ->orderBy('s.id', 'ASC');
                },
            ));
        }
        if($this->type != "img"){
            $builder->add('content', 'ckeditor');
        }

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MEMORAe\TextBundle\Entity\MediaEntity',
            'class'=>'form-horizontal'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'memorae_textbundle_mediaentity';
    }
}


text:
Removes a taxonomy term group and all its containing termsets
## Syntax
```powershell
Remove-PnPTermGroup -GroupName <String>
                    [-TermStoreName <String>]
                    [-Force [<SwitchParameter>]]
```

## Parameters
Parameter|Type|Required|Description
---------|----|--------|-----------
|GroupName|String|True|Name of the taxonomy term group to delete.|
|Force|SwitchParameter|False||
|TermStoreName|String|False|Term store to use; if not specified the default term store is used.|


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace ZptSharp.Expressions.NotExpressions
{
    /// <summary>
    /// An implementation of <see cref="IEvaluatesExpression"/> which evaluates TALES 'nots' expressions.
    /// </summary>
    public class NotExpressionEvaluator : IEvaluatesExpression
    {
        readonly ICoercesValueToBoolean valueConverter;
        readonly IEvaluatesExpression evaluator;
        readonly ILogger logger;

        /// <summary>
        /// Evaluates the expression asynchronously and returns the result.
        /// </summary>
        /// <returns>The expression result.</returns>
        /// <param name="expression">The expression string.</param>
        /// <param name="context">The expression context.</param>
        /// <param name="cancellationToken">An optional cancellation token.</param>
        public async Task<object> EvaluateExpressionAsync(string expression, ExpressionContext context, CancellationToken cancellationToken = default)
        {
            var innerExpressionResult = await evaluator.EvaluateExpressionAsync(expression, context, cancellationToken)
                .ConfigureAwait(false);

            if(logger.IsEnabled(LogLevel.Trace))
                logger.LogTrace(@"Not evaluator inverting {inner_result}", innerExpressionResult);

            var booleanResult = valueConverter.CoerceToBoolean(innerExpressionResult);
            return !booleanResult;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NotExpressionEvaluator"/> class.
        /// </summary>
        /// <param name="valueConverter">Value converter.</param>
        /// <param name="evaluator">Evaluator.</param>
        /// <param name="logger">Logger</param>
        public NotExpressionEvaluator(ICoercesValueToBoolean valueConverter,
                                      IEvaluatesExpression evaluator,
                                      ILogger<NotExpressionEvaluator> logger)
        {
            this.valueConverter = valueConverter ?? throw new ArgumentNullException(nameof(valueConverter));
            this.evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
    }
}


text:
function set_vc_from_bat($arch) {
    $vc_env = "vcvars$arch.bat"
    echo "Load MSVC environment $vc_env"
    if (Get-Command $vc_env -errorAction SilentlyContinue)
    {
        ## Store the output of cmd.exe. We also ask cmd.exe to output
        ## the environment table after the batch file completes
        ## Go through the environment variables in the temp file.
        ## For each of them, set the variable in our local environment.
        cmd /Q /c "$vc_env && set" 2>&1 | Foreach-Object {
            if ($_ -match "^(.*?)=(.*)$") {
                Set-Content "env:\$($matches[1])" $matches[2]
            }
        }

        echo "Successfully finished"
    }
    else {
        echo "Cannot find vcvars.bat for your arch '$arch'"
    }
}

# Setups environment using vswhere
# Check VsDevCmd.bat -? for available architectures
function set_vc($arch) {
    echo "Loading MSVC environment $arch..."

    if (Get-Command vswhere -ErrorAction SilentlyContinue) {
        $vswhere_path = Get-Command vswhere | Select-Object -ExpandProperty Definition
    } elseif (Test-Path("${Env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe")) {
        $vswhere_path = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
    } elseif (Test-Path("${Env:ProgramFiles}\Microsoft Visual Studio\Installer\vswhere.exe")) {
        $vswhere_path = "${Env:ProgramFiles}\Microsoft Visual Studio\Installer\vswhere.exe"
    } else {
        echo "vswhere.exe is not available in PATH. Cannot load"
        return
    }

    echo "Using vswhere: $vswhere_path"

    $installPath = (& "$vswhere_path" -products * -latest -property installationpath)
    echo "Found msvc installation: $installPath"

    Import-Module (Join-Path $installPath "Common7\Tools\Microsoft.VisualStudio.DevShell.dll")
    $null = Enter-VsDevShell -SkipAutomaticLocation -VsInstallPath $installPath -Arch $arch -HostArch $arch
}


text:
using Contracts.Infrastructure;
using iQuarc.AppBoot;

namespace Quotations.Services
{
    [Service(nameof(QuotationsModule), typeof(IModule))]
    class QuotationsModule : IModule
    {
        private readonly IModulesHostContainer container;

        public QuotationsModule(IModulesHostContainer container)
        {
            this.container = container;
        }

        public void Initialize()
        {
            container.RegisterModule("Quotations Module");
        }
    }
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Memployee extends CI_Model
{

    public $table = 'employee';
    public $id = 'id';
    public $order = 'DESC';

    function __construct()
    {
        parent::__construct();
    }

    // get all
    function get_all()
    {
        //$this->db->order_by($this->id, $this->order);
        $this->db->where('deleted',0);
        $this->db->order_by('firstName','ASC');
        return $this->db->get($this->table)->result();
    }

     function get_dropdown()
    {
         $this->db->select('id, firstName, lastName, costRate, (select positionName from position where position.Id = employee.positionId limit 1) as positionName, (select userlevelId from users where employeeId = employee.id limit 1) as userlevelId');
            $this->db->from('employee');
            $this->db->where('deleted',0);
            $this->db->order_by('firstName','ASC');
            $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
       // return $this->db->get($this->table)->result();
    }

     function get_dropdown2()
    {
         $this->db->select('id, firstName, lastName, costRate, (select userlevelId from users where employeeId = employee.id limit 1) as userlevelId');
            $this->db->from('employee');
            $this->db->where('deleted',0);
            $this->db->order_by('firstName','ASC');
            $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
       // return $this->db->get($this->table)->result();
    }

    // get data by id
    function get_by_id($id)
    {
        $this->db->where($this->id, $id);
        return $this->db->get($this->table)->row();
    }

    // get total rows
    function total_rows($q = NULL) {
        $this->db->like('id', $q);

	$this->db->from($this->table);
        return $this->db->count_all_results();
    }

    // get data with limit and search
    function get_limit_data($limit, $start = 0, $q = NULL) {
        $this->db->order_by($this->id, $this->order);

	$this->db->limit($limit, $start);
        return $this->db->get($this->table)->result();
    }

    function getData($limit, $start = 0, $q = NULL) {
       // $this->db->order_by($this->id, $this->order);
        //$this->db->like('id', $q);
	$this->db->limit($limit, $start);

         $this->db->select('a.*,d.groupName,b.employeeStatus,b.employeeStatusColors,c.positionName');
            $this->db->from('employee a');
            $this->db->join('employee_status b', 'b.id = a.employeeStatusId', 'left');
            $this->db->join('position c', 'c.id = a.positionId', 'left');
            $this->db->join('position_group d', 'c.positionGroup = d.id', 'left');
            //$this->db->join('employee c2', 'c2.id=a.managerId', 'left');
            $this->db->order_by('a.updateDate','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

    public function dropdown_level($level)
    {
        //$level = 4;
         $this->db->select('a.*,b.positionName,b.positionGroup,c.groupName');
            $this->db->from('employee a');
            $this->db->join('position b', 'a.positionId = b.id', 'left');
            $this->db->join('position_group c', 'b.positionGroup = c.id', 'left');
            $this->db->where("b.positionGroup", $level);
           // $this->db->where("a.active", 1);
            $this->db->group_by('a.id');
            $this->db->order_by('a.firstName','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

    public function dropdown_partner()
    {
         $this->db->select('a.username,a.userlevelId,CONCAT(b.firstName,b.lastName) as fullname, b.costRate');
            $this->db->from('users a');
            $this->db->join('employee b', 'a.employeeId = b.id', 'left');
            $this->db->where("a.userlevelId", 3);
            $this->db->where("a.active", 1);
            $this->db->order_by('username','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

     public function dropdown_manager()
    {
         $this->db->select('a.username,a.userlevelId,CONCAT(b.firstName,b.lastName) as fullname, b.costRate');
            $this->db->from('users a');
            $this->db->join('employee b', 'a.employeeId = b.id', 'left');
            $this->db->where("a.userlevelId", 4);
            $this->db->where("a.active", 1);
            $this->db->order_by('username','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

     public function dropdown_hrd()
    {
         $this->db->select('a.username,a.userlevelId,CONCAT(b.firstName,b.lastName) as fullname, b.costRate');
            $this->db->from('users a');
            $this->db->join('employee b', 'a.employeeId = b.id', 'left');
            $this->db->where("a.userlevelId", 5);
            $this->db->where("a.active", 1);
            $this->db->order_by('username','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }
    public function dropdown_staff()
    {
         $this->db->select('a.username,a.userlevelId,CONCAT(b.firstName,b.lastName) as fullname, b.costRate');
            $this->db->from('users a');
            $this->db->join('employee b', 'a.employeeId = b.id', 'left');
            $this->db->where("a.userlevelId", 6);
            $this->db->where("a.active", 1);
            $this->db->order_by('username','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

    public function getDropDown()
    {
         $this->db->select('id,firstname,lastname');
            $this->db->from('employee');
             $this->db->where("deleted", 0);
            $this->db->order_by('firstName','DESC');

        $query = $this->db->get();
        if ($query->num_rows() > 0)
            {
                 return $query->result();
            }
    }

    // insert data
    function insert($data)
    {
        $this->db->insert($this->table, $data);
    }

    // update data
    function update($id, $data)
    {
        $this->db->where($this->id, $id);
        $this->db->update($this->table, $data);
    }

    // delete data
    function delete($id)
    {
        $this->db->where($this->id, $id);
        $this->db->delete($this->table);
    }
    public function add_import($data_user){

        $this->db->insert($this->table, $data_user);

   }

}

/* End of file Memployee.php */
/* Location: ./application/models/Memployee.php */
/* Please DO NOT modify this information : */
/* Generated by Harviacode Codeigniter CRUD Generator 2016-03-21 20:29:03 */
/* http://harviacode.com */


text:
using std::map;
using std::multimap;
using std::set;
using std::string;
using std::vector;

// Tests that booleans are jsonified correctly.
TEST(JsonifyTest, Boolean) {
  EXPECT_EQ("true", string(jsonify(true)));
  EXPECT_EQ("false", string(jsonify(false)));
}

// Tests that `JSON::Boolean`s are jsonified correctly.
TEST(JsonifyTest, JSONBoolean) {
  EXPECT_EQ("true", string(jsonify(JSON::True())));
  EXPECT_EQ("false", string(jsonify(JSON::False())));

  EXPECT_EQ("true", string(jsonify(JSON::Boolean(true))));
  EXPECT_EQ("false", string(jsonify(JSON::Boolean(false))));
}

// Tests that `JSON::Boolean`s wrapped in `JSON::Value` are
// jsonified correctly.
TEST(JsonifyTest, JSONBooleanValue) {
  EXPECT_EQ("true", string(jsonify(JSON::Value(true))));
  EXPECT_EQ("false", string(jsonify(JSON::Value(false))));
}

// Tests that numbers are jsonified correctly.
TEST(JsonifyTest, Number) {
  // Test whole numbers (as doubles).
  EXPECT_EQ("0.0", string(jsonify(0.0)));
  EXPECT_EQ("1.0", string(jsonify(1.0)));

  // Negative.
  EXPECT_EQ("-1.0", string(jsonify(-1.0)));

  // Test integers.
  EXPECT_EQ("0", string(jsonify(0)));
  EXPECT_EQ("2", string(jsonify(2)));
  EXPECT_EQ("-2", string(jsonify(-2)));

  // Expect at least 15 digits of precision.
  EXPECT_EQ("1234567890.12345", string(jsonify(1234567890.12345)));
}

// Tests that `JSON::Number`s are jsonified correctly.
TEST(JsonifyTest, JSONNumber) {
  // Test whole numbers (as doubles).
  EXPECT_EQ("0.0", string(jsonify(JSON::Number(0.0))));
  EXPECT_EQ("1.0", string(jsonify(JSON::Number(1.0))));

  // Negative.
  EXPECT_EQ("-1.0", string(jsonify(JSON::Number(-1.0))));

  // Test integers.
  EXPECT_EQ("0", string(jsonify(JSON::Number(0))));
  EXPECT_EQ("2", string(jsonify(JSON::Number(2))));
  EXPECT_EQ("-2", string(jsonify(JSON::Number(-2))));

  // Expect at least 15 digits of precision.
  EXPECT_EQ(
      "1234567890.12345",
      string(jsonify(JSON::Number(1234567890.12345))));
}

// Tests that `JSON::Number`s wrapped in `JSON::Value` are jsonified correctly.
TEST(JsonifyTest, JSONNumberValue) {
  // Test whole numbers (as doubles).
  EXPECT_EQ("0.0", string(jsonify(JSON::Value(0.0))));
  EXPECT_EQ("1.0", string(jsonify(JSON::Value(1.0))));

  // Negative.
  EXPECT_EQ("-1.0", string(jsonify(JSON::Value(-1.0))));

  // Test integers.
  EXPECT_EQ("0", string(jsonify(JSON::Value(0))));
  EXPECT_EQ("2", string(jsonify(JSON::Value(2))));
  EXPECT_EQ("-2", string(jsonify(JSON::Value(-2))));

  // Expect at least 15 digits of precision.
  EXPECT_EQ(
      "1234567890.12345",
      string(jsonify(JSON::Value(1234567890.12345))));
}

// Tests that strings are jsonified correctly, including escaping.
TEST(JsonifyTest, String) {
  EXPECT_EQ("\"hello world!\"", string(jsonify("hello world!")));

  // We don't use the optional \uXXXX escaping for UTF-8,
  // unless required (" U+0022, \ U+005C, and the control
  // characters U+0000 to U+001F).
  EXPECT_EQ(
      "\"Hello! \\u0001\\u001F\\\"\\\\ \xF0\x9F\x98\x80\"",
      string(jsonify("Hello! \x01\x1F\x22\x5C \xF0\x9F\x98\x80")));

  // There currently is no validation either when constructing
  // invalid UTF-8 string, or during serialization. Here, we
  // use a 4 byte sequence but only provide the first byte.
  // For now, this just gets passed through.
  EXPECT_EQ("\"\xF0\"", string(jsonify("\xF0")));
}

// Tests that `JSON::String`s are jsonified correctly, including escaping.
TEST(JsonifyTest, JSONString) {
  EXPECT_EQ("\"hello world!\"", string(jsonify(JSON::String("hello world!"))));

  // We don't use the optional \uXXXX escaping for UTF-8,
  // unless required (" U+0022, \ U+005C, and the control
  // characters U+0000 to U+001F).
  EXPECT_EQ(
      "\"Hello! \\u0001\\u001F\\\"\\\\ \xF0\x9F\x98\x80\"",
      string(jsonify(
          JSON::String("Hello! \x01\x1F\x22\x5C \xF0\x9F\x98\x80"))));

  // There currently is no validation either when constructing
  // invalid UTF-8 string, or during serialization. Here, we
  // use a 4 byte sequence but only provide the first byte.
  // For now, this just gets passed through.
  EXPECT_EQ("\"\xF0\"", string(jsonify(JSON::String("\xF0"))));
}

// Tests that `JSON::String`s wrapped in `JSON::Value` are jsonified correctly,
// including escaping.
TEST(JsonifyTest, JSONStringValue) {
  EXPECT_EQ("\"hello world!\"", string(jsonify(JSON::Value("hello world!"))));

  // We don't use the optional \uXXXX escaping for UTF-8,
  // unless required (" U+0022, \ U+005C, and the control
  // characters U+0000 to U+001F).
  EXPECT_EQ(
      "\"Hello! \\u0001\\u001F\\\"\\\\ \xF0\x9F\x98\x80\"",
      string(
          jsonify(JSON::Value("Hello! \x01\x1F\x22\x5C \xF0\x9F\x98\x80"))));

  // There currently is no validation either when constructing
  // invalid UTF-8 string, or during serialization. Here, we
  // use a 4 byte sequence but only provide the first byte.
  // For now, this just gets passed through.
  EXPECT_EQ("\"\xF0\"", string(jsonify(JSON::Value("\xF0"))));
}

namespace store {

// A simple object consisting of primitive types.
struct Name {
  string first;
  string last;
};

// A simple object consisting of primitive types as well as a sub-object.
struct Customer {
  Name name;
  int age;
};

// `json` overload for `Name`.
void json(JSON::ObjectWriter* writer, const Name& name) {
  writer->field("first_name", name.first);
  writer->field("last_name", name.last);
}

// `json` overload for `Customer`.
void json(JSON::ObjectWriter* writer, const Customer& customer) {
  json(writer, customer.name); // Composition of `json` functions!
  writer->field("age", customer.age);
}

} // namespace store

// Tests that objects are jsonified correctly.
TEST(JsonifyTest, Object) {
  store::Name name{"michael", "park"};
  EXPECT_EQ(
      "{\"first_name\":\"michael\",\"last_name\":\"park\"}",
      string(jsonify(name)));

  store::Customer customer{name, 25};
  EXPECT_EQ(
      "{\"first_name\":\"michael\",\"last_name\":\"park\",\"age\":25}",
      string(jsonify(customer)));
}

// Tests that `JSON::Object`s are jsonified correctly.
TEST(JsonifyTest, JSONObject) {
  JSON::Object name = {{"first_name", "michael"}, {"last_name", "park"}};
  EXPECT_EQ(
      "{\"first_name\":\"michael\",\"last_name\":\"park\"}",
      string(jsonify(name)));

  JSON::Object customer = {
      {"age", 25},
      {"first_name", "michael"},
      {"last_name", "park"}};

  EXPECT_EQ(
      "{\"age\":25,\"first_name\":\"michael\",\"last_name\":\"park\"}",
      string(jsonify(customer)));
}

// Tests that `JSON::Object`s wrapped in `JSON::Value` are jsonified correctly.
TEST(JsonifyTest, JSONObjectValue) {
  JSON::Value name =
      JSON::Object{{"first_name", "michael"}, {"last_name", "park"}};

  EXPECT_EQ(
      "{\"first_name\":\"michael\",\"last_name\":\"park\"}",
      string(jsonify(name)));

  JSON::Value customer =
      JSON::Object{
          {"first_name", "michael"},
          {"last_name", "park"},
          {"age", 25}};

  EXPECT_EQ(
      "{\"age\":25,\"first_name\":\"michael\",\"last_name\":\"park\"}",
      string(jsonify(customer)));
}

// Tests that iterable types are jsonified as array correctly.
TEST(JsonifyTest, Array) {
  bool booleans[] = {true, true, false};
  EXPECT_EQ("[true,true,false]", string(jsonify(booleans)));

  vector<int> numbers = {1, 2, 3};
  EXPECT_EQ("[1,2,3]", string(jsonify(numbers)));

  set<string> strings = {"there", "hello"};
  EXPECT_EQ("[\"hello\",\"there\"]", string(jsonify(strings)));

  vector<set<int>> numbers_list = {{1, 2, 3}, {1, 1, 1}};
  EXPECT_EQ("[[1,2,3],[1]]", string(jsonify(numbers_list)));

  vector<store::Customer> names = {{{"michael", "park"}, 25}};
  EXPECT_EQ(
      "[{\"first_name\":\"michael\",\"last_name\":\"park\",\"age\":25}]",
      string(jsonify(names)));
}

// Tests that `JSON::Array`s types are jsonified as array correctly.
TEST(JsonifyTest, JSONArray) {
  JSON::Array booleans = {true, true, false};
  EXPECT_EQ("[true,true,false]", string(jsonify(booleans)));

  JSON::Array numbers = {1, 2, 3};
  EXPECT_EQ("[1,2,3]", string(jsonify(numbers)));

  JSON::Array numbers_list = {JSON::Array{1, 2, 3}, JSON::Array{1, 1, 1}};
  EXPECT_EQ("[[1,2,3],[1,1,1]]", string(jsonify(numbers_list)));

  JSON::Array names = {JSON::Object{
      {"first_name", "michael"},
      {"last_name", "park"},
      {"age", 25}}};

  EXPECT_EQ(
      "[{\"age\":25,\"first_name\":\"michael\",\"last_name\":\"park\"}]",
      string(jsonify(names)));
}

// Tests that `JSON::Array`s wrapped in `JSON::Value` types are jsonified as
// array correctly.
TEST(JsonifyTest, JSONArrayValue) {
  JSON::Value booleans = JSON::Array{true, true, false};
  EXPECT_EQ("[true,true,false]", string(jsonify(booleans)));

  JSON::Value numbers = JSON::Array{1, 2, 3};
  EXPECT_EQ("[1,2,3]", string(jsonify(numbers)));

  JSON::Value numbers_list =
      JSON::Array{JSON::Array{1, 2, 3}, JSON::Array{1, 1, 1}};

  EXPECT_EQ("[[1,2,3],[1,1,1]]", string(jsonify(numbers_list)));

  JSON::Value names = JSON::Array{JSON::Object{
      {"first_name", "michael"},
      {"last_name", "park"},
      {"age", 25}}};

  EXPECT_EQ(
      "[{\"age\":25,\"first_name\":\"michael\",\"last_name\":\"park\"}]",
      string(jsonify(names)));
}

// Tests that dictionary types of primitive a member typedef `mapped_type` are
// considered dictionaries and therefore are jsonified as objects correctly.
TEST(JsonifyTest, Dictionary) {
  map<string, bool> booleans = {{"x", true}, {"y", false}};
  EXPECT_EQ("{\"x\":true,\"y\":false}", string(jsonify(booleans)));

  map<string, map<string, int>> nested_numbers = {{"foo", {{"x", 1}}}};
  EXPECT_EQ("{\"foo\":{\"x\":1}}", string(jsonify(nested_numbers)));

  multimap<string, store::Name> names = {
      {"kobe", {"kobe", "bryant"}},
      {"michael", {"michael", "jordan"}},
      {"michael", {"michael", "park"}}};

  string expected = strings::remove(
      "{"
      "  \"kobe\":{\"first_name\":\"kobe\",\"last_name\":\"bryant\"},"
      "  \"michael\":{\"first_name\":\"michael\",\"last_name\":\"jordan\"},"
      "  \"michael\":{\"first_name\":\"michael\",\"last_name\":\"park\"}"
      "}",
      " ");

  EXPECT_EQ(expected, string(jsonify(names)));
}

// Tests that `JSON::Null`s are jsonified as array correctly.
TEST(JsonifyTest, JSONNull) {
  JSON::Null null;
  EXPECT_EQ("null", string(jsonify(null)));

  JSON::Array numbers = JSON::Array{1, JSON::Null(), 3};
  EXPECT_EQ("[1,null,3]", string(jsonify(numbers)));
}


text:
package modelo;

/**
 * Clase de las operaciones del circulo
 * @author cesar
 * @version 1.0
 *
 */
public class Circulo {

	private double radio = 0.0;
	private double diametro = 0.0;
	private double resultado = 0.0;

	/**
	 * Constructor por defecto
	 */
	public Circulo(){}

	/**
	 * Constructor de la clase
	 * @param radio Radio del circulo en formato double
	 * @param diametro Diametro del circulo en formato double
	 */
	public Circulo(double radio, double diametro) {
		this.radio = radio;
		this.diametro = diametro;
	}

	/**
	 * Retorna el Radio en formato double
	 * @return Retorna el Radio en formato double
	 */
	public double getRadio() {
		return radio;
	}

	/**
	 * Establece el valor del Radio
	 * @param radio Valor del raio en formato double
	 */
	public void setRadio(double radio) {
		this.radio = radio;
	}

	/**
	 * Retorna el valor del diametro en formato double
	 * @return Retorna el valor del diametro en formato double
	 */
	public double getDiametro() {
		return diametro;
	}

	/**
	 * Establece el valor del diametro
	 * @param diametro Valor del diametro en formato double
	 */
	public void setDiametro(double diametro) {
		this.diametro = diametro;
	}

	/**
	 * Retorna el resultado en formato double
	 * @return Retorna el resultado en formato double
	 */
	public double getResultado() {
		return resultado;
	}

	/**
	 * Establece el valor del resultado
	 * @param resultado Valor del resultado en formato double
	 */
	public void setResultado(double resultado) {
		this.resultado = resultado;
	}

	/**
	 * Operacion para calcular el area
	 * @param radio Valor del radio en formato double
	 * @return Retorna el resultado del area
	 */
	public double areaCirculo(double radio){
		return resultado = (Math.PI * Math.pow(radio, 2));
	}

	/**
	 * Operacion para calcular el perimetro
	 * @param diametro Valor del diametro en formato double
	 * @return Retorna el resultado del perimetro
	 */
	public double perimetroCirculo(double diametro){
		return resultado = (Math.PI * diametro);
	}

	/**
	 * Metodo para detectar numeros dobles y enteros
	 * @param numero Numero a detectar en formato double
	 * @return Retorna una cadena de texto con el numero
	 */
	public String detectaDoble(double numero){
		return numero % 1.0 != 0 ? String.format("%s", numero) : String.format("%.0f", numero);
	}

}


text:
package br.unb.cic.iris.mail.internal;

import static br.unb.cic.iris.mail.i18n.MessageBundle.message;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.event.FolderEvent;
import javax.mail.event.StoreEvent;
import javax.mail.internet.MimeMessage;
import javax.mail.search.SearchTerm;

import br.unb.cic.iris.exception.IrisException;
import br.unb.cic.iris.exception.IrisUncheckedException;
import br.unb.cic.iris.mail.EmailProvider;
import br.unb.cic.iris.mail.EmailReceiver;
import br.unb.cic.iris.mail.EmailStatusManager;
import br.unb.cic.iris.model.EmailMessage;
import br.unb.cic.iris.model.EntityFactory;
import br.unb.cic.iris.model.IrisFolder;

public abstract class AbstractEmailReceiver implements EmailReceiver {
	private Store store;
	private EmailSession session;
	private EmailProvider provider;
	private EntityFactory entityFactory;

	public AbstractEmailReceiver(EmailProvider provider, String encoding) {
		this.provider = provider;
		session = new EmailSession(provider, encoding);
		initEntityFactory();
	}

	protected abstract String getText(Object obj) throws Exception;

	public List<IrisFolder> listFolders() throws IrisException {
		List<IrisFolder> folders = new ArrayList<>();
		try {
			Folder defaultFolder = getStore().getDefaultFolder();
			Folder[] externalFolders = defaultFolder.list();
			for (Folder f : externalFolders) {
				folders.add(getEntityFactory().createIrisFolder(f.getName()));
			}
		} catch (MessagingException e) {
			throw new IrisException(message("error.list.folder"), e);
		}
		return folders;
	}

	public List<EmailMessage> getMessages(String folderName, SearchTerm searchTerm) throws IrisException {
		List<EmailMessage> messages = new ArrayList<>();
		Folder folder = openFolder(folderName);
		try {
			Message messagesRetrieved[] = null;
			if (searchTerm == null) {
				messagesRetrieved = folder.getMessages();
			} else {
				messagesRetrieved = folder.search(searchTerm);
			}
			messages = convertToIrisMessage(messagesRetrieved);
		} catch (MessagingException e) {
			throw new IrisException(e.getMessage(), e);
		}
		return messages;
	}

	public List<EmailMessage> getMessages(String folderName, int begin, int end) throws IrisException {
		List<EmailMessage> messages = new ArrayList<>();
		Folder folder = openFolder(folderName);
		try {
			Message messagesRetrieved[] = folder.getMessages(begin, end);
			messages = convertToIrisMessage(messagesRetrieved);
		} catch (MessagingException e) {
			throw new IrisException(e.getMessage(), e);
		}
		return messages;
	}

	public List<EmailMessage> getMessages(String folderName, int seqnum) throws IrisException {
		List<EmailMessage> messages = new ArrayList<>();
		Folder folder = openFolder(folderName);
		try {
			List<Message> messagesList = new ArrayList<>();
			int messageCount = folder.getMessageCount();
			for (int i = seqnum; i <= messageCount; i++) {
				Message message = folder.getMessage(i);
				messagesList.add(message);
			}
			Message[] messagesRetrieved = toArray(messagesList);
			messages = convertToIrisMessage(messagesRetrieved);
		} catch (MessagingException e) {
			throw new IrisException(e.getMessage(), e);
		}
		return messages;
	}

	private Message[] toArray(List<Message> messagesList) {
		return messagesList.toArray(new Message[messagesList.size()]);
	}

	private List<EmailMessage> convertToIrisMessage(Message[] messagesRetrieved) throws IrisException {
		List<EmailMessage> messages = new ArrayList<>();
		int cont = 0;
		int total = messagesRetrieved.length;
		for (Message m : messagesRetrieved) {
			// TODO
			messages.add(convertToIrisMessage(m));
			if (total != 0) {
				for (int i = 0; i < 15; i++) {
					System.out.print('\b');
				}
				cont++;
				int tmp = 100 * cont;
				System.out.print(message("email.receiver.download.progress", (tmp / total)));

				EmailStatusManager.instance().notifyMessageDownloadProgress((tmp / total));
			}
		}
		System.out.println();
		return messages;
	}

	private Folder openFolder(String folderName) throws IrisException {
		return openFolder(folderName, Folder.READ_ONLY);
	}

	private Folder openFolder(String folderName, int openType) throws IrisException {
		try {
			Folder folder = getStore().getFolder(folderName);
			folder.open(openType);
			return folder;
		} catch (MessagingException | IrisException e) {
			throw new IrisException(e.getMessage(), e);
		}
	}

	private EmailMessage convertToIrisMessage(Message message) throws IrisException {
		MimeMessage m = (MimeMessage) message;
		EmailMessage msg = getEntityFactory().createEmailMessage();

		try {
			msg.setBcc(convertAddressToString(m.getRecipients(RecipientType.BCC)));
			msg.setCc(convertAddressToString(m.getRecipients(RecipientType.CC)));
			msg.setTo(convertAddressToString(m.getRecipients(RecipientType.TO)));
			msg.setFrom(convertAddressToString(m.getFrom()));
			msg.setMessage(getText(m));
			msg.setSubject(m.getSubject());
			msg.setDate(m.getReceivedDate());
		} catch (Exception e) {
			// TODO i18n
			throw new IrisException("error ....", e);
		}

		return msg;
	}

	private String convertAddressToString(Address[] recipients) {
		StringBuilder sb = new StringBuilder("");
		if (recipients != null) {
			for (Address a : recipients) {
				sb.append(a.toString() + ", ");
			}
		}
		return sb.toString();
	}

	private Store createStoreAndConnect() throws MessagingException {
		EmailStatusManager.instance().notifyListener(message("email.status.receiver.create.store"));
		Store storeTmp = session.getSession().getStore(provider.getStoreProtocol());
		storeTmp.addStoreListener(this);
		storeTmp.addConnectionListener(session);
		session.connect(storeTmp, provider.getStoreHost(), provider.getStorePort());
		return storeTmp;
	}

	public Store getStore() throws IrisException {
		if (store == null) {
			try {
				store = createStoreAndConnect();
			} catch (MessagingException e) {
				throw new IrisException(e.getMessage(), e);
			}
		}
		return store;
	}

	public Store renew() throws IrisException {
		if (store != null) {
			try {
				store.close();
			} catch (MessagingException e) {
				throw new IrisException(e.getMessage(), e);
			}
			store = null;
		}
		return getStore();
	}

	@Override
	public void notification(StoreEvent e) {
		EmailStatusManager.instance().notifyListener(message("email.status.receiver.notification", e.getMessage()));
	}

	@Override
	public void folderCreated(FolderEvent e) {
	}

	@Override
	public void folderDeleted(FolderEvent e) {
	}

	@Override
	public void folderRenamed(FolderEvent e) {
	}

	private EntityFactory getEntityFactory() {
		return entityFactory;
	}

	private void initEntityFactory() {
		ServiceLoader<EntityFactory> sl = ServiceLoader.load(EntityFactory.class);
		Iterator<EntityFactory> it = sl.iterator();

		if (!it.hasNext())
			throw new IrisUncheckedException("No Entity Factory found!");

		entityFactory = it.next();
		System.out.println("Entity Factory: " + entityFactory.getClass().getCanonicalName());
	}

}


text:
import TerminalBuffer from './TerminalBuffer';

/**
 * A view into a parent TerminalBuffer
 * Basically a rectangular part of the parent TerminalBuffer
 * Writes and reads at an offset to the parent buffer
 */
export default class TerminalBufferView implements TerminalBuffer {
	public width: number;
	public height: number;
	private x: number;
	private y: number;

	constructor(private parent: TerminalBuffer,	{x = 0, y = 0, width, height}: {x?: number, y?: number, width?: number, height?: number} = {}, private overflow: boolean = true) {
		this.x = x;
		this.y = y;
		this.width = width || parent.width - x;
		this.height = height || parent.height - y;
	}

	clear() {
		for(let y = 0; y < this.height; y++) {
			for(let x = 0; x < this.height; x++) {
				this.put(x, y, ' ');
			}
		}
	}

	put(x: number, y: number, char: string, styles: Array<string> = []) {
		if(!this.overflow) {
			if(x < 0 || y < 0) return;
			if(x >= this.width || y >= this.height) return;
		}

		this.parent.put(this.x + x, this.y + y, char, styles);
	}

	get(x: number, y: number) {
		return this.parent.get(this.x + x, this.y + y);
	}

	/**
	 * Write something into our parent buffer
	 * Breaks lines at our own buffer border
	 */
	write(x: number, y: number, text: string, styles?: Array<string>) {
		let chars = text.split('');

		chars.forEach((char) => {
			this.put(x++, y, char, styles);

			if(x === this.width) {
				y += 1;
				x = 0;
			}
		});
	}

	writeBuffer(offsetX: number, offsetY: number, buffer: TerminalBuffer) {
		for(let y = 0; y < this.width; y++) {
			for(let x = 0; x < this.width; x++) {
				this.put(x + offsetX, y + offsetY, buffer.get(x, y));
			}
		}
	}
}


text:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MarkdownModule } from 'ngx-markdown';

import { ScrollspyNavLayoutModule } from '@shared/scrollspy-nav-layout/scrollspy-nav-layout.module';
import { SharedModule } from '@shared/shared.module';
import { BindingsRoutingModule } from './bindings-routing.module';
import { BindingsComponent } from './bindings.component';

@NgModule({
  imports: [
    BindingsRoutingModule,
    FormsModule,
    MarkdownModule.forChild(),
    MatInputModule,
    ScrollspyNavLayoutModule,
    SharedModule,
  ],
  declarations: [BindingsComponent],
})
export class BindingsModule { }


text:
require 'spec_helper'

module LimitedRed::Cucumber::Formatter
  describe Stats do
    let(:fake_step_mother){ mock('step_mother') }
    let(:fake_path_or_io){ mock('path_or_io').as_null_object }
    let(:fake_config){ mock(Config) }

    before(:each) do
      LimitedRed::Config.stub!(:load_and_validate_config).with('cucumber').and_return(fake_config)
      LimitedRed::ThreadPool.stub!(:wait_for_all_threads_to_finish)
    end

    describe "#new" do
      it "should create a limited red client with config" do
        LimitedRed::Config.stub!(:load_and_validate_config).with('cucumber').and_return(fake_config)

        LimitedRed::Client.should_receive(:new).with(fake_config)

        Stats.new(fake_step_mother, fake_path_or_io, {})
      end
    end

    describe "#after_feature" do
      let(:fake_feature){mock("fake_feature", :to_json => "{'FEATURE JSON'}", :[] => nil)}

      class FakeGherkinFormatter
        def initialize(json)
          @feature_hash = json
        end
      end

      it "should use the current time as the build id posted to the client" do
        client = mock(LimitedRed::Client)
        LimitedRed::Client.stub(:new).and_return(client)

        Time.stub!(:now).and_return(1324468723)

        stats = Stats.new(fake_step_mother, fake_path_or_io, {})
        stats.instance_variable_set("@gf", FakeGherkinFormatter.new(fake_feature))

        client.should_receive(:log_result).with(1324468723, anything)

        stats.after_feature(mock("feature result"))
      end

      it "should log the feature json with the client" do
        client = mock(LimitedRed::Client)
        LimitedRed::Client.stub(:new).and_return(client)

        stats = Stats.new(fake_step_mother, fake_path_or_io, {})

        #TODO: How does this get set by Cucumber/Gherkin?
        stats.instance_variable_set("@gf", FakeGherkinFormatter.new(fake_feature))

        client.should_receive(:log_result).with(anything, {:result => "{'FEATURE JSON'}", :uri=>nil} )

        stats.after_feature(mock("feature result"))
      end
    end

    describe "#after_features" do
      def scenario(file_and_line)
        scenario = mock(Cucumber::Ast::Scenario, :file_colon_line => file_and_line)
        scenario.stub!(:is_a?).with(Cucumber::Ast::Scenario).and_return(true)
        scenario.stub!(:is_a?).with(Cucumber::Ast::OutlineTable::ExampleRow).and_return(false)
        scenario
      end

      it "should log all the failing and passing feature files" do
        client = mock(LimitedRed::Client)
        LimitedRed::Client.stub(:new).and_return(client)

        fake_step_mother.stub!(:scenarios).with(:failed).and_return([scenario(file_line="example.feature:2")])
        fake_step_mother.stub!(:scenarios).with(:passed).and_return([scenario(file_line="another.feature:4")])

        stats = Stats.new(fake_step_mother, fake_path_or_io, {})

        client.should_receive(:log_build).with(anything, {:fails =>  ['example.feature:2'],
                                                          :passes => ['another.feature:4']} )

        stats.after_features(mock("features"))
      end

    end

  end
end


text:
@echo off
title [convert excel to json]
echo press any button to start.
@pause > nul
echo start converting ....
node index.js --export
echo convert over!
@pause


text:
/*
 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#ifndef __IP_FLOWID_H__
#define __IP_FLOWID_H__

#include <sys/types.h>
#include <netinet/in.h>

/*
 * This structure is used as a flow mask and a flow id for various
 * parts of the code.
 */
struct ip_flow_id {
	u_int32_t       dst_ip;
	u_int32_t       src_ip;
	u_int16_t       dst_port;
	u_int16_t       src_port;
	u_int8_t        proto;
	u_int8_t        flags;  /* protocol-specific flags */
	u_int8_t        addr_type; /* 4 = ipv4, 6 = ipv6, 1=ether ? */
	struct in6_addr dst_ip6;        /* could also store MAC addr! */
	struct in6_addr src_ip6;
	u_int32_t       flow_id6;
	u_int32_t       frag_id6;
};

#define IS_IP6_FLOW_ID(id)      ((id)->addr_type == 6)

#endif /* __IP_FLOWID_H__ */


text:
module Nanoc
  module CLI
    # A simple ANSI colorizer for strings. When given a string and a list of
    # attributes, it returns a colorized string.
    #
    # @api private
    module ANSIStringColorizer
      # TODO: complete mapping
      MAPPING = {
        bold: "\e[1m",
        red: "\e[31m",
        green: "\e[32m",
        yellow: "\e[33m",
        blue: "\e[34m",
      }.freeze

      # @param [String] str The string to colorize
      #
      # @param [Array] attrs An array of attributes from `MAPPING` to colorize the
      #   string with
      #
      # @return [String] A string colorized using the given attributes
      def self.c(str, *attrs)
        attrs.map { |a| MAPPING[a] }.join('') + str + "\e[0m"
      end
    end
  end
end


text:
ios:
	cake --config ios.json dev

android:
	cake --config android.json dev

nodejs:
	mkdir -p public
	rsync -r src/images/ public/images/
	rsync libs/client/*.js public/javascripts/
	rsync src/locales.json public/
	node-dev app.coffee

tdd:
	@NODE_ENV=test ./node_modules/.bin/mocha -b -G -w \
	--compilers coffee:coffee-script \
	--reporter dot

casper:
	casperjs test/casper/test.coffee

docs:
	rm -fr docs
	./node_modules/.bin/docco src/coffeescripts/*.coffee

lint:
	coffeelint -f test/config/coffeelint.json src/coffeescripts/*.coffee

clean:
	rm -rf public/
	rm -rf docs/

pull:
	git pull origin dev

push:
	git push origin dev

dev2stable:
	git checkout stable
	git merge dev
	git push origin stable
	git checkout dev

stable2master:
	git checkout master
	git merge stable
	git push origin master
	git checkout dev

deploy:
	git push heroku refs/remotes/github/master:refs/heads/master

test:
	@NODE_ENV=test ./node_modules/.bin/mocha -b -G \
	--compilers coffee:coffee-script \
	--reporter xunit > xunit.xml

.PHONY: test docs ios android


text:
package trie

import (
	"errors"
	"fmt"

	"github.com/ethereum/go-ethereum/common"
	"gopkg.in/karalabe/cookiejar.v2/collections/prque"
)

// ErrNotRequested is returned by the trie sync when it's requested to process a
// node it did not request.
var ErrNotRequested = errors.New("not requested")

// ErrAlreadyProcessed is returned by the trie sync when it's requested to process a
// node it already processed previously.
var ErrAlreadyProcessed = errors.New("already processed")

// request represents a scheduled or already in-flight state retrieval request.
type request struct {
	hash common.Hash // Hash of the node data content to retrieve
	data []byte      // Data content of the node, cached until all subtrees complete
	raw  bool        // Whether this is a raw entry (code) or a trie node

	parents []*request // Parent state nodes referencing this entry (notify all upon completion)
	depth   int        // Depth level within the trie the node is located to prioritise DFS
	deps    int        // Number of dependencies before allowed to commit this node

	callback TrieSyncLeafCallback // Callback to invoke if a leaf node it reached on this branch
}

// SyncResult is a simple list to return missing nodes along with their request
// hashes.
type SyncResult struct {
	Hash common.Hash // Hash of the originally unknown trie node
	Data []byte      // Data content of the retrieved node
}

// syncMemBatch is an in-memory buffer of successfully downloaded but not yet
// persisted data items.
type syncMemBatch struct {
	batch map[common.Hash][]byte // In-memory membatch of recently completed items
	order []common.Hash          // Order of completion to prevent out-of-order data loss
}

// newSyncMemBatch allocates a new memory-buffer for not-yet persisted trie nodes.
func newSyncMemBatch() *syncMemBatch {
	return &syncMemBatch{
		batch: make(map[common.Hash][]byte),
		order: make([]common.Hash, 0, 256),
	}
}

// TrieSyncLeafCallback is a callback type invoked when a trie sync reaches a
// leaf node. It's used by state syncing to check if the leaf node requires some
// further data syncing.
type TrieSyncLeafCallback func(leaf []byte, parent common.Hash) error

// TrieSync is the main state trie synchronisation scheduler, which provides yet
// unknown trie hashes to retrieve, accepts node data associated with said hashes
// and reconstructs the trie step by step until all is done.
type TrieSync struct {
	database DatabaseReader           // Persistent database to check for existing entries
	membatch *syncMemBatch            // Memory buffer to avoid frequest database writes
	requests map[common.Hash]*request // Pending requests pertaining to a key hash
	queue    *prque.Prque             // Priority queue with the pending requests
}

// NewTrieSync creates a new trie data download scheduler.
func NewTrieSync(root common.Hash, database DatabaseReader, callback TrieSyncLeafCallback) *TrieSync {
	ts := &TrieSync{
		database: database,
		membatch: newSyncMemBatch(),
		requests: make(map[common.Hash]*request),
		queue:    prque.New(),
	}
	ts.AddSubTrie(root, 0, common.Hash{}, callback)
	return ts
}

// AddSubTrie registers a new trie to the sync code, rooted at the designated parent.
func (s *TrieSync) AddSubTrie(root common.Hash, depth int, parent common.Hash, callback TrieSyncLeafCallback) {
	// Short circuit if the trie is empty or already known
	if root == emptyRoot {
		return
	}
	if _, ok := s.membatch.batch[root]; ok {
		return
	}
	key := root.Bytes()
	blob, _ := s.database.Get(key)
	if local, err := decodeNode(key, blob, 0); local != nil && err == nil {
		return
	}
	// Assemble the new sub-trie sync request
	req := &request{
		hash:     root,
		depth:    depth,
		callback: callback,
	}
	// If this sub-trie has a designated parent, link them together
	if parent != (common.Hash{}) {
		ancestor := s.requests[parent]
		if ancestor == nil {
			panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
		}
		ancestor.deps++
		req.parents = append(req.parents, ancestor)
	}
	s.schedule(req)
}

// AddRawEntry schedules the direct retrieval of a state entry that should not be
// interpreted as a trie node, but rather accepted and stored into the database
// as is. This method's goal is to support misc state metadata retrievals (e.g.
// contract code).
func (s *TrieSync) AddRawEntry(hash common.Hash, depth int, parent common.Hash) {
	// Short circuit if the entry is empty or already known
	if hash == emptyState {
		return
	}
	if _, ok := s.membatch.batch[hash]; ok {
		return
	}
	if ok, _ := s.database.Has(hash.Bytes()); ok {
		return
	}
	// Assemble the new sub-trie sync request
	req := &request{
		hash:  hash,
		raw:   true,
		depth: depth,
	}
	// If this sub-trie has a designated parent, link them together
	if parent != (common.Hash{}) {
		ancestor := s.requests[parent]
		if ancestor == nil {
			panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
		}
		ancestor.deps++
		req.parents = append(req.parents, ancestor)
	}
	s.schedule(req)
}

// Missing retrieves the known missing nodes from the trie for retrieval.
func (s *TrieSync) Missing(max int) []common.Hash {
	requests := []common.Hash{}
	for !s.queue.Empty() && (max == 0 || len(requests) < max) {
		requests = append(requests, s.queue.PopItem().(common.Hash))
	}
	return requests
}

// Process injects a batch of retrieved trie nodes data, returning if something
// was committed to the database and also the index of an entry if processing of
// it failed.
func (s *TrieSync) Process(results []SyncResult) (bool, int, error) {
	committed := false

	for i, item := range results {
		// If the item was not requested, bail out
		request := s.requests[item.Hash]
		if request == nil {
			return committed, i, ErrNotRequested
		}
		if request.data != nil {
			return committed, i, ErrAlreadyProcessed
		}
		// If the item is a raw entry request, commit directly
		if request.raw {
			request.data = item.Data
			s.commit(request)
			committed = true
			continue
		}
		// Decode the node data content and update the request
		node, err := decodeNode(item.Hash[:], item.Data, 0)
		if err != nil {
			return committed, i, err
		}
		request.data = item.Data

		// Create and schedule a request for all the children nodes
		requests, err := s.children(request, node)
		if err != nil {
			return committed, i, err
		}
		if len(requests) == 0 && request.deps == 0 {
			s.commit(request)
			committed = true
			continue
		}
		request.deps += len(requests)
		for _, child := range requests {
			s.schedule(child)
		}
	}
	return committed, 0, nil
}

// Commit flushes the data stored in the internal membatch out to persistent
// storage, returning th enumber of items written and any occurred error.
func (s *TrieSync) Commit(dbw DatabaseWriter) (int, error) {
	// Dump the membatch into a database dbw
	for i, key := range s.membatch.order {
		if err := dbw.Put(key[:], s.membatch.batch[key]); err != nil {
			return i, err
		}
	}
	written := len(s.membatch.order)

	// Drop the membatch data and return
	s.membatch = newSyncMemBatch()
	return written, nil
}

// Pending returns the number of state entries currently pending for download.
func (s *TrieSync) Pending() int {
	return len(s.requests)
}

// schedule inserts a new state retrieval request into the fetch queue. If there
// is already a pending request for this node, the new request will be discarded
// and only a parent reference added to the old one.
func (s *TrieSync) schedule(req *request) {
	// If we're already requesting this node, add a new reference and stop
	if old, ok := s.requests[req.hash]; ok {
		old.parents = append(old.parents, req.parents...)
		return
	}
	// Schedule the request for future retrieval
	s.queue.Push(req.hash, float32(req.depth))
	s.requests[req.hash] = req
}

// children retrieves all the missing children of a state trie entry for future
// retrieval scheduling.
func (s *TrieSync) children(req *request, object node) ([]*request, error) {
	// Gather all the children of the node, irrelevant whether known or not
	type child struct {
		node  node
		depth int
	}
	children := []child{}

	switch node := (object).(type) {
	case *shortNode:
		children = []child{{
			node:  node.Val,
			depth: req.depth + len(node.Key),
		}}
	case *fullNode:
		for i := 0; i < 17; i++ {
			if node.Children[i] != nil {
				children = append(children, child{
					node:  node.Children[i],
					depth: req.depth + 1,
				})
			}
		}
	default:
		panic(fmt.Sprintf("unknown node: %+v", node))
	}
	// Iterate over the children, and request all unknown ones
	requests := make([]*request, 0, len(children))
	for _, child := range children {
		// Notify any external watcher of a new key/value node
		if req.callback != nil {
			if node, ok := (child.node).(valueNode); ok {
				if err := req.callback(node, req.hash); err != nil {
					return nil, err
				}
			}
		}
		// If the child references another node, resolve or schedule
		if node, ok := (child.node).(hashNode); ok {
			// Try to resolve the node from the local database
			hash := common.BytesToHash(node)
			if _, ok := s.membatch.batch[hash]; ok {
				continue
			}
			if ok, _ := s.database.Has(node); ok {
				continue
			}
			// Locally unknown node, schedule for retrieval
			requests = append(requests, &request{
				hash:     hash,
				parents:  []*request{req},
				depth:    child.depth,
				callback: req.callback,
			})
		}
	}
	return requests, nil
}

// commit finalizes a retrieval request and stores it into the membatch. If any
// of the referencing parent requests complete due to this commit, they are also
// committed themselves.
func (s *TrieSync) commit(req *request) (err error) {
	// Write the node content to the membatch
	s.membatch.batch[req.hash] = req.data
	s.membatch.order = append(s.membatch.order, req.hash)

	delete(s.requests, req.hash)

	// Check all parents for completion
	for _, parent := range req.parents {
		parent.deps--
		if parent.deps == 0 {
			if err := s.commit(parent); err != nil {
				return err
			}
		}
	}
	return nil
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hello-world</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <!-- please change this to the latest non-snapshot version: -->
        <rapidoid.version>6.0.0-SNAPSHOT</rapidoid.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.rapidoid</groupId>
            <artifactId>rapidoid-rest</artifactId>
            <version>${rapidoid.version}</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.rapidoid</groupId>
            <artifactId>rapidoid-http-client</artifactId>
            <version>${rapidoid.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-engine</artifactId>
            <version>1.1.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>-Xms512m -Xmx1024m</argLine>
                    <forkCount>1</forkCount>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>1.1.1</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>


text:
using System;

namespace Eto.Parse.Scanners
{
	public class StringScanner : Scanner
	{
		readonly int end;
		readonly string value;

		public override bool IsEof
		{
			get { return Position >= end; }
		}

		public string Value
		{
			get { return value; }
		}

		public string GetContext(int count)
		{
			return value.Substring(Position, Math.Min(value.Length - Position, count));
		}

		public StringScanner(string value)
		{
			this.value = value;
			this.end = value.Length;
		}

		public StringScanner(string value, int index, int length)
		{
			this.value = value;
			this.Position = index;
			this.end = index + length;
		}

		public override int ReadChar()
		{
			var pos = Position;
			if (pos < end)
			{
				Position = pos + 1;
				return value[pos];
			}
			return -1;
		}

		public override int Peek()
		{
			var pos = Position;
			return pos < end ? value[pos] : -1;
		}

		public override int Advance(int length)
		{
			var start = Position;
			var newPos = start + length;
			if (newPos <= end)
			{
				Position = newPos;
				return start;
			}
			return -1;
		}

		public override bool ReadString(string matchString, bool caseSensitive)
		{
			var index = Position;
			var endstring = index + matchString.Length;
			if (endstring <= end)
			{
				if (caseSensitive)
				{
					for (int i = 0; i < matchString.Length; i++)
					{
						if (value[index++] != matchString[i])
							return false;
					}
					Position = endstring;
					return true;
				}
				else
				{
					for (int i = 0; i < matchString.Length; i++)
					{
						if (char.ToLowerInvariant(value[index++]) != char.ToLowerInvariant(matchString[i]))
							return false;
					}
					Position = endstring;
					return true;
				}
			}
			return false;
		}

		public override string Substring(int index, int length)
		{
			if (index < end)
			{
				length = Math.Min(index + length, end) - index;
				return value.Substring(index, length);
			}
			return null;
		}
	}
}


text:
/* eslint-disable */
const path = require('path');
const fs = require('fs');

const readImageDirectory = dir =>
  fs
    .readdirSync(dir)
    .reduce(
    (files, file) =>
      fs.statSync(path.join(dir, file)).isDirectory()
        ? files.concat(readImageDirectory(path.join(dir, file)))
        : files.concat(path.join(dir, file)),
    []
    )
    .filter(file => typeof file === 'string')
    .filter(image => {
      fs.lstatSync(image).size > 1000000;
    });

const fileArray = readImageDirectory('src/images/');

if (fileArray.length) {
  console.log(`The following image(s) are over our 1MB size limit: ${fileArray}`);
  process.exit(-1);
} else {
  console.log('Test successful 💪 💪 💪 💪 💪 💪');
  process.exit(0);
}