text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

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

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.sling</groupId>
        <artifactId>sling</artifactId>
        <version>19</version>
        <relativePath>../../../parent/pom.xml</relativePath>
    </parent>

    <artifactId>org.apache.sling.settings</artifactId>
    <packaging>bundle</packaging>
    <version>1.3.1-SNAPSHOT</version>

    <name>Apache Sling Settings</name>
    <description>
        Settings support including run modes
    </description>

    <scm>
        <connection>
            scm:svn:http://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/settings
        </connection>
        <developerConnection>
            scm:svn:https://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/settings
        </developerConnection>
        <url>
            http://svn.apache.org/viewvc/sling/trunk/bundles/extensions/settings
        </url>
    </scm>

    <properties>
        <site.jira.version.id>12315254</site.jira.version.id>
        <site.javadoc.exclude>**.impl.**</site.javadoc.exclude>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-DocURL>
                            http://sling.apache.org/documentation/bundles/sling-settings-orgapacheslingsettings.html
                        </Bundle-DocURL>
                        <Private-Package>
                            org.apache.sling.settings.impl
                        </Private-Package>
                        <Bundle-Activator>
                            org.apache.sling.settings.impl.Activator
                        </Bundle-Activator>
                        <DynamicImport-Package>
                            org.osgi.service.cm
                        </DynamicImport-Package>
                        <Import-Package>
                            !org.osgi.service.cm,
                            org.apache.felix.shell;resolution:=optional,
                            *
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.shell</artifactId>
            <version>1.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.launchpad.api</artifactId>
            <version>1.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
      <!-- Testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>
    </dependencies>
</project>


text:
FROM ubuntu:16.04
ARG BASHUTILS_VERSION
ENV BASHUTILS_VERSION=${BASHUTILS_VERSION:-1.5.1} BASHUTILS=/bashutils/share BASHUTILS_HOME=/bashutils
LABEL maintainer="Carl Seelye <cseelye@gmail.com>" version="${BASHUTILS_VERSION}" description="Container for hosting bashutils scripts"

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install --assume-yes \
        bsdmainutils \
        bzip2 \
        coreutils \
        cpio \
        curl \
        dialog \
        findutils \
        gawk \
        genisoimage \
        gnupg \
        grep \
        gzip \
        iproute2 \
        iputils-ping \
        jq \
        locales \
        lsb-release \
        openssl \
        ncurses-bin \
        pbzip2 \
        pigz \
        sed \
        squashfs-tools \
        tar \
        tzdata \
        util-linux \
        uuid-runtime \
        vim \
        wget \
        xz-utils && \
    locale-gen en_US.UTF-8 && \
    update-locale LANG=en_US.utf8 && \
    apt-get autoremove --assume-yes && \
    apt-get clean --assume-yes && \
    rm --force --recursive /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN mkdir /bashutils && \
    curl https://bitbucket.org/solidfire/bashutils/get/bashutils-${BASHUTILS_VERSION}.tar.gz | tar xz -C bashutils --strip-components=1

ENTRYPOINT ["/bin/bash", "-l", "-c", "${BASHUTILS_HOME}/bin/bashutils"]

redpajama_set_name: RedPajamaGithub


text:
using System;
using AlphaChiTech.VirtualizingCollection.Interfaces;

namespace AlphaChiTech.VirtualizingCollection.Pageing
{
    /// <summary>
    ///     An implementation of a IPageExiryComparer that uses DateTime to see if the update should be applied
    /// </summary>
    public class DateBasedPageExpiryComparer : IPageExpiryComparer
    {
        /// <summary>
        ///     Gets the default instance.
        /// </summary>
        /// <value>
        ///     The default instance.
        /// </value>
        public static DateBasedPageExpiryComparer DefaultInstance { get; } = new DateBasedPageExpiryComparer();

        /// <summary>
        ///     Determines whether [is update valid] [the specified page based on the updateAt].
        /// </summary>
        /// <param name="pageUpdateAt">The page update at - null or a DateTime.</param>
        /// <param name="updateAt">The update at - null or a DateTime.</param>
        /// <returns></returns>
        public bool IsUpdateValid(object pageUpdateAt, object updateAt)
        {
            if (pageUpdateAt == null || updateAt == null || !(pageUpdateAt is DateTime) || !(updateAt is DateTime))
                return true;

            return ((DateTime) pageUpdateAt) < ((DateTime) updateAt);
        }
    }
}


text:
module GitlabRuby
  class APIObject < Hash
    def initialize(data)
      super()
      data.each { |key, val| self[key] = val } if data.is_a?(Hash)
    end

    def format(val)
      return if val.nil?
      if val.class == Hash
        APIObject.new(val)
      else
        val
      end
    end

    def method_missing(method, *args, &blk)
      format(self[method.to_s]) || super
    end

    def respond_to_missing?(method, include_all = false)
      key?(method.to_s) || super
    end
  end
end


text:
package com.opengamma.analytics.financial.model.interestrate.curve;

import java.io.Serializable;

import org.apache.commons.lang.ObjectUtils;

import com.opengamma.analytics.math.curve.ConstantDoublesCurve;
import com.opengamma.analytics.math.curve.Curve;
import com.opengamma.analytics.math.curve.FunctionalDoublesCurve;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.integration.RungeKuttaIntegrator1D;
import com.opengamma.analytics.util.serialization.InvokedSerializedForm;
import com.opengamma.util.ArgumentChecker;

/**
 *
 */
public class ForwardCurve implements Serializable {
  private static final RungeKuttaIntegrator1D INTEGRATOR = new RungeKuttaIntegrator1D();
  private final Curve<Double, Double> _fwdCurve;
  private final Curve<Double, Double> _drift;
  private final double _spot;

  public ForwardCurve(final Curve<Double, Double> fwdCurve, final Curve<Double, Double> driftCurve) {
    ArgumentChecker.notNull(fwdCurve, "null fwdCurve");
    ArgumentChecker.notNull(driftCurve, "null driftCurve");
    _fwdCurve = fwdCurve;
    _drift = driftCurve;
    _spot = _fwdCurve.getYValue(0.0);
  }

  public ForwardCurve(final Curve<Double, Double> fwdCurve) {
    ArgumentChecker.notNull(fwdCurve, "curve");
    _fwdCurve = fwdCurve;
    _drift = getDriftCurve(fwdCurve);  //TODO YieldAndDiscountCurve should have a getForwardRate method, which should be used here
    _spot = _fwdCurve.getYValue(0.0);
  }

  /**
   * Forward curve with zero drift (i.e. curve is constant)
   * @param spot The spot rate
   */
  public ForwardCurve(final double spot) {
    _fwdCurve = ConstantDoublesCurve.from(spot);
    _drift = ConstantDoublesCurve.from(0.0);
    _spot = spot;
  }

  /**
   * Forward curve with constant drift
   * @param spot  The spot
   * @param drift The drift
   */
  public ForwardCurve(final double spot, final double drift) {
    _drift = ConstantDoublesCurve.from(drift);
    _fwdCurve = getForwardCurve(spot, drift);
    _spot = spot;
  }

  /**
   * Forward curve with functional drift.
   * <b>Warning</b> This will be slow if you want access to the forward at many times
   * @param spot The spot rate
   * @param driftCurve The drift curve
   */
  public ForwardCurve(final double spot, final Curve<Double, Double> driftCurve) {
    ArgumentChecker.notNull(driftCurve, "null driftCurve");
    _drift = driftCurve;
    _fwdCurve = getForwardCurve(spot, driftCurve);
    _spot = spot;
  }

  public ForwardCurve(final Function1D<Double, Double> func) {
    this(FunctionalDoublesCurve.from(func));
  }

  public Curve<Double, Double> getForwardCurve() {
    return _fwdCurve;
  }

  public double getForward(final double t) {
    return _fwdCurve.getYValue(t);
  }

  /**
   * Gets the drift.
   * @return the drift
   */
  public Curve<Double, Double> getDriftCurve() {
    return _drift;
  }

  public double getDrift(final double t) {
    return _drift.getYValue(t);
  }

  public double getSpot() {
    return _spot;
  }

  protected static Curve<Double, Double> getForwardCurve(final double spot, final YieldAndDiscountCurve riskFreeCurve, final YieldAndDiscountCurve costOfCarryCurve) {
    ArgumentChecker.notNull(riskFreeCurve, "risk-free curve");
    ArgumentChecker.notNull(costOfCarryCurve, "cost-of-carry curve");
    final Function1D<Double, Double> f = new Function1D<Double, Double>() {

      @Override
      public Double evaluate(final Double t) {
        return spot * costOfCarryCurve.getDiscountFactor(t) / riskFreeCurve.getDiscountFactor(t);
      }

    };
    return new FunctionalDoublesCurve(f) {
      public Object writeReplace() {
        return new InvokedSerializedForm(ForwardCurve.class, "getForwardCurve", spot, riskFreeCurve, costOfCarryCurve);
      }
    };
  }

  protected static Curve<Double, Double> getForwardCurve(final Double spot, final Double drift) {
    final Function1D<Double, Double> fwd = new Function1D<Double, Double>() {

      @Override
      public Double evaluate(final Double t) {
        return spot * Math.exp(drift * t);
      }

    };

    return new FunctionalDoublesCurve(fwd) {

      public Object writeReplace() {
        return new InvokedSerializedForm(ForwardCurve.class, "getForwardCurve", spot, drift);
      }
    };
  }

  protected static Curve<Double, Double> getForwardCurve(final Double spot, final Curve<Double, Double> driftCurve) {
    final Function1D<Double, Double> fwd = new Function1D<Double, Double>() {

      @Override
      public Double evaluate(final Double t) {
        final Function1D<Double, Double> driftFunc = new Function1D<Double, Double>() {

          @Override
          public Double evaluate(final Double y) {
            return driftCurve.getYValue(y);
          }

        };
        @SuppressWarnings("synthetic-access")
        final double temp = INTEGRATOR.integrate(driftFunc, 0.0, t);
        return spot * Math.exp(temp);
      }

    };
    return new FunctionalDoublesCurve(fwd) {

      public Object writeReplace() {
        return new InvokedSerializedForm(ForwardCurve.class, "getForwardCurve", spot, driftCurve);
      }
    };
  }

  protected static Curve<Double, Double> getDriftCurve(final Curve<Double, Double> fwdCurve) {
    final Function1D<Double, Double> drift = new Function1D<Double, Double>() {
      private final double _eps = 1e-3;

      @Override
      public Double evaluate(final Double t) {

        final double up = Math.log(fwdCurve.getYValue(t + _eps));

        if (t < _eps) {
          final double mid = Math.log(fwdCurve.getYValue(t));
          return (up - mid) / _eps;
        }
        final double down = Math.log(fwdCurve.getYValue(t - _eps));
        return (up - down) / 2 / _eps;
      }

    };

    return new FunctionalDoublesCurve(drift) {
      public Object writeReplace() {
        return new InvokedSerializedForm(ForwardCurve.class, "getDriftCurve", fwdCurve);
      }
    };
  }

  /**
   * Shift the forward curve by a fractional amount, shift, such that the new curve F'(T) = (1 + shift) * F(T), has
   * an unchanged drift.
   * @param shift The fractional shift amount, i.e. 0.1 will produce a curve 10% larger than the original
   * @return The shifted curve
   */
  public ForwardCurve withFractionalShift(final double shift) {
    ArgumentChecker.isTrue(shift > -1, "shift must be > -1");

    final Function1D<Double, Double> func = new Function1D<Double, Double>() {
      @SuppressWarnings("synthetic-access")
      @Override
      public Double evaluate(final Double t) {
        return (1 + shift) * _fwdCurve.getYValue(t);
      }
    };
    return new ForwardCurve(FunctionalDoublesCurve.from(func), _drift);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + _drift.hashCode();
    result = prime * result + _fwdCurve.hashCode();
    long temp;
    temp = Double.doubleToLongBits(_spot);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final ForwardCurve other = (ForwardCurve) obj;
    if (!ObjectUtils.equals(_drift, other._drift)) {
      return false;
    }
    if (!ObjectUtils.equals(_fwdCurve, other._fwdCurve)) {
      return false;
    }
    if (Double.doubleToLongBits(_spot) != Double.doubleToLongBits(other._spot)) {
      return false;
    }
    return true;
  }

}


text:
import os
import time
from slackclient import SlackClient

# starterbot's ID as an environment variable
BOT_ID = os.environ.get("BOT_ID")

# constants
AT_BOT = "<@" + BOT_ID + ">"

DO = "do"
MAKE = "make"
COFFEE = "coffee"

# instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

def handle_command(command, channel):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = "Error: Does not compute."
    if command.startswith(DO):
        response = "Do it yourself ..."
    if command.startswith(MAKE):
        response = "Make it yourself ..."
    if command.startswith(COFFEE):
        response = "Here you go :coffee:"
    slack_client.api_call("chat.postMessage", channel=channel,
                          text=response, as_user=True)

def parse_slack_output(slack_rtm_output):
    """
        The Slack Real Time Messaging API is an events firehose.
        this parsing function returns None unless a message is
        directed at the Bot, based on its ID.
    """
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
                # return text after the @ mention, whitespace removed
                return output['text'].split(AT_BOT)[1].strip().lower(), \
                       output['channel']
    return None, None

if __name__ == "__main__":
    READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
    if slack_client.rtm_connect():
        print("StarterBot connected and running!")
        while True:
            command, channel = parse_slack_output(slack_client.rtm_read())
            if command and channel:
                handle_command(command, channel)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print("Connection failed. Invalid Slack token or bot ID?")


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

{{ page.title }}

{% endblock title %}
{% block content %}

        {{ page }}

{% block content_footer %}
{% endblock content_footer %}
{% endblock content %}


text:
package com.intellij.codeInsight.codeFragment;

import java.util.*;

public class CodeFragment {
  private final List<String> inputVariables;
  private final List<String> outputVariables;
  private final boolean returnInstructionInside;

  public CodeFragment(final Set<String> input, final Set<String> output, final boolean returnInside) {
    inputVariables = new ArrayList<>(input);
    Collections.sort(inputVariables);
    outputVariables = new ArrayList<>(output);
    Collections.sort(outputVariables);
    returnInstructionInside = returnInside;
  }

  public Collection<String> getInputVariables() {
    return inputVariables;
  }

  public Collection<String> getOutputVariables() {
    return outputVariables;
  }

  public boolean isReturnInstructionInside() {
    return returnInstructionInside;
  }
}


text:
package org.vaadin.alump.fancylayouts.gwt.client.shared;

import com.vaadin.shared.ui.AbstractLayoutState;

@SuppressWarnings("serial")
public class FancyCssLayoutState extends AbstractLayoutState {

    public boolean horMarginTransition = true;
    public boolean verMarginTransition = true;

}


text:
<?php

# input values from URL
$nbHabitId = $_GET['habitId'];
$nbUniqueId = $_GET['id'];

$urlApiJson = "https://www.coach.me/api/v3/users/".$nbUniqueId."/activity";
//$urlApiJson = "https://www.coach.me/api/v3/users/".$nbUniqueId."/stats"; // using the stats API/JSON
//$urlApiJson = 'http://www.pedrodz.com/pedro.json'; //test purpose

$stringApi = file_get_contents($urlApiJson);
$obj = json_decode($stringApi, true);

// using the stats API/JSON:
// extract particular elements:
//$plan = $obj['plans'][$nbPlan]['name'];
//$checking = $obj['plans'][$nbPlan]['stats']['total_checkin_count'];
// text to output
//$output = 'Coach.me | ' . $plan . ' for ' . $checking . ' days'; //. " days checked in since " . $date;  // Date is broken in JSON
//$habit = $obj['plans'][$nbPlan]['name'];
//$checking = $obj['plans'][$nbPlan]['stats']['total_checkin_count'];

foreach($obj['activity_items'] as $activity){
    	$habit = $activity['habit_id'];
    	if ($nbHabitId == $habit) {
    		$activityRichTitle = $activity['activity_rich_title'];
    		break;
}}

// text to output
$name = $obj['refs']['users'][0]['name'];
$nameExplode = explode(' ',trim($name));
$first_name = $nameExplode[0]; // will print Pedro
$activityRichTitle = strip_tags($activityRichTitle); // remove html tags from string
$output = ' Coach.me | '.$first_name.': ' . $activityRichTitle;
//$output = ' Coach.me | ' . $activityRichTitle;

// image processing
$h = 6*strlen($output); // change size of pic depending in nb characters

$my_img = imagecreate( $h, 20 );
$background = imagecolorallocate( $my_img, 255, 255, 255 );
$text_colour = imagecolorallocate( $my_img, 128, 128, 128 );
#$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 2, 0, 0, $output , $text_colour );
#imagesetthickness ( $my_img, 5 );
#imageline( $my_img, 30, 45, 165, 45, $line_colour );

header( "Content-type: image/png" );
imagepng( $my_img ); # Ideally to change to png, but it should be PHP http://www.thesitewizard.com/php/create-image.shtml
#imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );

// delete variables (not necessary)
unset($output);
unset($activityRichTitle);

?>


text:
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
namespace SignalR.Client._20.Transports
{
    public class OptionalEventSignal<T> : EventSignal<T>
    {
        protected override void handleNoEventHandler()
        {
        }
    }
}

#endif


text:
package com.rawals.mymapa;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.PolyUtil;

import java.util.List;

public class DetallesCarrera extends AppCompatActivity implements OnMapReadyCallback{

    private GoogleMap map;
    Comunicador com = null;
    carrera c = null;
    Button borrar;
    TextView fecha;
    TextView distancia;
    TextView tiempo;
    TextView tipo;

    private GestorBD gestorbd = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detalles_carrera);

        gestorbd = new GestorBD(this);

        //Recogemos los valores del objeto guardado
        c = (carrera)com.getObjeto();

        fecha = (TextView) findViewById(R.id.fecha);
        distancia = (TextView) findViewById(R.id.distancia);
        tiempo = (TextView) findViewById(R.id.tiempo);
        tipo = (TextView) findViewById(R.id.tipo);
        borrar = (Button) findViewById(R.id.b_borrar_carrera);

        fecha.setText(c.getFecha());
        distancia.setText(c.getDistancia());
        tiempo.setText(c.getDuracion());
        tipo.setText(c.getTipo());

        //Para que nos salga el mapa en el cuadrado
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        borrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gestorbd.abrirBD();
                carrera c_elegido = new carrera(c.getFecha(), c.getDistancia(), c.getDuracion(),c.getPolilinea(),c.getTipo());
                gestorbd.borrarCarrera(c_elegido);
                gestorbd.cerrarBD();
                Intent intent = new Intent(DetallesCarrera.this, CarreraList.class);
                startActivity(intent);
                finish();
            }
        });

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        //Recogemos los points y los decodificamos
        List<LatLng> decodedPath = PolyUtil.decode(c.getPolilinea());
        int total = decodedPath.size();
        LatLng zoom = decodedPath.get(total/2);
    //Para centrar la camara en el medio de la polilinea
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(zoom.latitude,zoom.longitude),13));

        googleMap.addPolyline(new PolylineOptions().addAll(decodedPath));

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //Menu de los 3 puntitos
        getMenuInflater().inflate(R.menu.main, menu);

        return (super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //Menu de las opciones de los 3 puntitos
        if (item.getItemId() == R.id.legal) {
            startActivity(new Intent(this, LegalNoticesActivity.class));

            return(true);
        }

        return(super.onOptionsItemSelected(item));
    }
}


text:
package com.google.api.ads.adwords.jaxws.v201402.o;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             {@link Attribute} type that contains an {@link OpportunityIdeaType} value.
 *             For example, if a
 *             {@link com.google.ads.api.services.optimization.bulkopportunity.OpportunityIdea}
 *             represents a keyword idea, its {@link OpportunityIdeaTypeAttribute} would
 *             contain a {@code KEYWORD} {@link OpportunityIdeaType}.
 *
 *
 *
Java class for OpportunityIdeaTypeAttribute complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="OpportunityIdeaTypeAttribute">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/o/v201402}Attribute">
 *       <sequence>
 *         <element name="value" type="{https://adwords.google.com/api/adwords/o/v201402}OpportunityIdeaType" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OpportunityIdeaTypeAttribute", propOrder = {
    "value"
})
public class OpportunityIdeaTypeAttribute
    extends Attribute
{

    protected OpportunityIdeaType value;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link OpportunityIdeaType }
     *
     */
    public OpportunityIdeaType getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link OpportunityIdeaType }
     *
     */
    public void setValue(OpportunityIdeaType value) {
        this.value = value;
    }

}


text:
package org.apache.derbyTesting.unitTests.junit;

import junit.framework.Test;
import junit.framework.TestSuite;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UTFDataFormatException;

import org.apache.derby.iapi.types.ReaderToUTF8Stream;
import org.apache.derby.iapi.util.UTF8Util;

import org.apache.derbyTesting.functionTests.util.streams.CharAlphabet;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetStream;
import org.apache.derbyTesting.junit.BaseTestCase;

/**
 * Tests that skipFully and skipUntilEOF behaves
 * correctly on Derby's modfied UTF-8 encoded streams.
 *

 * These tests are dependent on the behavior of ReaderToUTF8Stream.
 * Note that this class inserts two bytes at the start of the user/application
 * stream to encode the length of the stream. These two bytes may be zero, even
 * if the stream is short enough for its length to be encoded.
 *

 * Also note that the lengths chosen for large streams are just suitably large
 * integers. The point is to choose them large enough to make sure buffer
 * boundaries are crossed.
 *
 * @see ReaderToUTF8Stream
 * @see UTF8Util
 */
public class UTF8UtilTest
    extends BaseTestCase {

    /**
     * Creates a test of the specified name.
     */
    public UTF8UtilTest(String name) {
        super(name);
    }

    /**
     * Ensure the assumption that the default looping alphabet stream and the
     * modified UTF-8 encoding is equal.
     *

     * If this assumption is broken, several of the other tests will fail.
     */
    public void testEqualityOfModifedUTF8AndASCII()
            throws IOException {
        final int length = 12706;
        InputStream ascii = new LoopingAlphabetStream(length);
        InputStream modUTF8 = new ReaderToUTF8Stream(
                                    new LoopingAlphabetReader(length),
                                    length, 0, "ignored-test-type");
        modUTF8.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        assertEquals(ascii, modUTF8);
    }

    public void testSkipUntilEOFOnZeroLengthStream()
            throws IOException {
        assertEquals(0, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(0)));
    }

    public void testSkipUntilEOFOnShortStreamASCII()
            throws IOException {
        assertEquals(5, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(5)));
    }

    public void testSkipUntilEOFOnShortStreamCJK()
            throws IOException {
        final int charLength = 5;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        assertEquals(charLength, UTF8Util.skipUntilEOF(in));
    }

    public void testSkipUntilEOFOnLongStreamASCII()
            throws IOException {
        assertEquals(127019, UTF8Util.skipUntilEOF(
                new LoopingAlphabetStream(127019)));
    }

    public void testSkipUntilEOFOnLongStreamCJK()
            throws IOException {
        final int charLength = 127019;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        assertEquals(charLength, UTF8Util.skipUntilEOF(in));
    }

    /**
     * Tests that skipFully successfully skips the requested
     * characters and returns the correct number of bytes skipped.
     *
     * @throws IOException if the test fails for some unexpected reason
     */
    public void testSkipFullyOnValidLongStreamCJK()
            throws IOException {
        final int charLength = 161019;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        // Returns count in bytes, we are using CJK chars so multiply length
        // with 3 to get expected number of bytes.
        assertEquals(charLength *3, UTF8Util.skipFully(in, charLength));
    }

    /**
     * Tests that skipFully throws exception if the stream contains
     * less characters than the requested number of characters to skip.
     *
     * @throws IOException if the test fails for some unexpected reason
     */
    public void testSkipFullyOnTooShortStreamCJK()
            throws IOException {
        final int charLength = 161019;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        try {
            UTF8Util.skipFully(in, charLength + 100);
            fail("Should have failed because of too short stream.");
        } catch (EOFException eofe) {
            // As expected, do nothing.
        }
    }

    /**
     * Tests that skipFully throws exception if there is a UTF-8
     * encoding error in the stream
     *
     * @throws IOException if the test fails for some unexpected reason
     */
    public void testSkipFullyOnInvalidStreamCJK()
            throws IOException {
        final int charLength = 10;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        in.skip(1L); // Skip one more byte to trigger a UTF error.
        try {
            UTF8Util.skipFully(in, charLength);
            fail("Should have failed because of UTF error.");
        } catch (UTFDataFormatException udfe) {
            // As expected, do nothing.
        }
    }

    /**
     * Tests a sequence of skip calls.
     */
    public void testMixedSkipOnStreamTamil()
            throws IOException {
        final int charLength = 161019;
        InputStream in = new ReaderToUTF8Stream(
                new LoopingAlphabetReader(charLength, CharAlphabet.tamil()),
                charLength, 0, "ignored-test-type");
        in.skip(2L); // Skip encoded length added by ReaderToUTF8Stream.
        int firstSkip = 10078;
        assertEquals(firstSkip*3, UTF8Util.skipFully(in, firstSkip));
        assertEquals(charLength - firstSkip, UTF8Util.skipUntilEOF(in));
        assertEquals(0, UTF8Util.skipUntilEOF(in)); // Nothing left here.
        try {
            UTF8Util.skipFully(in, 1L);
            fail("Should have failed because the stream has been drained.");
        } catch (EOFException eofe) {
            // As expected, do nothing
        }
    }

    /**
     * Tries to skip characters where the data is incomplete.
     *

     * In this test, the encoding states there is a character represented by
     * two bytes present. However, only one byte is provided.
     */
    public void testMissingSecondByteOfTwo()
            throws IOException {
        // 0xdf = 11011111
        byte[] data = {'a', (byte)0xdf};
        InputStream is = new ByteArrayInputStream(data);
        try {
            UTF8Util.skipFully(is, 2);
            fail("Reading invalid UTF-8 should fail");
        } catch (UTFDataFormatException udfe) {
            // As expected
        }
    }

    /**
     * Tries to skip characters where the data is incomplete.
     *

     * In this test, the encoding states there is a character represented by
     * three bytes present. However, only one byte is provided.
     */
    public void testMissingSecondByteOfThree()
            throws IOException {
        // 0xef = 11101111
        byte[] data = {'a', (byte)0xef};
        InputStream is = new ByteArrayInputStream(data);
        try {
            UTF8Util.skipFully(is, 2);
            fail("Reading invalid UTF-8 should fail");
        } catch (UTFDataFormatException udfe) {
            // As expected
        }
    }

    /**
     * Tries to skip characters where the data is incomplete.
     *

     * In this test, the encoding states there is a character represented by
     * three bytes present. However, only two bytes are provided.
     */
    public void testMissingThirdByteOfThree()
            throws IOException {
        // 0xef = 11101111, 0xb8 = 10111000
        byte[] data = {'a', (byte)0xef, (byte)0xb8};
        InputStream is = new ByteArrayInputStream(data);
        try {
            UTF8Util.skipFully(is, 2);
            fail("Reading invalid UTF-8 should fail");
        } catch (UTFDataFormatException udfe) {
            // As expected
        }
    }

    /**
     * Tries to read a stream of data where there is an invalid UTF-8 encoded
     * byte.
     */
    public void testInvalidUTF8Encoding()
            throws IOException {
        // 0xf8 = 11111000 <-- invalid UTF-8 encoding
        byte[] data = {'a', 'b', 'c', (byte)0xf8, 'e', 'f'};
        InputStream is = new ByteArrayInputStream(data);
        try {
            UTF8Util.skipFully(is, 6);
            fail("Reading invalid UTF-8 should fail");
        } catch (UTFDataFormatException udfe) {
            // As expected when reading invalid data
        }
    }

    /**
     * Demonstrates that skipping incorrectly encoded character sequences
     * works because the stream is not checked for well-formedness.
     */
    public void testSkippingInvalidEncodingWorks()
            throws IOException {
        // The array contains three valid characters and one invalid three-byte
        // representation that only has two bytes present.
        // When skipping, this sequence is (incorrectly) taken as a sequence of
        // three characters ('a' - some three byte character - 'a').
        // 0xef = 11101111, 0xb8 = 10111000
        byte[] data = {'a', (byte)0xef, (byte)0xb8, 'a', 'a'};
        byte[] dataWithLength =
            {0x0, 0x5, 'a', (byte)0xef, (byte)0xb8, 'a', 'a'};
        InputStream is = new ByteArrayInputStream(data);
        // This is actually incorrect, but does work currently.
        UTF8Util.skipFully(is, 3);
        // Verify that decoding this actually fails.
        DataInputStream dis = new DataInputStream(
                                    new ByteArrayInputStream(dataWithLength));
        try {
            dis.readUTF();
            fail("UTF-8 expected to be invalid, read should fail");
        } catch (UTFDataFormatException udfe) {
            // This is expected, since the UTF-8 encoding is invalid
        }
    }

    /**
     * Returns a suite of tests.
     */
    public static Test suite() {
        return new TestSuite(UTF8UtilTest.class, "UTF8Util tests");
    }
}


text:
<?php

namespace Google\Service\Document;

class GoogleCloudDocumentaiV1beta3SetDefaultProcessorVersionMetadata extends \Google\Model
{
  protected $commonMetadataType = GoogleCloudDocumentaiV1beta3CommonOperationMetadata::class;
  protected $commonMetadataDataType = '';

  /**
   * @param GoogleCloudDocumentaiV1beta3CommonOperationMetadata
   */
  public function setCommonMetadata(GoogleCloudDocumentaiV1beta3CommonOperationMetadata $commonMetadata)
  {
    $this->commonMetadata = $commonMetadata;
  }
  /**
   * @return GoogleCloudDocumentaiV1beta3CommonOperationMetadata
   */
  public function getCommonMetadata()
  {
    return $this->commonMetadata;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDocumentaiV1beta3SetDefaultProcessorVersionMetadata::class, 'Google_Service_Document_GoogleCloudDocumentaiV1beta3SetDefaultProcessorVersionMetadata');


text:
package io.pcp.parfait.timing;

import io.pcp.parfait.*;

import javax.measure.Unit;

public class CounterPairFactory {
    private final MonitorableRegistry registry;
    private final ThreadMetricSuite metricSuite;

    public CounterPairFactory(MonitorableRegistry registry, ThreadMetricSuite metricSuite) {
        this.registry = registry;
        this.metricSuite = metricSuite;
    }

    public Counter createCounterPair(Unit<?> unit, String globalCounterName, String threadMetricName,
            String threadMetricSuffix, String description) {
        MonitoredCounter metric = new MonitoredCounter(globalCounterName, description, registry, unit);
        ThreadCounter threadCounter = new ThreadCounter.ThreadMapCounter();

        ThreadMetric threadMetric = new ThreadValueMetric(threadMetricName, unit, threadMetricSuffix,
                description, threadCounter);
        metricSuite.addMetric(threadMetric);
        return new CounterPair(metric, threadCounter);
    }

}


text:
package de.atomfrede.mate.application.rest.common;

public class LoginFailedException extends Exception {

}


text:
package org.helianto.bootstrap;

import org.helianto.core.def.CategoryGroup;
import org.helianto.core.domain.Category;
import org.helianto.core.domain.Credential;
import org.helianto.core.domain.Entity;
import org.helianto.core.domain.Identity;
import org.helianto.core.domain.PublicEntity;
import org.helianto.core.domain.Unit;

/**
 * Core installation tasks.
 *
 * @author mauriciofernandesdecastro
 */
public interface CoreInstallationMgr {

	/**
	 * Install category.
	 *
     * @param entity
     * @param categoryGroup
     * @param categoryCode
	 */
	public Category installCategory(Entity entity, CategoryGroup categoryGroup, String categoryCode, String categoryName);

    /**
     *
Create Credential and Identity.

     *
     * @param principal
     */
    public Credential installIdentity(String principal);

    /**
     *
Create Credential.

     *
     * @param identity
     */
    public Credential installCredential(Identity identity);

	/**
     * Install PublicEntity.
     *
     * @param entity
     */
	public PublicEntity installPublicEntity(Entity entity);

	/**
	 * Install a unit if does not exist.
	 *
	 * @param category
	 * @param unitCode
	 * @param unitName
	 */
	public Unit installUnit(Category category, String unitCode, String unitName);

}


text:
#ifndef _IAS_TXM_API_Session_H_
#define _IAS_TXM_API_Session_H_

#include <commonlib/commonlib.h>

namespace IAS {
namespace TXM {
namespace API {

/*************************************************************************/
/** The Session class.
 *
 */
class Session {
public:

	virtual ~Session() throw(){};

	virtual void begin()=0;
	virtual void commit()=0;
	virtual void rollback()=0;

	typedef IAS_DFT_FACTORY<Session>::PtrHolder PtrHolder;
};

/*************************************************************************/
}
}
}

#endif /* _IAS_QS_API_Session_H_ */


text:
package org.apache.solr.cloud;

import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * This test is not fully functional - the port registered is illegal -
 * so you cannot hit this with http - a nice side benifit is that it will
 * detect if a node is trying to do an update to itself with http - it shouldn't
 * do that.
 */
@Slow
public class BasicZkTest extends AbstractZkTestCase {

  @BeforeClass
  public static void beforeClass() {

  }

  @Test
  public void testBasic() throws Exception {

    // test using ZooKeeper
    assertTrue("Not using ZooKeeper", h.getCoreContainer().isZooKeeperAware());

    // for the really slow/busy computer, we wait to make sure we have a leader before starting
    h.getCoreContainer().getZkController().getZkStateReader().getLeaderUrl("collection1", "shard1", 30000);

    ZkController zkController = h.getCoreContainer().getZkController();

    SolrCore core = h.getCore();

    // test that we got the expected config, not just hardcoded defaults
    assertNotNull(core.getRequestHandler("mock"));

    lrf.args.put(CommonParams.VERSION, "2.2");
    assertQ("test query on empty index", request("qlkciyopsbgzyvkylsjhchghjrdf"),
        "//result[@numFound='0']");

    // test escaping of ";"
    assertU("deleting 42 for no reason at all", delI("42"));
    assertU("adding doc#42", adoc("id", "42", "val_s", "aa;bb"));
    assertU("does commit work?", commit());

    assertQ("backslash escaping semicolon", request("id:42 AND val_s:aa\\;bb"),
        "//*[@numFound='1']", "//int[@name='id'][.='42']");

    assertQ("quote escaping semicolon", request("id:42 AND val_s:\"aa;bb\""),
        "//*[@numFound='1']", "//int[@name='id'][.='42']");

    assertQ("no escaping semicolon", request("id:42 AND val_s:aa"),
        "//*[@numFound='0']");

    assertU(delI("42"));
    assertU(commit());
    assertQ(request("id:42"), "//*[@numFound='0']");

    // test overwrite default of true

    assertU(adoc("id", "42", "val_s", "AAA"));
    assertU(adoc("id", "42", "val_s", "BBB"));
    assertU(commit());
    assertQ(request("id:42"), "//*[@numFound='1']", "//str[.='BBB']");
    assertU(adoc("id", "42", "val_s", "CCC"));
    assertU(adoc("id", "42", "val_s", "DDD"));
    assertU(commit());
    assertQ(request("id:42"), "//*[@numFound='1']", "//str[.='DDD']");

    // test deletes
    String[] adds = new String[] { add(doc("id", "101"), "overwrite", "true"),
        add(doc("id", "101"), "overwrite", "true"),
        add(doc("id", "105"), "overwrite", "false"),
        add(doc("id", "102"), "overwrite", "true"),
        add(doc("id", "103"), "overwrite", "false"),
        add(doc("id", "101"), "overwrite", "true"), };
    for (String a : adds) {
      assertU(a, a);
    }
    assertU(commit());
    int zkPort = zkServer.getPort();

    zkServer.shutdown();

    Thread.sleep(300);

    // try a reconnect from disconnect
    zkServer = new ZkTestServer(zkDir, zkPort);
    zkServer.run();

    Thread.sleep(300);

    // ensure zk still thinks node is up
    assertTrue(
        zkController.getClusterState().getLiveNodes().toString(),
        zkController.getClusterState().liveNodesContain(
            zkController.getNodeName()));

    // test maxint
    assertQ(request("q", "id:[100 TO 110]", "rows", "2147483647"),
        "//*[@numFound='4']");

    // test big limit
    assertQ(request("q", "id:[100 TO 111]", "rows", "1147483647"),
        "//*[@numFound='4']");

    assertQ(request("id:[100 TO 110]"), "//*[@numFound='4']");
    assertU(delI("102"));
    assertU(commit());
    assertQ(request("id:[100 TO 110]"), "//*[@numFound='3']");
    assertU(delI("105"));
    assertU(commit());
    assertQ(request("id:[100 TO 110]"), "//*[@numFound='2']");
    assertU(delQ("id:[100 TO 110]"));
    assertU(commit());
    assertQ(request("id:[100 TO 110]"), "//*[@numFound='0']");

    // SOLR-2651: test that reload still gets config files from zookeeper
    zkController.getZkClient().setData("/configs/conf1/solrconfig.xml", new byte[0], true);

    // we set the solrconfig to nothing, so this reload should fail
    try {
      ignoreException("solrconfig.xml");
      h.getCoreContainer().reload(h.getCore().getName());
      fail("The reloaded SolrCore did not pick up configs from zookeeper");
    } catch(SolrException e) {
      resetExceptionIgnores();
      assertTrue(e.getMessage().contains("Unable to reload core [collection1]"));
      assertTrue(e.getCause().getMessage().contains("Error loading solr config from solrconfig.xml"));
    }

    // test stats call
    NamedList stats = core.getStatistics();
    assertEquals("collection1", stats.get("coreName"));
    assertEquals("collection1", stats.get("collection"));
    assertEquals("shard1", stats.get("shard"));
    assertTrue(stats.get("refCount") != null);

    //zkController.getZkClient().printLayoutToStdOut();
  }

  public SolrQueryRequest request(String... q) {
    LocalSolrQueryRequest req = lrf.makeRequest(q);
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add(req.getParams());
    params.set("distrib", false);
    req.setParams(params);
    return req;
  }

  @AfterClass
  public static void afterClass() {

  }
}


text:
package org.apache.carbondata.core.datastore.columnar;

import java.util.Arrays;

import org.apache.carbondata.core.util.ByteUtil.UnsafeComparer;

public class ColumnWithIntIndexForHighCard extends ColumnWithIntIndex
    implements Comparable<ColumnWithIntIndex> {

  public ColumnWithIntIndexForHighCard(byte[] column, int index) {
    super(column, index);
  }

  @Override public int compareTo(ColumnWithIntIndex o) {
    return UnsafeComparer.INSTANCE
        .compareTo(column, 2, column.length - 2, o.column, 2, o.column.length - 2);
  }

  @Override public boolean equals(Object obj) {
    if (obj == null || getClass() != obj.getClass()) {
      return false;
    }
    ColumnWithIntIndexForHighCard o = (ColumnWithIntIndexForHighCard)obj;
    return Arrays.equals(column, o.column) && getIndex() == o.getIndex();
  }

  @Override public int hashCode() {
    return Arrays.hashCode(column) + getIndex();
  }
}


text:
from egat.execution_groups import execution_group
from egat.testset import SequentialTestSet

# This class demonstrates how to use an execution group. By annotating this class with
# an execution group we specify that if one of the methods in the class fails then the
# rest of the methods should be skipped. Execution groups can be added to classes or
# functions, and can span multiple files as long as the id you pass to the
# decorator stays the same.
# You can test this by running this command from the root directory of the project:
#   ./egatest examples.execution_group_example
#
# You should see in the test output that the testFooWasCreated() method was skipped.
@execution_group("FooExecutionGroup")
class TestFooCreation(SequentialTestSet):
    def testOpenFooPage(self):
        assert(True)

    def testClickCreateFooButton(self):
        assert(False)

    def testFooWasCreated(self):
        assert(True)


text:
import fresh_tomatoes

import media

# movie title, storyline, poster image and movie trailer
american_sniper = media.Movie(
    "American Sniper",
     "True story of a true American hero, Chris Kyle",
     "http://t2.gstatic.com/images?q=tbn:ANd9GcSCEJMtX2_SB-ZlvYpabgPb6dwI_bVSY-eVap6aSSSfFq5Ldmxa",  # NOQA
     "https://www.youtube.com/watch?v=99k3u9ay1gs")

# movie title, storyline, poster image and movie trailer
mission_impossible = media.Movie(
    "Mission Impossible",
    "Ethan Hunt needs to prove his innocence and keep the world safe",
    "https://upload.wikimedia.org/wikipedia/en/e/e1/MissionImpossiblePoster.jpg",  # NOQA
    "https://www.youtube.com/watch?v=gOW_azQbOjw")

# movie title, storyline, poster image and movie trailer
wonder_woman = media.Movie(
    "Wonder Woman",
    "Diana Prince comes out from the shadows to save the world",
    "http://t1.gstatic.com/images?q=tbn:ANd9GcQcCAOmt-FsRsR8GebIzI67qSvdQ2JLYDRLxeAcbH-541fzqq1H",  # NOQA
    "https://www.youtube.com/watch?v=VSB4wGIdDwo")

# movie title, storyline, poster image and movie trailer
the_hobbit = media.Movie(
    "The Hobbit",
    "A reluctant hobbit, Bilbo Baggins, sets out on a journey with a"
    "spirited group of dwarves to reclaim their home",
    "http://cdn.collider.com/wp-content/uploads/hobbit-unexpected-journey-imax-poster-andy-serkis.jpg",  # NOQA
    "https://www.youtube.com/watch?v=nOGsB9dORBg")

# movie title, storyline, poster image and movie trailer
the_avengers = media.Movie(
    "The Avengers",
    "Earth's mightiest heroes need to work together to save the world",
    "https://upload.wikimedia.org/wikipedia/en/f/f9/TheAvengers2012Poster.jpg",  # NOQA
    "https://www.youtube.com/watch?v=eOrNdBpGMv8")

# movie: movie title, storyline, poster image and movie trailer
zero_dark_thirty = media.Movie(
    "Zero Dark Thirty",
    "The Greatest Manhunt in History",
    "http://static.metacritic.com/images/products/movies/8/a22d5b5f78fbbea4f6f8f19b6dbd00e5.jpg",   # NOQA
    "www.youtube.com/watch?v=mejkiIvnkzY")

# set the movies to be passed to the media file
movies = [
    american_sniper,
    mission_impossible,
    wonder_woman,
    the_hobbit,
    the_avengers,
    zero_dark_thirty
]

# open the HTML file in a web browser via the fresh_tomatoes.py file
fresh_tomatoes.open_movies_page(movies)


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
define(["require", "exports", "./plane", "../../common/base_sketch", "../../utils/load_utils"], function (require, exports, plane_1, base_sketch_1, load_utils_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Sketch = /** @class */ (function (_super) {
        __extends(Sketch, _super);
        function Sketch() {
            var _this = _super.call(this) || this;
            _this.windowWidth = 0;
            _this.windowHeight = 0;
            _this.counter = 0;
            load_utils_1.LoadUtils.LoadShaders(["../../scripts/ts/sketches/TrianglesTransitionSketch/frag1.glsl",
                "../../scripts/ts/sketches/TrianglesTransitionSketch/frag2.glsl",
                "../../scripts/ts/sketches/TrianglesTransitionSketch/vert1.glsl",
                "../../scripts/ts/sketches/TrianglesTransitionSketch/vert2.glsl"]).then(function (src) {
                _this.handleLoad(src);
            });
            return _this;
        }
        Sketch.prototype.draw = function (time) {
            if (this.renderer) {
                this.renderer.clear();
                this.renderMaterial.uniforms["time"].value = time;
                this.updateBottomLine();
                this.renderer.render(this.renderScene, this.camera, this.renderTexture, true);
                this.material.uniforms["time"].value = time;
                this.renderer.render(this.scene, this.camera);
            }
        };
        Sketch.prototype.updateBottomLine = function () {
            this.planes.forEach(function (plane) {
                plane.update();
            });
        };
        Sketch.prototype.resize = function (windowWidth, windowHeight) {
            this.windowWidth = windowWidth;
            this.windowHeight = windowHeight;
            if (this.renderer) {
                this.renderer.setSize(windowWidth, windowHeight);
            }
            if (this.renderTexture)
                this.renderTexture.setSize(windowWidth, windowHeight);
        };
        //------------------------------------------------------
        Sketch.prototype.handleLoad = function (src) {
            this.renderer = new THREE.WebGLRenderer({ alpha: true });
            this.renderer.setClearColor(0x000000, 0);
            this.renderer.setPixelRatio(window.devicePixelRatio);
            this.renderer.setSize(window.innerWidth, window.innerHeight);
            this.el.appendChild(this.renderer.domElement);
            this.camera = new THREE.Camera();
            this.renderScene = new THREE.Scene();
            this.renderTexture = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight, {
                minFilter: THREE.LinearFilter,
                magFilter: THREE.NearestFilter,
                format: THREE.RGBAFormat
            });
            this.renderMaterial = new THREE.RawShaderMaterial({
                uniforms: { time: { value: 0 } },
                vertexShader: src[3],
                fragmentShader: src[1]
            });
            var count = 10;
            var distance = window.innerWidth / window.innerHeight * (2 / count);
            this.planes = [];
            for (var i = 0; i < count; i++) {
                var l = { x: -1 + i * 2 / count, y: 1 };
                var r = { x: l.x + 2 / count, y: 1 };
                var plane = new plane_1.Plane(l, r, distance);
                this.planes.push(plane);
                var mesh = new THREE.Mesh(plane.renderPlane, this.renderMaterial);
                this.renderScene.add(mesh);
            }
            //set up rendered scene...
            this.scene = new THREE.Scene();
            this.material = new THREE.RawShaderMaterial({
                uniforms: {
                    time: { value: 0 },
                    texture: { value: this.renderTexture.texture },
                    resolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) }
                },
                vertexShader: src[2],
                fragmentShader: src[0]
            });
            this.material.transparent = true;
            this.material.alphaTest = 0;
            this.material.depthWrite = false;
            var planeBuffer = new THREE.PlaneBufferGeometry(2, 2);
            this.mesh = new THREE.Mesh(planeBuffer, this.material);
            this.scene.add(this.mesh);
        };
        return Sketch;
    }(base_sketch_1.BaseSketch));
    exports.Sketch = Sketch;
});
//# sourceMappingURL=TrianglesTransitionSketch.js.map


text:
OC.L10N.register(
    "files_sharing",
    {
    "Server to server sharing is not enabled on this server" : "Šajā serverī koplietošana starp serveriem nav ieslēgta",
    "The mountpoint name contains invalid characters." : "Montēšanas punkta nosaukums satur nederīgus simbolus.",
    "Invalid or untrusted SSL certificate" : "Nepareizs vai neuzticams SSL sertifikāts",
    "Could not authenticate to remote share, password might be wrong" : "Nesanāca autentificēties pie attālinātās koplietotnes, parole varētu būt nepareiza",
    "Storage not valid" : "Glabātuve nav derīga",
    "Couldn't add remote share" : "Nevarēja pievienot attālināto koplietotni",
    "Shared with you" : "Kopīgots ar tevi",
    "Shared with others" : "Kopīgots ar citiem",
    "Shared by link" : "Kopīgots ar saiti",
    "Uploaded files" : "Augšupielādētie faili",
    "Uploading..." : "Augšupielādē...",
    "Nothing shared with you yet" : "Nekas vēl nav kopīgots",
    "Files and folders others share with you will show up here" : "Faili un mapes, ko citi koplietos ar tevi, tiks rādīti šeit",
    "Nothing shared yet" : "Nekas vēl nav kopīgots",
    "Files and folders you share will show up here" : "Faili un mapes, ko koplietosi ar citiem, tiks rādīti šeit",
    "No shared links" : "Nav kopīgotu saišu",
    "Files and folders you share by link will show up here" : "Faili un mapes, ko koplietosit ar saitēm, tiks rādīti šeit",
    "Do you want to add the remote share {name} from {owner}@{remote}?" : "Vai vēlaties pievienot attālināto koplietotni {name} no {owner}@{remote}?",
    "Remote share" : "Attālinātā koplietotne",
    "Remote share password" : "Attālinātās koplietotnes parole",
    "Cancel" : "Atcelt",
    "Add remote share" : "Pievienot attālināto koplietotni",
    "You can upload into this folder" : "Jūs variet augšuplādēt šajā mapē",
    "No ownCloud installation (7 or higher) found at {remote}" : "Nav atrasta neviena ownCloud (7. vai augstāka) instalācija {remote}",
    "Invalid ownCloud url" : "Nederīga ownCloud saite",
    "Share" : "Dalīties",
    "Declined" : "Noraidīts",
    "Pending" : "Gaida savu kārtu",
    "Shared by" : "Dalījās",
    "Sharing" : "Dalīšanās",
    "A file or folder has been shared" : "Koplietota fails vai mape",
    "A file or folder was shared from another server" : "Fails vai mape tika kopīgota no cita servera",
    "A public shared file or folder was downloaded" : "Publiski kopīgots fails vai mape tika lejupielādēts",
    "You received a new remote share %2$s from %1$s" : "Jūs saņēmāt jaunu attālinātu koplietotni %2$s no %1$s",
    "You received a new remote share from %s" : "Saņēmāt jaunu attālinātu koplietotni no %s",
    "%1$s accepted remote share %2$s" : "%1$s apstiprināja attālināto koplietotni %2$s",
    "%1$s declined remote share %2$s" : "%1$s noraidīja attālināto koplietotni %2$s",
    "%1$s unshared %2$s from you" : "%1$s atslēdza kopīgošanu %2$s ar tevi",
    "Public shared folder %1$s was downloaded" : "Publiski kopīgota mape %1$s tika lejupielādēta",
    "Public shared file %1$s was downloaded" : "Publiski kopīgots fails %1$s tika lejupielādēts",
    "You shared %1$s with %2$s" : "Tu kopīgoji %1$s ar %2$s",
    "%2$s shared %1$s with %3$s" : "%2$s kopīgots %1$s ar %3$s",
    "You removed the share of %2$s for %1$s" : "Tu noņēmi koplietošanu no %2$s priekš %1$s",
    "%2$s removed the share of %3$s for %1$s" : "%2$s noņēma koplietošanu no %3$s priekš %1$s",
    "You shared %1$s with group %2$s" : "Tu kopīgoji %1$s ar grupu %2$s",
    "%2$s shared %1$s with group %3$s" : "%2$s kopīgots %1$s ar grupu %3$s",
    "You removed the share of group %2$s for %1$s" : "Tu noņēmi koplietošanu no grupas %2$s priekš %1$s",
    "%2$s removed the share of group %3$s for %1$s" : "%2$s noņēma koplietošanu no gruapas %3$s priekš %1$s",
    "%2$s shared %1$s via link" : "%2$s kopīgots %1$s ,izmantojot saiti ",
    "You shared %1$s via link" : "Tu kopīgoji %1$s , izmantojot saiti",
    "You removed the public link for %1$s" : "Jūs noņēmāt publisko saiti no %1$s",
    "%2$s shared %1$s with you" : "%2$s kopīgoja %1$s ar tevi",
    "Downloaded via public link" : "Lejupielādēts, izmantojot publisku saiti",
    "Shared with %2$s" : "Kopīgots ar %2$s",
    "Shared with %3$s by %2$s" : "%2$s kopīgoja ar %3$s",
    "Unshared %1$s from self" : "Atslēdzā sev %1$s kopīgošanu",
    "Shared with group %2$s" : "Kopīgots ar grupu %2$s",
    "Shared with group %3$s by %2$s" : "%2$s kopīgoja ar grupu %3$s",
    "Shared via link by %2$s" : "%2$s kopīgoja ar saiti",
    "Shared via public link" : "Kopīgots ar publisku saiti",
    "Shared by %2$s" : "%2$s kopīgoja",
    "Shares" : "Koplietotie",
    "File sharing" : "Failu kopīgošana",
    "Public link" : "Publiska saite",
    "Share API is disabled" : "Koplietošanas API ir atslēgta",
    "Wrong share ID, share doesn't exist" : "Nepareizs koplietošanas ID, koplietotne neeksistē",
    "Could not delete share" : "Neizdevās dzēst koplietotni",
    "Please specify a file or folder path" : "Lūdzu norādiet datnes vai mapes ceļu",
    "Wrong path, file/folder doesn't exist" : "Nepareizs ceļš, datne/mape neeksistē",
    "Invalid date, date format must be YYYY-MM-DD" : "Nepareizs datums, datumam jābūt YYYY-MM-DD formātā",
    "Please specify a valid user" : "Lūdzu norādiet derīgu lietotāju",
    "Group sharing is disabled by the administrator" : "Administrators grupas koplietošanu ir atslēdzis",
    "Please specify a valid group" : "Lūdzu norādiet derīgu grupu",
    "The group is blacklisted for sharing" : "Grupa ir melnajā saraksta un nevar izmantot kopīgošanu",
    "Public link sharing is disabled by the administrator" : "Administrators publisku saites koplietošanu ir atslēdzis",
    "Public upload disabled by the administrator" : "Administrators publisku augšupielādi ir atslēdzis",
    "Public upload is only possible for publicly shared folders" : "Publiska augšupielāde iespējama tikai publiski kopīgotām mapēm",
    "Unknown share type" : "Nezināms koplietošanas tips",
    "Could not lock path" : "Nevarēja bloķēt ceļu",
    "Can't change permissions for public share links" : "Publiskai koplietošanas saitei nevar mainīt tiesības",
    "\"%1$s\" shared \"%3$s\" with you" : "%1$s kopīgoja %3$s ar tevi",
    "Accept" : "Akceptēt",
    "Decline" : "Atteikties",
    "This share is password-protected" : "Šī koplietotne ir aizsargāta ar paroli",
    "The password is wrong. Try again." : "Nepareiza parole. Mēģiniet vēlreiz.",
    "Password" : "Parole",
    "No entries found in this folder" : "Šajā mapē nekas nav atrasts",
    "Name" : "Nosaukums",
    "State" : "Stāvoklis",
    "Share time" : "Koplietošanas laiks",
    "Expiration date" : "Termiņa datums",
    "Sorry, this link doesn't seem to work anymore." : "Izskatās, ka šī saite vairs nedarbojas",
    "Reasons might be:" : "Iespējamie iemesli:",
    "the item was removed" : "vienums tika dzēsts",
    "the link expired" : "saitei beidzies termiņš",
    "sharing is disabled" : "koplietošana nav ieslēgta",
    "For more info, please ask the person who sent this link." : "Vairāk informācijas vaicā personai, kas nosūtīja šo saiti.",
    "%s is publicly shared" : "%s ir publiski kopīgots",
    "Download" : "Lejupielādēt",
    "Download %s" : "Lejupielādēt %s",
    "Direct link" : "Tiešā saite",
    "Group Sharing Blacklist" : "Grupu kopīgošanas melnais saraksts"
},
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);");


text:
package org.wso2.developerstudio.eclipse.capp.core.utils;

import java.io.File;

import org.wso2.developerstudio.eclipse.capp.core.Activator;
import org.wso2.developerstudio.eclipse.capp.core.artifacts.ICAppArtifactHandler;
import org.wso2.developerstudio.eclipse.capp.core.artifacts.manager.CAppEnvironment;
import org.wso2.developerstudio.eclipse.capp.core.data.Bundle;
import org.wso2.developerstudio.eclipse.capp.core.manifest.Artifact;
import org.wso2.developerstudio.eclipse.capp.core.manifest.CARArtifactFeatureManifest;
import org.wso2.developerstudio.eclipse.capp.core.manifest.SimpleJarManifest;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;

public class ArtifactFeatureCreator {
	private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);

	private Artifact artifact;
	private String parentApplication;
	private File location;

	public ArtifactFeatureCreator(Artifact artifact,File location, String parentApplication) {
	    setArtifact(artifact);
	    setParentApplication(parentApplication);
	    setLocation(location);
    }

	public void setArtifact(Artifact artifact) {
	    this.artifact = artifact;
    }

	public Artifact getArtifact() {
	    return artifact;
    }

	public void setParentApplication(String parentApplication) {
	    this.parentApplication = parentApplication;
    }

	public String getParentApplication() {
	    return parentApplication;
    }

	public void setLocation(File location) {
	    this.location = location;
    }

	public File getLocation() {
	    return location;
    }

	public File getFeature() throws Exception{
		File tmpFolder;
        try {
	        tmpFolder = FileUtils.createTempDirectory();
	        File pluginsPath = new File(tmpFolder,"plugins");
	        File featuresPath = new File(tmpFolder,"features");
	        File featurePath = new File(featuresPath,artifact.getName()+"_"+artifact.getVersion());
	        File featureMetaInfPath = new File(featurePath,"META-INF");
	        featureMetaInfPath.mkdirs();
	        pluginsPath.mkdirs();
	        File featureManifestFile = new File(featureMetaInfPath,"MANIFEST.MF");
	        new SimpleJarManifest().toFile(featureManifestFile);
	        File featureXmlManifestFile = new File(featurePath,"feature.xml");
	        CARArtifactFeatureManifest carArtifactFeatureManifest = new CARArtifactFeatureManifest(artifact);
	        ICAppArtifactHandler artifactHandler = CAppEnvironment.getcAppManager().getArtifactHandler(artifact);
	        File bundle;
	        if (artifactHandler!=null) {
	            bundle = artifactHandler.getBundle(getLocation(), artifact, getParentApplication());
            }else{
            	bundle = new ArtifactBundleCreator(artifact, location, parentApplication).getBundle();
            }
            FileUtils.copy(bundle, new File(pluginsPath, bundle.getName()));
	        Bundle artifactBundle = new Bundle();
	        artifactBundle.setName(artifact.getName());
	        artifactBundle.setVersion(artifact.getTimestampedVersion());
	        artifactBundle.setUnpack(false);
	        carArtifactFeatureManifest.getBundles().add(artifactBundle);
	        carArtifactFeatureManifest.toFile(featureXmlManifestFile);
			return tmpFolder;
        } catch (Exception e) {
	        log.error(e);
	        throw e;
        }
	}
}


text:
<!doctype html>

<title>CodeMirror: Smarty mixed mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">

Home

Manual

Code

Language modes

Smarty mixed

Smarty mixed mode

    <form><textarea id="code" name="code">
        {**
        * @brief Smarty mixed mode
        * @author Ruslan Osmanov
        * @date 29.06.2013
        *}

            <title>{$title|htmlspecialchars|truncate:30}</title>

        {* Multiline smarty
        * comment, no {$variables} here
        *}
        {literal}
        {literal} is just an HTML text.

        {/literal}

        {extends file="parent.tpl"}
        {include file="template.tpl"}

        {* some example Smarty content *}
        {if isset($name) && $name == 'Blog'}
        This is a {$var}.
        {$integer = 4511}, {$array[] = "a"}, {$stringvar = "string"}
        {$integer = 4512} {$array[] = "a"} {$stringvar = "string"}
        {assign var='bob' value=$var.prop}
        {elseif $name == $foo}
        {function name=menu level=0}
        {foreach $data as $entry}
        {if is_array($entry)}
        - {$entry@key}
        {menu data=$entry level=$level+1}
        {else}
        {$entry}
        {* One
        * Two
        * Three
        *}
        {/if}
        {/foreach}
        {/function}
        {/if}

    </textarea></form>

The Smarty mixed mode depends on the Smarty and HTML mixed modes. HTML
        mixed mode itself depends on XML, JavaScript, and CSS modes.

It takes the same options, as Smarty and HTML mixed modes.

MIME types defined: text/x-smarty.


text:
function out = RRtestAccessVariable(obj, fieldname)
%RRtestAccessVariable Will return a character vector of the variable linked
%to the given standard. In the case that there is nothing linked, it will
%return 0.
%   GO THROUGH AND FIX THIS BECAUSE THIS IS BAD

%% Error Handling

if class(obj) ~= 'RebelRacingData'
    error('Object %s is not of type RebelRacingData',obj);
end

if RRtestAccessStatus(obj,1,fieldname)
    out = getfield(obj.RRtestAccess.(fieldname),'VariableName'); %#ok<*GFLD>
else
    out = false;
end

end


text:
/*
 * GeoIP C library binding for nodejs
 *
 * Licensed under the GNU LGPL 2.1 license
 */

#include "utils.h"
#include "global.h"

namespace native {
    namespace utils {
        NAN_METHOD(isString) {
            NanScope();

            Local<Boolean> result = NanNew(args[0].As<Object>()->IsString() ? NanTrue() : NanFalse());

            NanReturnValue(result);
        }

        NAN_METHOD(check) {
            NanScope();

            Local<Value> edition = NanNew(NanNull());
            Local<String> file_str = args[0]->ToString();
            size_t size = file_str->Length() + 1;
            char file_cstr[size];
            size_t bc;
            NanCString(args[0], &bc, file_cstr, size);

            GeoIP *db = GeoIP_open(file_cstr, GEOIP_STANDARD);

            if (db) {
                int db_edition = GeoIP_database_edition(db);

                switch(db_edition) {
                    case GEOIP_COUNTRY_EDITION:
                        edition = NanNew<String>("country");
                        break;

                    case GEOIP_COUNTRY_EDITION_V6:
                        edition = NanNew<String>("country_v6");
                        break;

                    case GEOIP_CITY_EDITION_REV0:
                        edition = NanNew<String>("city");
                        break;

                    case GEOIP_CITY_EDITION_REV1:
                        edition = NanNew<String>("city");
                        break;

                    case GEOIP_CITY_EDITION_REV0_V6:
                        edition = NanNew<String>("city_v6");
                        break;

                    case GEOIP_CITY_EDITION_REV1_V6:
                        edition = NanNew<String>("city_v6");
                        break;

                    case GEOIP_REGION_EDITION_REV0:
                        edition = NanNew<String>("region");
                        break;

                    case GEOIP_REGION_EDITION_REV1:
                        edition = NanNew<String>("region");
                        break;

                    case GEOIP_ORG_EDITION:
                        edition = NanNew<String>("org");
                        break;

                    case GEOIP_ISP_EDITION:
                        edition = NanNew<String>("isp");
                        break;

                    case GEOIP_ASNUM_EDITION:
                        edition = NanNew<String>("asnum");
                        break;

                    case GEOIP_PROXY_EDITION:
                        edition = NanNew<String>("proxy");
                        break;

                    case GEOIP_NETSPEED_EDITION:
                        edition = NanNew<String>("netspeed");
                        break;

                    case GEOIP_NETSPEED_EDITION_REV1:
                        edition = NanNew<String>("netspeed cellular");
                        break;

                    case GEOIP_DOMAIN_EDITION:
                        edition = NanNew<String>("domain");
                        break;

                    default:
                        edition = NanNew<String>("unknown");
                }

                GeoIP_delete(db);
                db = NULL;

                NanReturnValue(edition);
            }

            return NanThrowError("Error: Cannot open database");
        }
    }
}


text:
from . import util
from okcupyd import User, photo

@util.use_cassette(path='photo_upload',
                   match_on=util.match_on_no_body)
def test_photo_upload():
    uploader = photo.PhotoUploader()
    upload_response_dict = uploader.upload_and_confirm('fixtures/image.jpg')
    assert int(upload_response_dict['id']) > 0

@util.use_cassette(path='test_photo_delete', match_on=util.match_on_no_body)
def test_photo_delete():
    user = User()
    response_dict = user.photo.upload_and_confirm(user.quickmatch().photo_infos[0])
    before_delete_photos = user.profile.photo_infos
    user.photo.delete(response_dict['id'])
    user.profile.refresh()
    assert len(before_delete_photos) - 1 == len(user.profile.photo_infos)

def test_make_photo_uri_from_https_link():
    photo_info = photo.Info.from_cdn_uri(
        'https://k0.okccdn.com/php/load_okc_image'
        '.php/images/150x150/558x800/0x21/400x421/0'
        '/2254475731855279447.webp?v=2'
    )
    assert photo_info.id == 2254475731855279447
    assert photo_info.thumb_nail_top == 21

@util.use_cassette
def test_photo_info_upload(vcr_live_sleep):
    user = User()
    response = user.photo.upload_and_confirm(user.quickmatch().photo_infos[0])
    vcr_live_sleep(2)
    assert int(response['id']) in [pi.id for pi in user.profile.photo_infos]


text:
namespace DaocClientLib.Drawing
{
	using System;
	using System.IO;
	using System.Collections.Generic;
	using System.Linq;

	using Niflib;
	using Niflib.Extensions;

	#if OpenTK
	using OpenTK;
	using Matrix = OpenTK.Matrix4;
	#elif SharpDX
	using SharpDX;
	#elif MonoGame
	using Microsoft.Xna.Framework;
	#endif

	/// <summary>
	/// ZoneRenderer Build primitive 3D object From Zone Geometry Data
	/// </summary>
	public class ZoneRenderer : ZoneGeometry
	{
		/// <summary>
		/// Client Data Wrapper for Accessing Geometry Data
		/// </summary>
		protected ClientDataWrapper ClientWrapper { get; set; }

		/// <summary>
		/// Nif Primitives Cache
		/// </summary>
		public IDictionary<int, ClientMesh> NifCache { get; protected set; }

		/// <summary>
		/// Nif Instances Matrix
		/// Index Nif Cache Meshes with a World Instance Matrix
		/// </summary>
		public KeyValuePair<int, Matrix>[] InstancesMatrix { get; protected set; }

		/// <summary>
		/// TreeReplacement Map Cache
		/// </summary>
		protected TreeReplacementMap TreeReplacement { get; set; }

		/// <summary>
		/// Matrix To rotate Meshes
		/// </summary>
		protected static Matrix RotationMatrix = Matrix.CreateRotationX((float)(Math.PI / -2f));

		/// <summary>
		/// Layers Categories to Retrieve From Nif Objects
		/// </summary>
		protected virtual IDictionary<string, string[]> Layers
		{
			get
			{
				return new Dictionary<string, string[]> {
					{ "pickee", new []{ "pickee", "collidee", "visible", "exterior", "near", } },
					{ "collidee", new []{ "collidee", "visible", "exterior", "near", } },
					{ "visible", new []{ "visible", "exterior", "near", } },
					{ "climb", new []{ "climb[0-9]{3}", } },
					{ "door", new []{ "door[0-9]{3}", } },
				};
			}
		}

		/// <summary>
		/// Default Constructor
		/// </summary>
		/// <param name="id"></param>
		/// <param name="files"></param>
		/// <param name="type"></param>
		/// <param name="wrapper"></param>
		public ZoneRenderer(int id, IEnumerable<FileInfo> files, ZoneType type, ClientDataWrapper wrapper)
			: base(id, files, type)
		{
			TreeReplacement = wrapper.TreeReplacement;
			NifCache = new Dictionary<int, ClientMesh>();
			InstancesMatrix = new KeyValuePair<int, Matrix>[0];
			ClientWrapper = wrapper;
		}

		/// <summary>
		/// Init Nif Cache with a collection of Nifs References
		/// </summary>
		/// <param name="nifs"></param>
		protected void AddNifCache(IDictionary<int, string> nifs)
		{
			// Store Nifs Meshes
			foreach(var nif in nifs)
				AddNifMesh(nif.Key, nif.Value);
		}

		/// <summary>
		/// Add Nif Reference in Mesh Cache
		/// </summary>
		/// <param name="id"></param>
		/// <param name="nif"></param>
		protected void AddNifMesh(int id, string nif)
		{
			var trees = TreeReplacement[nif];

			var nifName = nif;
			// Tree match, replace nif name
			if (trees.Length > 0)
			{
				nifName = trees.First().RealNif;
			}

			// Store Layered Nif in Cache
			var meshes = GetNifMeshFromName(nif);
			NifCache.Add(id, meshes);
		}

		/// <summary>
		/// Search Nif File Name through all Client Files and extract Primitives Layers needed for displaying
		/// </summary>
		/// <param name="nifname"></param>
		/// <returns></returns>
		protected ClientMesh GetNifMeshFromName(string nifname)
		{
			// Get File Bytes
			var bytes = ClientWrapper.SearchRawFileOrPackaged(nifname, new []{ ".npk", ".mpk" });

			if (bytes != null)
			{
				return new ClientMesh(nifname, bytes);
			}

			return null;
		}
	}
}


text:
<?php

namespace Knnf\WhatsupBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('lastname')
            ->add('username')
            ->add('email')
            ->add('password')
            ->add('website')
             ->add('birthday','date',array('widget' => 'single_text',
                                                'input' => 'datetime',
                                                'format' => 'dd/MM/yyyy',
                                                'attr' => array('class' => 'date')
                                                ))
            ->add('photo')
            ->add('country')
            ->add('city')
            ->add('zipcode')
            ->add('description')
            //->add('dateinsert')
            //->add('dateupdate')
            //->add('activate')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Knnf\WhatsupBundle\Entity\User'
        ));
    }

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


text:
#include "ruby.h"
#include "rubyio.h"

#include <assert.h>

#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

/* 1 GiB maximum buffer size */
#define MAX_BUFFER_SIZE 0x40000000

/* Macro for retrieving the file descriptor from an FPTR */
#if !HAVE_RB_IO_T_FD
#define FPTR_TO_FD(fptr) fileno(fptr->f)
#else
#define FPTR_TO_FD(fptr) fptr->fd
#endif

/* Default number of bytes in each node's buffer.  Should be >= MTU */
#define DEFAULT_NODE_SIZE 16384
static unsigned default_node_size = DEFAULT_NODE_SIZE;

struct buffer {
    unsigned size, node_size;
    struct buffer_node *head, *tail;
    struct buffer_node *pool_head, *pool_tail;

};

struct buffer_node {
    unsigned start, end;
    struct buffer_node *next;
    unsigned char   data[0];
};

static VALUE    cIO_Buffer = Qnil;

static VALUE    IO_Buffer_allocate(VALUE klass);
static void     IO_Buffer_mark(struct buffer *);
static void     IO_Buffer_free(struct buffer *);

static VALUE    IO_Buffer_default_node_size(VALUE klass);
static VALUE    IO_Buffer_set_default_node_size(VALUE klass, VALUE size);
static VALUE    IO_Buffer_initialize(int argc, VALUE * argv, VALUE self);
static VALUE    IO_Buffer_clear(VALUE self);
static VALUE    IO_Buffer_size(VALUE self);
static VALUE    IO_Buffer_empty(VALUE self);
static VALUE    IO_Buffer_append(VALUE self, VALUE data);
static VALUE    IO_Buffer_prepend(VALUE self, VALUE data);
static VALUE    IO_Buffer_read(int argc, VALUE * argv, VALUE self);
static VALUE    IO_Buffer_read_frame(VALUE self, VALUE data, VALUE mark);
static VALUE    IO_Buffer_to_str(VALUE self);
static VALUE    IO_Buffer_read_from(VALUE self, VALUE io);
static VALUE    IO_Buffer_write_to(VALUE self, VALUE io);

static struct buffer *buffer_new(void);
static void     buffer_clear(struct buffer * buf);
static void     buffer_free(struct buffer * buf);
static void     buffer_free_pool(struct buffer * buf);
static void     buffer_prepend(struct buffer * buf, char *str, unsigned len);
static void     buffer_append(struct buffer * buf, char *str, unsigned len);
static void     buffer_read(struct buffer * buf, char *str, unsigned len);
static int      buffer_read_frame(struct buffer * buf, VALUE str, char frame_mark);
static void     buffer_copy(struct buffer * buf, char *str, unsigned len);
static int      buffer_read_from(struct buffer * buf, int fd);
static int      buffer_write_to(struct buffer * buf, int fd);

/*
 * High-performance I/O buffer intended for use in non-blocking programs
 *
 * Data is stored in as a memory-pooled linked list of equally sized chunks.
 * Routines are provided for high speed non-blocking reads and writes from
 * Ruby IO objects.
 */
void
Init_iobuffer_ext()
{
    cIO_Buffer = rb_define_class_under(rb_cIO, "Buffer", rb_cObject);
    rb_define_alloc_func(cIO_Buffer, IO_Buffer_allocate);

    rb_define_singleton_method(cIO_Buffer, "default_node_size",
                   IO_Buffer_default_node_size, 0);
    rb_define_singleton_method(cIO_Buffer, "default_node_size=",
                   IO_Buffer_set_default_node_size, 1);

    rb_define_method(cIO_Buffer, "initialize", IO_Buffer_initialize, -1);
    rb_define_method(cIO_Buffer, "clear", IO_Buffer_clear, 0);
    rb_define_method(cIO_Buffer, "size", IO_Buffer_size, 0);
    rb_define_method(cIO_Buffer, "empty?", IO_Buffer_empty, 0);
    rb_define_method(cIO_Buffer, "<<", IO_Buffer_append, 1);
    rb_define_method(cIO_Buffer, "append", IO_Buffer_append, 1);
    rb_define_method(cIO_Buffer, "write", IO_Buffer_append, 1);
    rb_define_method(cIO_Buffer, "prepend", IO_Buffer_prepend, 1);
    rb_define_method(cIO_Buffer, "read", IO_Buffer_read, -1);
    rb_define_method(cIO_Buffer, "read_frame", IO_Buffer_read_frame, 2);
    rb_define_method(cIO_Buffer, "to_str", IO_Buffer_to_str, 0);
    rb_define_method(cIO_Buffer, "read_from", IO_Buffer_read_from, 1);
    rb_define_method(cIO_Buffer, "write_to", IO_Buffer_write_to, 1);

    rb_define_const(cIO_Buffer, "MAX_SIZE", INT2NUM(MAX_BUFFER_SIZE));
}

static VALUE
IO_Buffer_allocate(VALUE klass)
{
    return Data_Wrap_Struct(klass, IO_Buffer_mark, IO_Buffer_free, buffer_new());
}

static void
IO_Buffer_mark(struct buffer * buf)
{
    /* Naively discard the memory pool whenever Ruby garbage collects */
    buffer_free_pool(buf);
}

static void
IO_Buffer_free(struct buffer * buf)
{
    buffer_free(buf);
}

/**
 * call-seq:
 *   IO_Buffer.default_node_size -> 4096
 *
 * Retrieves the current value of the default node size.
 */
static VALUE
IO_Buffer_default_node_size(VALUE klass)
{
    return UINT2NUM(default_node_size);
}

/*
 * safely converts node sizes from Ruby numerics to C and raising
 * ArgumentError or RangeError on invalid sizes
 */
static unsigned
convert_node_size(VALUE size)
{
    if (
        rb_funcall(size, rb_intern("<"), 1, INT2NUM(1)) == Qtrue ||
        rb_funcall(size, rb_intern(">"), 1, INT2NUM(MAX_BUFFER_SIZE)) == Qtrue
    )
        rb_raise(rb_eArgError, "invalid buffer size");

    return (unsigned) NUM2INT(size);
}

/**
 * call-seq:
 *   IO_Buffer.default_node_size = 16384
 *
 * Sets the default node size for calling IO::Buffer.new with no arguments.
 */
static VALUE
IO_Buffer_set_default_node_size(VALUE klass, VALUE size)
{
    default_node_size = convert_node_size(size);

    return size;
}

/**
 *  call-seq:
 *    IO_Buffer.new(size = IO::Buffer.default_node_size) -> IO_Buffer
 *
 * Create a new IO_Buffer with linked segments of the given size
 */
static VALUE
IO_Buffer_initialize(int argc, VALUE * argv, VALUE self)
{
    VALUE           node_size_obj;
    struct buffer *buf;

    if (rb_scan_args(argc, argv, "01", &node_size_obj) == 1) {
        Data_Get_Struct(self, struct buffer, buf);

        /*
         * Make sure we're not changing the buffer size after data
         * has been allocated
         */
        assert(!buf->head);
        assert(!buf->pool_head);

        buf->node_size = convert_node_size(node_size_obj);
    }
    return Qnil;
}

/**
 *  call-seq:
 *    IO_Buffer#clear -> nil
 *
 * Clear all data from the IO_Buffer
 */
static VALUE
IO_Buffer_clear(VALUE self)
{
    struct buffer *buf;
    Data_Get_Struct(self, struct buffer, buf);

    buffer_clear(buf);

    return Qnil;
}

/**
 *  call-seq:
 *    IO_Buffer#size -> Integer
 *
 * Return the size of the buffer in bytes
 */
static VALUE
IO_Buffer_size(VALUE self)
{
    struct buffer *buf;
    Data_Get_Struct(self, struct buffer, buf);

    return INT2NUM(buf->size);
}

/**
 *  call-seq:
 *    IO_Buffer#empty? -> Boolean
 *
 * Is the buffer empty?
 */
static VALUE
IO_Buffer_empty(VALUE self)
{
    struct buffer *buf;
    Data_Get_Struct(self, struct buffer, buf);

    return buf->size > 0 ? Qfalse : Qtrue;
}

/**
 *  call-seq:
 *    IO_Buffer#append(data) -> String
 *
 * Append the given data to the end of the buffer
 */
static VALUE
IO_Buffer_append(VALUE self, VALUE data)
{
    struct buffer *buf;
    Data_Get_Struct(self, struct buffer, buf);

    /* Is this needed?  Never seen anyone else do it... */
    data = rb_convert_type(data, T_STRING, "String", "to_str");
    buffer_append(buf, RSTRING_PTR(data), RSTRING_LEN(data));

    return data;
}

/**
 *  call-seq:
 *    IO_Buffer#prepend(data) -> String
 *
 * Prepend the given data to the beginning of the buffer
 */
static VALUE
IO_Buffer_prepend(VALUE self, VALUE data)
{
    struct buffer *buf;
    Data_Get_Struct(self, struct buffer, buf);

    data = rb_convert_type(data, T_STRING, "String", "to_str");
    buffer_prepend(buf, RSTRING_PTR(data), RSTRING_LEN(data));

    return data;
}

/**
 *  call-seq:
 *    IO_Buffer#read(length = nil) -> String
 *
 * Read the specified abount of data from the buffer.  If no value
 * is given the entire contents of the buffer are returned.  Any data
 * read from the buffer is cleared.
 * The given length must be greater than 0 or an exception would raise.
 * If the buffer size is zero then an empty string is returned (regardless
 * the given length).
 */
static VALUE
IO_Buffer_read(int argc, VALUE * argv, VALUE self)
{
    VALUE  length_obj, str;
    int    length;
    struct buffer *buf;

    Data_Get_Struct(self, struct buffer, buf);

    if (rb_scan_args(argc, argv, "01", &length_obj) == 1) {
        length = NUM2INT(length_obj);
        if(length < 1)
          rb_raise(rb_eArgError, "length must be greater than zero");
        if(length > buf->size)
          length = buf->size;
    } else
        length = buf->size;

    if(buf->size == 0)
        return rb_str_new2("");

    str = rb_str_new(0, length);
    buffer_read(buf, RSTRING_PTR(str), length);

    return str;
}

/**
 *  call-seq:
 *    IO_Buffer#read_frame(str, mark) -> boolean
 *
 * Read up to and including the given frame marker (expressed a a
 * Fixnum 0-255) byte, copying into the supplied string object. If the mark is
 * not encountered before the end of the buffer, false is returned but data
 * is still copied into str. True is returned if the end of a frame is reached.
 *
 */
static VALUE
IO_Buffer_read_frame(VALUE self, VALUE data, VALUE mark)
{
    char mark_c = (char) NUM2INT(mark);
    struct buffer *buf;

    Data_Get_Struct(self, struct buffer, buf);

    if (buffer_read_frame(buf, data, mark_c)) {
        return Qtrue;
    } else {
        return Qfalse;
    }
}

/**
 *  call-seq:
 *    IO_Buffer#to_str -> String
 *
 * Convert the Buffer to a String.  The original buffer is unmodified.
 */
static VALUE
IO_Buffer_to_str(VALUE self)
{
    VALUE          str;
    struct buffer *buf;

    Data_Get_Struct(self, struct buffer, buf);

    str = rb_str_new(0, buf->size);
    buffer_copy(buf, RSTRING_PTR(str), buf->size);

    return str;
}

/**
 *  call-seq:
 *    IO_Buffer#read_from(io) -> Integer
 *
 * Perform a nonblocking read of the the given IO object and fill
 * the buffer with any data received.  The call will read as much
 * data as it can until the read would block.
 */
static VALUE
IO_Buffer_read_from(VALUE self, VALUE io)
{
    struct buffer  *buf;
    int             ret;
#if HAVE_RB_IO_T
    rb_io_t        *fptr;
#else
    OpenFile       *fptr;
#endif

    Data_Get_Struct(self, struct buffer, buf);
    GetOpenFile(rb_convert_type(io, T_FILE, "IO", "to_io"), fptr);
    rb_io_set_nonblock(fptr);

    ret = buffer_read_from(buf, FPTR_TO_FD(fptr));
    return ret == -1 ? Qnil : INT2NUM(ret);
}

/**
 *  call-seq:
 *    IO_Buffer#write_to(io) -> Integer
 *
 * Perform a nonblocking write of the buffer to the given IO object.
 * As much data as possible is written until the call would block.
 * Any data which is written is removed from the buffer.
 */
static VALUE
IO_Buffer_write_to(VALUE self, VALUE io)
{
    struct buffer  *buf;
#if HAVE_RB_IO_T
    rb_io_t        *fptr;
#else
    OpenFile       *fptr;
#endif

    Data_Get_Struct(self, struct buffer, buf);
    GetOpenFile(rb_convert_type(io, T_FILE, "IO", "to_io"), fptr);
    rb_io_set_nonblock(fptr);

    return INT2NUM(buffer_write_to(buf, FPTR_TO_FD(fptr)));
}

/*
 * Ruby bindings end here.  Below is the actual implementation of
 * the underlying byte queue ADT
 */

/* Create a new buffer */
static struct buffer *
buffer_new(void)
{
    struct buffer *buf;

    buf = (struct buffer *) xmalloc(sizeof(struct buffer));
    buf->head = buf->tail = buf->pool_head = buf->pool_tail = 0;
    buf->size = 0;
    buf->node_size = default_node_size;

    return buf;
}

/* Clear all data from a buffer */
static void
buffer_clear(struct buffer * buf)
{
    /* Move everything into the buffer pool */
    if (!buf->pool_tail) {
        buf->pool_head = buf->pool_tail = buf->head;
    } else {
        buf->pool_tail->next = buf->head;
    }

    buf->head = buf->tail = 0;
    buf->size = 0;
}

/* Free a buffer */
static void
buffer_free(struct buffer * buf)
{
    buffer_clear(buf);
    buffer_free_pool(buf);

    free(buf);
}

/* Free the memory pool */
static void
buffer_free_pool(struct buffer * buf)
{
    struct buffer_node *tmp;

    while (buf->pool_head) {
        tmp = buf->pool_head;
        buf->pool_head = tmp->next;
        free(tmp);
    }

    buf->pool_tail = 0;
}

/* Create a new buffer_node (or pull one from the memory pool) */
static struct buffer_node *
buffer_node_new(struct buffer * buf)
{
    struct buffer_node *node;

    /* Pull from the memory pool if available */
    if (buf->pool_head) {
        node = buf->pool_head;
        buf->pool_head = node->next;

        if (node->next)
            node->next = 0;
        else
            buf->pool_tail = 0;
    } else {
        node = (struct buffer_node *) xmalloc(sizeof(struct buffer_node) + buf->node_size);
        node->next = 0;
    }

    node->start = node->end = 0;
    return node;
}

/* Free a buffer node (i.e. return it to the memory pool) */
static void
buffer_node_free(struct buffer * buf, struct buffer_node * node)
{
    node->next = buf->pool_head;
    buf->pool_head = node;

    if (!buf->pool_tail) {
        buf->pool_tail = node;
    }
}

/* Prepend data to the front of the buffer */
static void
buffer_prepend(struct buffer * buf, char *str, unsigned len)
{
    struct buffer_node *node, *tmp;
    buf->size += len;

    /* If it fits in the beginning of the head */
    if (buf->head && buf->head->start >= len) {
        buf->head->start -= len;
        memcpy(buf->head->data + buf->head->start, str, len);
    } else {
        node = buffer_node_new(buf);
        node->next = buf->head;
        buf->head = node;
        if (!buf->tail)
            buf->tail = node;

        while (len > buf->node_size) {
            memcpy(node->data, str, buf->node_size);
            node->end = buf->node_size;

            tmp = buffer_node_new(buf);
            tmp->next = node->next;
            node->next = tmp;

            if (buf->tail == node)
                buf->tail = tmp;
            node = tmp;

            str += buf->node_size;
            len -= buf->node_size;
        }

        if (len > 0) {
            memcpy(node->data, str, len);
            node->end = len;
        }
    }
}

/* Append data to the front of the buffer */
static void
buffer_append(struct buffer * buf, char *str, unsigned len)
{
    unsigned nbytes;
    buf->size += len;

    /* If it fits in the remaining space in the tail */
    if (buf->tail && len <= buf->node_size - buf->tail->end) {
        memcpy(buf->tail->data + buf->tail->end, str, len);
        buf->tail->end += len;
        return;
    }
    /* Empty list needs initialized */
    if (!buf->head) {
        buf->head = buffer_node_new(buf);
        buf->tail = buf->head;
    }
    /* Build links out of the data */
    while (len > 0) {
        nbytes = buf->node_size - buf->tail->end;
        if (len < nbytes)
            nbytes = len;

        memcpy(buf->tail->data + buf->tail->end, str, nbytes);
        str += nbytes;
        len -= nbytes;

        buf->tail->end += nbytes;

        if (len > 0) {
            buf->tail->next = buffer_node_new(buf);
            buf->tail = buf->tail->next;
        }
    }
}

/* Read data from the buffer (and clear what we've read) */
static void
buffer_read(struct buffer * buf, char *str, unsigned len)
{
    unsigned nbytes;
    struct buffer_node *tmp;

    while (buf->size > 0 && len > 0) {
        nbytes = buf->head->end - buf->head->start;
        if (len < nbytes)
            nbytes = len;

        memcpy(str, buf->head->data + buf->head->start, nbytes);
        str += nbytes;
        len -= nbytes;

        buf->head->start += nbytes;
        buf->size -= nbytes;

        if (buf->head->start == buf->head->end) {
            tmp = buf->head;
            buf->head = tmp->next;
            buffer_node_free(buf, tmp);

            if (!buf->head)
                buf->tail = 0;
        }
    }
}

/*
 * Read data from the buffer into str until byte frame_mark or empty. Bytes
 * are copied into str and removed if a complete frame is read, a true value
 * is returned
 */
static int
buffer_read_frame(struct buffer * buf, VALUE str, char frame_mark)
{
    unsigned nbytes = 0;
    struct buffer_node *tmp;

    while (buf->size > 0) {
        struct buffer_node *head = buf->head;
        char           *loc, *s = head->data + head->start, *e = head->data + head->end;
        nbytes = e - s;

        loc = memchr(s, frame_mark, nbytes);

        if (loc) {
            nbytes = loc - s + 1;
        }

        /* Copy less than everything if we found a frame byte */
        rb_str_cat(str, s, nbytes);

        /* Fixup the buffer pointers to indicate the bytes were consumed */
        head->start += nbytes;
        buf->size -= nbytes;

        if (head->start == head->end) {
            buf->head = head->next;
            buffer_node_free(buf, head);

            if (!buf->head)
                buf->tail = 0;
        }

        if (loc) {
            return 1;
        }
    }

    return 0;
}

/* Copy data from the buffer without clearing it */
static void
buffer_copy(struct buffer * buf, char *str, unsigned len)
{
    unsigned nbytes;
    struct buffer_node *node;

    node = buf->head;
    while (node && len > 0) {
        nbytes = node->end - node->start;
        if (len < nbytes)
            nbytes = len;

        memcpy(str, node->data + node->start, nbytes);
        str += nbytes;
        len -= nbytes;

        if (node->start + nbytes == node->end)
            node = node->next;
    }
}

/* Write data from the buffer to a file descriptor */
static int
buffer_write_to(struct buffer * buf, int fd)
{
    int bytes_written, total_bytes_written = 0;
    struct buffer_node *tmp;

    while (buf->head) {
        bytes_written = write(fd, buf->head->data + buf->head->start, buf->head->end - buf->head->start);

        /* If the write failed... */
        if (bytes_written < 0) {
            if (errno != EAGAIN)
                rb_sys_fail("write");

            return total_bytes_written;
        }

        total_bytes_written += bytes_written;
        buf->size -= bytes_written;

        /* If the write blocked... */
        if (bytes_written < buf->head->end - buf->head->start) {
            buf->head->start += bytes_written;
            return total_bytes_written;
        }
        /* Otherwise we wrote the whole buffer */
        tmp = buf->head;
        buf->head = tmp->next;
        buffer_node_free(buf, tmp);

        if (!buf->head)
            buf->tail = 0;
    }

    return total_bytes_written;
}

/* Read data from a file descriptor to a buffer */
/* Append data to the front of the buffer */
static int
buffer_read_from(struct buffer * buf, int fd)
{
    int      bytes_read, total_bytes_read = 0;
    unsigned nbytes;

    /* Empty list needs initialized */
    if (!buf->head) {
        buf->head = buffer_node_new(buf);
        buf->tail = buf->head;
    }

    do {
        nbytes = buf->node_size - buf->tail->end;
        bytes_read = read(fd, buf->tail->data + buf->tail->end, nbytes);

        if (bytes_read == 0) {
            return -1;
            //When the file reaches EOF
        } else if (bytes_read < 0) {
            if (errno != EAGAIN)
                rb_sys_fail("read");

            return total_bytes_read;
        }

        total_bytes_read += bytes_read;
        buf->tail->end += bytes_read;
        buf->size += bytes_read;

        if (buf->tail->end == buf->node_size) {
            buf->tail->next = buffer_node_new(buf);
            buf->tail = buf->tail->next;
        }
    } while (bytes_read == nbytes);

    return total_bytes_read;
}


text:
=======
Credits
=======

Development Lead
----------------

* Patrizio Tufarolo <patrizio.tufarolo@studenti.unimi.it>

Contributors
------------

None yet. Why not be the first?