text:
package io.gravitee.rest.api.model.api;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.gravitee.common.component.Lifecycle;
import io.gravitee.definition.jackson.datatype.api.deser.PropertiesDeserializer;
import io.gravitee.definition.model.*;
import io.gravitee.definition.model.Properties;
import io.gravitee.definition.model.flow.Flow;
import io.gravitee.definition.model.plugins.resources.Resource;
import io.gravitee.definition.model.services.Services;
import io.gravitee.rest.api.model.DeploymentRequired;
import io.gravitee.rest.api.model.PrimaryOwnerEntity;
import io.gravitee.rest.api.model.Visibility;
import io.gravitee.rest.api.model.WorkflowState;
import io.gravitee.rest.api.model.filtering.FilterableItem;
import io.gravitee.rest.api.model.search.Indexable;
import io.swagger.annotations.ApiModelProperty;
import java.util.*;
import javax.validation.constraints.NotNull;

/**
 * --------------------------------------------------------------------------------------------------------------
 * --------------------------------------------------------------------------------------------------------------
 * /!\ Do not forget to update {@see io.gravitee.rest.api.service.jackson.ser.api.ApiDefaultSerializer}
 * for each modification of the ApiEntity class to apply export API changes /!\
 * --------------------------------------------------------------------------------------------------------------
 * --------------------------------------------------------------------------------------------------------------
 *
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com)
 * @author Azize ELAMRANI (azize.elamrani at graviteesource.com)
 * @author GraviteeSource Team
 */
@JsonFilter("apiMembershipTypeFilter")
public class ApiEntity implements Indexable, FilterableItem {

    @ApiModelProperty(value = "API's uuid.", example = "00f8c9e7-78fc-4907-b8c9-e778fc790750")
    private String id;

    @ApiModelProperty(value = "API's name. Duplicate names can exists.", example = "My Api")
    private String name;

    @ApiModelProperty(value = "Api's version. It's a simple string only used in the portal.", example = "v1.0")
    private String version;

    @ApiModelProperty(
        value = "API's description. A short description of your API.",
        example = "I can use a hundred characters to describe this API."
    )
    private String description;

    @ApiModelProperty(value = "API's groups. Used to add team in your API.", example = "['MY_GROUP1', 'MY_GROUP2']")
    private Set<String> groups;

    @JsonProperty(value = "context_path")
    @ApiModelProperty(value = "API's context path.", example = "/my-awesome-api")
    private String contextPath;

    @NotNull
    @DeploymentRequired
    @JsonProperty(value = "proxy", required = true)
    @ApiModelProperty(value = "API's definition.")
    private Proxy proxy;

    @DeploymentRequired
    @JsonProperty(value = "flow_mode")
    @ApiModelProperty(value = "API's flow mode.", example = "BEST_MATCH")
    private FlowMode flowMode;

    @DeploymentRequired
    @JsonProperty(value = "paths", required = true)
    @ApiModelProperty(value = "a map where you can associate a path to a configuration (the policies configuration)")
    private Map<String, List<Rule>> paths = new HashMap<>();

    @DeploymentRequired
    @JsonProperty(value = "flows", required = true)
    @ApiModelProperty(value = "a list of flows (the policies configuration)")
    private List<Flow> flows = new ArrayList<>();

    @DeploymentRequired
    @JsonProperty(value = "plans", required = true)
    @ApiModelProperty(value = "a list of plans with flows (the policies configuration)")
    private List<Plan> plans = new ArrayList<>();

    @DeploymentRequired
    @JsonProperty(value = "gravitee", required = false)
    @ApiModelProperty(value = "API's gravitee definition version")
    private String graviteeDefinitionVersion;

    @JsonProperty("deployed_at")
    @ApiModelProperty(value = "The last date (as timestamp) when the API was deployed.", example = "1581256457163")
    private Date deployedAt;

    @JsonProperty("created_at")
    @ApiModelProperty(value = "The date (as a timestamp) when the API was created.", example = "1581256457163")
    private Date createdAt;

    @JsonProperty("updated_at")
    @ApiModelProperty(value = "The last date (as a timestamp) when the API was updated.", example = "1581256457163")
    private Date updatedAt;

    @ApiModelProperty(value = "The visibility of the API regarding the portal.", example = "PUBLIC", allowableValues = "PUBLIC, PRIVATE")
    private Visibility visibility;

    @ApiModelProperty(
        value = "The status of the API regarding the gateway.",
        example = "STARTED",
        allowableValues = "INITIALIZED, STOPPED, STARTED, CLOSED"
    )
    private Lifecycle.State state;

    @JsonProperty("owner")
    @ApiModelProperty(value = "The user with role PRIMARY_OWNER on this API.")
    private PrimaryOwnerEntity primaryOwner;

    @DeploymentRequired
    @JsonProperty(value = "properties")
    @ApiModelProperty(value = "A dictionary (could be dynamic) of properties available in the API context.")
    private io.gravitee.definition.model.Properties properties;

    @DeploymentRequired
    @JsonProperty(value = "services")
    @ApiModelProperty(value = "The configuration of API services like the dynamic properties, the endpoint discovery or the healthcheck.")
    private Services services;

    @DeploymentRequired
    @ApiModelProperty(value = "the list of sharding tags associated with this API.", example = "public, private")
    private Set<String> tags;

    @ApiModelProperty(value = "the API logo encoded in base64")
    private String picture;

    @JsonProperty(value = "picture_url")
    @ApiModelProperty(
        value = "the API logo url.",
        example = "https://gravitee.mycompany.com/management/apis/6c530064-0b2c-4004-9300-640b2ce0047b/picture"
    )
    private String pictureUrl;

    @DeploymentRequired
    @JsonProperty(value = "resources")
    @ApiModelProperty(value = "The list of API resources used by policies like cache resources or oauth2")
    private List<Resource> resources = new ArrayList<>();

    @ApiModelProperty(value = "the list of categories associated with this API", example = "Product, Customer, Misc")
    private Set<String> categories;

    @ApiModelProperty(value = "the free list of labels associated with this API", example = "json, read_only, awesome")
    private List<String> labels;

    @DeploymentRequired
    @JsonProperty(value = "path_mappings")
    @ApiModelProperty(
        value = "A list of paths used to aggregate data in analytics",
        example = "/products/:productId, /products/:productId/media"
    )
    private Set<String> pathMappings = new HashSet<>();

    @JsonIgnore
    private Map<String, Object> metadata = new HashMap<>();

    @DeploymentRequired
    @JsonProperty(value = "response_templates")
    @ApiModelProperty(
        value = "A map that allows you to configure the output of a request based on the event throws by the gateway. Example : Quota exceeded, api-ky is missing, ..."
    )
    private Map<String, Map<String, ResponseTemplate>> responseTemplates;

    @JsonProperty(value = "lifecycle_state")
    private ApiLifecycleState lifecycleState;

    @JsonProperty(value = "workflow_state")
    private WorkflowState workflowState;

    @JsonProperty("disable_membership_notifications")
    private boolean disableMembershipNotifications;

    private List<ApiEntrypointEntity> entrypoints;

    @ApiModelProperty(value = "the API background encoded in base64")
    private String background;

    @JsonProperty(value = "background_url")
    @ApiModelProperty(
        value = "the API background url.",
        example = "https://gravitee.mycompany.com/management/apis/6c530064-0b2c-4004-9300-640b2ce0047b/background"
    )
    private String backgroundUrl;

    @JsonIgnore
    private String referenceType;

    @JsonIgnore
    private String referenceId;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getReferenceType() {
        return this.referenceType;
    }

    @Override
    public void setReferenceType(String referenceType) {
        this.referenceType = referenceType;
    }

    @Override
    public String getReferenceId() {
        return referenceId;
    }

    @Override
    public void setReferenceId(String referenceId) {
        this.referenceId = referenceId;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Visibility getVisibility() {
        return visibility;
    }

    public void setVisibility(Visibility visibility) {
        this.visibility = visibility;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Lifecycle.State getState() {
        return state;
    }

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

    public Proxy getProxy() {
        return proxy;
    }

    public void setProxy(Proxy proxy) {
        this.proxy = proxy;
    }

    public Map<String, List<Rule>> getPaths() {
        return paths;
    }

    public void setPaths(Map<String, List<Rule>> paths) {
        this.paths = paths;
    }

    public PrimaryOwnerEntity getPrimaryOwner() {
        return primaryOwner;
    }

    public void setPrimaryOwner(PrimaryOwnerEntity primaryOwner) {
        this.primaryOwner = primaryOwner;
    }

    public Services getServices() {
        return services;
    }

    public void setServices(Services services) {
        this.services = services;
    }

    public Properties getProperties() {
        return properties;
    }

    @JsonIgnore
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @JsonSetter("properties")
    public void setPropertyList(List<Property> properties) {
        this.properties = new Properties();
        this.properties.setProperties(properties);
    }

    @JsonGetter("properties")
    public List<Property> getPropertyList() {
        if (properties != null) {
            return properties.getProperties();
        }
        return Collections.emptyList();
    }

    public Set<String> getTags() {
        return tags;
    }

    public void setTags(Set<String> tags) {
        this.tags = tags;
    }

    public Date getDeployedAt() {
        return deployedAt;
    }

    public void setDeployedAt(Date deployedAt) {
        this.deployedAt = deployedAt;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

    public String getPictureUrl() {
        return pictureUrl;
    }

    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }

    public List<Resource> getResources() {
        return resources;
    }

    public void setResources(List<Resource> resources) {
        this.resources = resources;
    }

    public Set<String> getCategories() {
        return categories;
    }

    public void setCategories(Set<String> categories) {
        this.categories = categories;
    }

    public Set<String> getGroups() {
        return groups;
    }

    public void setGroups(Set<String> groups) {
        this.groups = groups;
    }

    public List<String> getLabels() {
        return labels;
    }

    public void setLabels(List<String> labels) {
        this.labels = labels;
    }

    public Set<String> getPathMappings() {
        return pathMappings;
    }

    public void setPathMappings(Set<String> pathMappings) {
        this.pathMappings = pathMappings;
    }

    public Map<String, Object> getMetadata() {
        return metadata;
    }

    public void setMetadata(Map<String, Object> metadata) {
        this.metadata = metadata;
    }

    public Map<String, Map<String, ResponseTemplate>> getResponseTemplates() {
        return responseTemplates;
    }

    public void setResponseTemplates(Map<String, Map<String, ResponseTemplate>> responseTemplates) {
        this.responseTemplates = responseTemplates;
    }

    public ApiLifecycleState getLifecycleState() {
        return lifecycleState;
    }

    public void setLifecycleState(ApiLifecycleState lifecycleState) {
        this.lifecycleState = lifecycleState;
    }

    public WorkflowState getWorkflowState() {
        return workflowState;
    }

    public void setWorkflowState(WorkflowState workflowState) {
        this.workflowState = workflowState;
    }

    public List<ApiEntrypointEntity> getEntrypoints() {
        return entrypoints;
    }

    public void setEntrypoints(List<ApiEntrypointEntity> entrypoints) {
        this.entrypoints = entrypoints;
    }

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public boolean isDisableMembershipNotifications() {
        return disableMembershipNotifications;
    }

    public void setDisableMembershipNotifications(boolean disableMembershipNotifications) {
        this.disableMembershipNotifications = disableMembershipNotifications;
    }

    public String getBackground() {
        return background;
    }

    public void setBackground(String background) {
        this.background = background;
    }

    public String getBackgroundUrl() {
        return backgroundUrl;
    }

    public void setBackgroundUrl(String backgroundUrl) {
        this.backgroundUrl = backgroundUrl;
    }

    public List<Flow> getFlows() {
        return flows;
    }

    public void setFlows(List<Flow> flows) {
        this.flows = flows;
    }

    public List<Plan> getPlans() {
        return plans;
    }

    public void setPlans(List<Plan> plans) {
        this.plans = plans;
    }

    public String getGraviteeDefinitionVersion() {
        return graviteeDefinitionVersion;
    }

    public void setGraviteeDefinitionVersion(String graviteeDefinitionVersion) {
        this.graviteeDefinitionVersion = graviteeDefinitionVersion;
    }

    public FlowMode getFlowMode() {
        return flowMode;
    }

    public void setFlowMode(FlowMode flowMode) {
        this.flowMode = flowMode;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ApiEntity api = (ApiEntity) o;
        return Objects.equals(id, api.id) && Objects.equals(version, api.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, version);
    }

    public String toString() {
        return (
            "ApiEntity{" +
            "id='" +
            id +
            '\'' +
            ", name='" +
            name +
            '\'' +
            ", version='" +
            version +
            '\'' +
            ", description='" +
            description +
            '\'' +
            ", proxy=" +
            proxy +
            ", paths=" +
            paths +
            ", createdAt=" +
            createdAt +
            ", updatedAt=" +
            updatedAt +
            ", visibility=" +
            visibility +
            ", state=" +
            state +
            ", primaryOwner=" +
            primaryOwner +
            ", tags=" +
            tags +
            ", category=" +
            categories +
            ", groups=" +
            groups +
            ", pathMappings=" +
            pathMappings +
            ", lifecycleState=" +
            lifecycleState +
            ", workflowState=" +
            workflowState +
            ", disableMembershipNotifications=" +
            disableMembershipNotifications +
            ", graviteeDefinitionVersion=" +
            graviteeDefinitionVersion +
            ", flowMode=" +
            flowMode +
            '}'
        );
    }
}


text:
using System;
using UnityEngine;

namespace AmplifyShaderEditor
{
	[Serializable]
	[NodeAttributes( "Power", "Operators", "Base to the Exp-th power of scalars and vectors", null, KeyCode.E )]
	public sealed class PowerNode : ParentNode
	{
		protected override void CommonInit( int uniqueId )
		{
			base.CommonInit( uniqueId );
			AddInputPort( WirePortDataType.FLOAT, false, "Base" );
			AddInputPort( WirePortDataType.FLOAT, false, "Exp" );
			AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
			m_useInternalPortData = true;
			m_textLabelWidth = 50;
			m_previewShaderGUID = "758cc2f8b537b4e4b93d9833075d138c";
		}

		public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
		{
			base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
			UpdateConnections( portId );
		}

		public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
		{
			base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type );
			UpdateConnections( inputPortId );
		}

		void UpdateConnections( int inputPort )
		{
			m_inputPorts[ inputPort ].MatchPortToConnection();
			if ( inputPort == 0 )
			{
				m_outputPorts[ 0 ].ChangeType( m_inputPorts[ 0 ].DataType, false );
			}
		}

		public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
		{
			string x = m_inputPorts[ 0 ].GenerateShaderForOutput( ref dataCollector, m_inputPorts[ 0 ].DataType, ignoreLocalvar );
			string y = m_inputPorts[ 1 ].GenerateShaderForOutput( ref dataCollector, m_inputPorts[ 0 ].DataType, ignoreLocalvar, true );
			string result = "pow( " + x + " , " + y + " )";
			return CreateOutputLocalVariable( 0, result, ref dataCollector );
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import "../src/styles/app.less";
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from "./index";
ReactDOM.render(
    <App/>,
    document.getElementById('app')
);


text:
<?php

/* FpOpenIdBundle::layout.html.twig */
class __TwigTemplate_68360ab756d4e19bfc9376303e88ea40924c9585e89bfba0db3d9b6752d3aefa extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'fp_openid_content' => array($this, 'block_fp_openid_content'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "<!DOCTYPE html>

        <meta charset=\"UTF-8\" />

            ";
        // line 8
        if ($this->env->getExtension('security')->isGranted("IS_AUTHENTICATED_OPENID")) {
            // line 9
            echo "                logged in via an openid provider:
                env->getExtension('routing')->getPath("fp_openid_security_logout");
            echo "\">Logout
            ";
        } else {
            // line 12
            echo "                env->getExtension('routing')->getPath("fp_openid_security_login");
            echo "\">Login
            ";
        }
        // line 14
        echo "

        ";
        // line 16
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session", array()), "flashbag", array()), "all", array(), "method"));
        foreach ($context['_seq'] as $context["type"] => $context["messages"]) {
            // line 17
            echo "            ";
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($context["messages"]);
            foreach ($context['_seq'] as $context["_key"] => $context["message"]) {
                // line 18
                echo "
env, $context["type"], "html", null, true);
                echo "\">
                    ";
                // line 19
                echo twig_escape_filter($this->env, $context["message"], "html", null, true);
                echo "

            ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 22
            echo "        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['type'], $context['messages'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 23
        echo "

            ";
        // line 25
        $this->displayBlock('fp_openid_content', $context, $blocks);
        // line 27
        echo "

";
    }

    // line 25
    public function block_fp_openid_content($context, array $blocks = array())
    {
        // line 26
        echo "            ";
    }

    public function getTemplateName()
    {
        return "FpOpenIdBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  94 => 26,  91 => 25,  84 => 27,  82 => 25,  78 => 23,  72 => 22,  63 => 19,  58 => 18,  53 => 17,  49 => 16,  45 => 14,  39 => 12,  34 => 10,  31 => 9,  29 => 8,  20 => 1,);
    }
}


text:
import {useDeps, composeAll, composeWithTracker, compose} from 'mantra-core';

import BuddyItem from '../components/buddy_item.jsx';

export const composer = ({context}, onData) => {
  const {Meteor, Collections} = context();

  onData(null, {});
};

export const depsMapper = (context, actions) => ({
  context: () => context
});

export default composeAll(
  composeWithTracker(composer),
  useDeps(depsMapper)
)(BuddyItem);


text:
require 'erb'

module Spec
  module Runner
    module Formatter
      module Story
        class HtmlFormatter < BaseTextFormatter
          include ERB::Util

          def run_started(count)
            @output.puts <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Stories</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Expires" content="-1" />
    <meta http-equiv="Pragma" content="no-cache" />

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

EOF
          end

          def collected_steps(steps)
            unless steps.empty?
              @output.puts "
"
              steps.each do |step|
                @output.puts "
#{step}
"
              end
              @output.puts "
"
            end
          end

          def run_ended
            @output.puts <<-EOF

EOF
          end

          def story_started(title, narrative)
            @output.puts <<-EOF

#{h title}

            #{h(narrative).split("\n").join("
")}

EOF
          end

          def story_ended(title, narrative)
            @output.puts <<-EOF

EOF
          end

          def scenario_started(story_title, scenario_name)
            @output.puts <<-EOF

#{h scenario_name}

EOF
          end

          def scenario_ended
            @output.puts <<-EOF

EOF
          end

          def found_scenario(type, description)
          end

          def scenario_succeeded(story_title, scenario_name)
            scenario_ended
          end

          def scenario_pending(story_title, scenario_name, reason)
            scenario_ended
          end

          def scenario_failed(story_title, scenario_name, err)
            scenario_ended
          end

          def step_succeeded(type, description, *args)
            print_step('passed', type, description, *args) # TODO: uses succeeded CSS class
          end

          def step_pending(type, description, *args)
            print_step('pending', type, description, *args)
          end

          def step_failed(type, description, *args)
            print_step('failed', type, description, *args)
          end

          def print_step(klass, type, description, *args)
            spans = args.map { |arg| "#{arg}" }
            i = -1
            inner = type.to_s.capitalize + ' ' + description.gsub(::Spec::Story::Step::PARAM_PATTERN) { |param| spans[i+=1] }
            @output.puts "
#{inner}
"
          end

        end
      end
    end
  end
end


text:
int running = 0;

#define USE_PATCH

OVRkill g_ok;
#ifdef USE_PATCH
PanoramaPatch* g_pPano = NULL; ///< Initialize AFTER we have a GL context
#else
PanoramaCylinder* g_pPano = NULL; ///< Initialize AFTER we have a GL context
#endif

///
/// VR view parameters
///

// The world RHS coordinate system is defines as follows (as seen in perspective view):
//  Y - Up
//  Z - Back
//  X - Right
const OVR::Vector3f UpVector     (0.0f, 1.0f, 0.0f);
const OVR::Vector3f ForwardVector(0.0f, 0.0f, -1.0f);
const OVR::Vector3f RightVector  (1.0f, 0.0f, 0.0f);

// We start out looking in the positive Z (180 degree rotation).
const float    YawInitial  = 3.141592f;
const float    Sensitivity = 10.0f;
const float    MoveSpeed   = 30.0f; // m/s

const float g_standingHeight = 0.0f;//1.78f; /// From Oculus SDK p.13: 1.78m ~= 5'10"
const float g_crouchingHeight = 0.6f;
OVR::Vector3f EyePos(0.0f, g_standingHeight, 0.0f);
float EyeYaw = YawInitial;
float EyePitch = 0;
float EyeRoll = 0;
float LastSensorYaw = 0;
OVR::Vector3f FollowCamPos(EyePos.x, EyePos.y + 3.0f, EyePos.z + 3.0f);
bool UseFollowCam = false;

/// World modelview matrix
OVR::Matrix4f  View;

/// Viewing parameters fed in from joystick and the HMD
OVR::Quatf  g_joyOrient;
OVR::Quatf  g_hmdOrient;
OVR::Vector3f  GamepadMove, GamepadRotate;
OVR::Vector3f  MouseMove, MouseRotate;
OVR::Vector3f  KeyboardMove, KeyboardRotate;

int g_windowWidth = 1280;
int g_windowHeight = 800;

float g_viewAngle = 45.0; ///< For the no HMD case

// mouse motion internal state
int oldx, oldy, newx, newy;
int which_button = -1;
int modifier_mode = 0;
int last_wheelpos = 0;

int g_keyStates[GLFW_KEY_LAST] = {0};

Timer g_timer;

int currentPano = 0;
void InitPano(int argc, char *argv[]);
std::string datadir = "panos/";
std::vector<std::string> panoFiles;

// OpenGL init:
// Call this once GL context is created.
void OpenGL_initialization()
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}

// Handle mouse clicks
void GLFWCALL clickhandler(int button, int action)
{
    which_button = button;
    glfwGetMousePos(&newx, &newy);
    oldx = newx;
    oldy = newy;
    if (action == GLFW_RELEASE)
    {
        which_button = 0;
    }
    if ((button == GLFW_MOUSE_BUTTON_RIGHT) && (action == GLFW_PRESS))
    {
        InitPano(1, NULL);
    }
}

// Handle mouse drags
void GLFWCALL motionhandler(int x, int y)
{
    const float thresh = 32;

    oldx = newx;
    oldy = newy;
    newx = x;
    newy = y;
    const int mmx = x-oldx;
    const int mmy = y-oldy;
    const float rx = (float)mmx/thresh;
    const float ry = (float)mmy/thresh;

    MouseRotate = OVR::Vector3f(0, 0, 0);
    MouseMove   = OVR::Vector3f(0, 0, 0);

    if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT))
    {
        MouseRotate = OVR::Vector3f(rx, ry, 0);
    }
    else if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT))
    {
        MouseMove   = OVR::Vector3f(rx * rx * (rx > 0 ? 1 : -1),
                                    0,
                                    ry * ry * (ry > 0 ? 1 : -1));
    }
}

void GLFWCALL wheelhandler(int pos)
{
    int delta = pos - last_wheelpos;

    if (g_pPano != NULL)
    {
#ifdef USE_PATCH
        if (delta < 0)
            g_pPano->DecreaseCoverage();
        else if (delta > 0)
            g_pPano->IncreaseCoverage();
#endif
    }

    last_wheelpos = pos;
}

// Handle keyboard events
void GLFWCALL keyhandler(int key, int action)
{
    if ((key > -1) && (key <= GLFW_KEY_LAST))
    {
        g_keyStates[key] = action;
        printf("key ac  %d %d\n", key, action);
    }

    if (key == GLFW_KEY_LSHIFT)
    {
        if (action == GLFW_PRESS)
        {
            EyePos.y = g_crouchingHeight;
        }
        else if (action == GLFW_RELEASE)
        {
            EyePos.y = g_standingHeight;
        }
    }

    if (action != GLFW_PRESS)
    {
        return;
    }

    const float factor = 1.05f;
    const float tweak = 0.001f;
    switch (key)
    {
    case GLFW_KEY_ESC:
        running = GL_FALSE;
        break;

    case GLFW_KEY_F1:
        g_ok.SetDisplayMode(OVRkill::SingleEye);
        UseFollowCam = false;
        break;

    case GLFW_KEY_F2:
        g_ok.SetDisplayMode(OVRkill::Stereo);
        UseFollowCam = false;
        break;

    case GLFW_KEY_F3:
        g_ok.SetDisplayMode(OVRkill::StereoWithDistortion);
        UseFollowCam = false;
        break;

    case GLFW_KEY_F4:
        g_ok.SetDisplayMode(OVRkill::SingleEye);
        UseFollowCam = true;
        break;

    case 'J':
        if (g_pPano != NULL)
            g_pPano->m_cylHeight *= factor;
        break;
    case 'K':
        if (g_pPano != NULL)
            g_pPano->m_cylHeight /= factor;
        break;

    case 'N':
        if (g_pPano != NULL)
            g_pPano->m_cylRadius *= factor;
        break;
    case 'M':
        if (g_pPano != NULL)
            g_pPano->m_cylRadius /= factor;
        break;

    case 'L':
        if (g_pPano != NULL)
            g_pPano->m_manualTexToggle = !g_pPano->m_manualTexToggle;
        break;

    case 'Z':
        if (g_pPano != NULL)
        {
            g_pPano->m_pairTweak -= tweak;
            printf("tweak: %f\n", g_pPano->m_pairTweak);
        }
        break;
    case 'X':
        if (g_pPano != NULL)
        {
            g_pPano->m_pairTweak += tweak;
            printf("tweak: %f\n", g_pPano->m_pairTweak);
        }
        break;

    case 'Y':
        if (g_pPano != NULL)
        {
            const float tw = 0.010f;
            g_pPano->m_rollTweak -= tw;
            printf("rolltweak: %f\n", g_pPano->m_rollTweak);
        }
        break;
    case 'U':
        if (g_pPano != NULL)
        {
            const float tw = 0.010f;
            g_pPano->m_rollTweak += tw;
            printf("rolltweak: %f\n", g_pPano->m_rollTweak);
        }
        break;

    case GLFW_KEY_SPACE:
        {
            InitPano(1,NULL);
        }
        break;

    default:
        printf("%d: %c\n", key, (char)key);
        break;
    }

    fflush(stdout);
}

/// Handle input's influence on orientation variables.
void AccumulateInputs(float dt)
{
    // Handle Sensor motion.
    // We extract Yaw, Pitch, Roll instead of directly using the orientation
    // to allow "additional" yaw manipulation with mouse/controller.
    if (g_ok.SensorActive())
    {
        OVR::Quatf    hmdOrient = g_ok.GetOrientation();
        float    yaw = 0.0f;

        hmdOrient.GetEulerAngles<OVR::Axis_Y, OVR::Axis_X, OVR::Axis_Z>(&yaw, &EyePitch, &EyeRoll);

        EyeYaw += (yaw - LastSensorYaw);
        LastSensorYaw = yaw;
    }

    // Gamepad rotation.
    EyeYaw -= GamepadRotate.x * dt;

    if (!g_ok.SensorActive())
    {
        // Allow gamepad to look up/down, but only if there is no Rift sensor.
        EyePitch -= GamepadRotate.y * dt;
        EyePitch -= Sensitivity * MouseRotate.y * dt;
        EyeYaw   -= Sensitivity * MouseRotate.x * dt;

        const float maxPitch = ((3.1415f/2)*0.98f);
        if (EyePitch > maxPitch)
            EyePitch = maxPitch;
        if (EyePitch < -maxPitch)
            EyePitch = -maxPitch;
    }
}

/// From the OVR SDK.
void AssembleViewMatrix()
{
    // Rotate and position View Camera, using YawPitchRoll in BodyFrame coordinates.
    //
    OVR::Matrix4f rollPitchYaw = //OVR::Matrix4f::RotationY(EyeYaw) *
                                 OVR::Matrix4f::RotationX(EyePitch) *
                                 OVR::Matrix4f::RotationZ(EyeRoll);
    OVR::Vector3f up      = rollPitchYaw.Transform(UpVector);
    OVR::Vector3f forward = rollPitchYaw.Transform(ForwardVector);

    // Minimal head modelling.
    float headBaseToEyeHeight     = 0.15f;  // Vertical height of eye from base of head
    float headBaseToEyeProtrusion = 0.09f;  // Distance forward of eye from base of head

    OVR::Vector3f eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion);
    OVR::Vector3f shiftedEyePos = EyePos + rollPitchYaw.Transform(eyeCenterInHeadFrame);
    shiftedEyePos.y -= eyeCenterInHeadFrame.y; // Bring the head back down to original height

    View = OVR::Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + forward, up);

    // This is what transformation would be without head modeling.
    // View = Matrix4f::LookAtRH(EyePos, EyePos + forward, up);

    if (UseFollowCam)
    {
        OVR::Vector3f viewTarget(EyePos);
        OVR::Vector3f viewVector = viewTarget - FollowCamPos;
        View = OVR::Matrix4f::LookAtRH(FollowCamPos, viewVector, up);
    }
}

/// Handle animations, joystick states and viewing matrix
void timestep(float dt)
{
    AccumulateInputs(dt);
    AssembleViewMatrix();
}

void RenderForOneEye(const OVR::Matrix4f& mview, const OVR::Matrix4f& persp, bool isLeft=true)
{
    if (g_pPano == NULL)
        return;

    glUseProgram(g_pPano->m_progPanoCylinder);
    {
        glUniformMatrix4fv(getUniLoc(g_pPano->m_progPanoCylinder, "mvmtx"), 1, false, &mview.Transposed().M[0][0]);
        glUniformMatrix4fv(getUniLoc(g_pPano->m_progPanoCylinder, "prmtx"), 1, false, &persp.Transposed().M[0][0]);

        const float vMove = sin(EyeRoll);
        const float vEyeYaw = -EyeYaw / (2.0f * (float)M_PI);
        g_pPano->DrawPanoramaGeometry(isLeft, vMove, vEyeYaw);
    }
    glUseProgram(0);
}

/// Set up view matrices, then draw scene
void display()
{
    glEnable(GL_DEPTH_TEST);

    g_ok.BindRenderBuffer();
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        const int fboWidth = g_ok.GetRenderBufferWidth();
        const int fboHeight = g_ok.GetRenderBufferHeight();
        const int halfWidth = fboWidth/2;
        if (g_ok.GetStereoMode() == OVR::Util::Render::Stereo_LeftRight_Multipass)
        {
            const OVR::HMDInfo& hmd = g_ok.GetHMD();
            // Compute Aspect Ratio. Stereo mode cuts width in half.
            float aspectRatio = float(hmd.HResolution * 0.5f) / float(hmd.VResolution);

            // Compute Vertical FOV based on distance.
            float halfScreenDistance = (hmd.VScreenSize / 2);
            float yfov = 2.0f * atan(halfScreenDistance/hmd.EyeToScreenDistance);

            // Post-projection viewport coordinates range from (-1.0, 1.0), with the
            // center of the left viewport falling at (1/4) of horizontal screen size.
            // We need to shift this projection center to match with the lens center.
            // We compute this shift in physical units (meters) to correct
            // for different screen sizes and then rescale to viewport coordinates.
            float viewCenterValue = hmd.HScreenSize * 0.25f;
            float eyeProjectionShift = viewCenterValue - hmd.LensSeparationDistance * 0.5f;
            float projectionCenterOffset = 4.0f * eyeProjectionShift / hmd.HScreenSize;

            // Projection matrix for the "center eye", which the left/right matrices are based on.
            OVR::Matrix4f projCenter = OVR::Matrix4f::PerspectiveRH(yfov, aspectRatio, 0.3f, 1000.0f);
            OVR::Matrix4f projLeft   = OVR::Matrix4f::Translation(projectionCenterOffset, 0, 0) * projCenter;
            OVR::Matrix4f projRight  = OVR::Matrix4f::Translation(-projectionCenterOffset, 0, 0) * projCenter;

            // View transformation translation in world units.
            float halfIPD = hmd.InterpupillaryDistance * 0.5f;
            OVR::Matrix4f viewLeft = OVR::Matrix4f::Translation(halfIPD, 0, 0) * View;
            OVR::Matrix4f viewRight= OVR::Matrix4f::Translation(-halfIPD, 0, 0) * View;

            glViewport(0        ,0,(GLsizei)halfWidth, (GLsizei)fboHeight);
            glScissor (0        ,0,(GLsizei)halfWidth, (GLsizei)fboHeight);
            RenderForOneEye(viewLeft, projLeft, true);

            glViewport(halfWidth,0,(GLsizei)halfWidth, (GLsizei)fboHeight);
            glScissor (halfWidth,0,(GLsizei)halfWidth, (GLsizei)fboHeight);
            RenderForOneEye(viewRight, projRight, false);
        }
        else
        {
            /// Set up our 3D transformation matrices
            /// Remember DX and OpenGL use transposed conventions. And doesn't DX use left-handed coords?
            OVR::Matrix4f mview = View;
            mview = OVR::Matrix4f::Translation(1, 0, -30) * mview;
            OVR::Matrix4f persp = OVR::Matrix4f::PerspectiveRH(g_viewAngle, (float)g_windowWidth/(float)g_windowHeight, 0.004f, 500.0f);

            glViewport(0,0,(GLsizei)fboWidth, (GLsizei)fboHeight);
            RenderForOneEye(mview, persp);
        }
    }
    g_ok.UnBindRenderBuffer();

    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    OVRkill::PostProcessType post = OVRkill::PostProcess_None;
    RiftDistortionParams  riftDist;
    g_ok.PresentFbo(post, riftDist);

    glfwSwapBuffers();
}

// Window resized event callback
void GLFWCALL reshape(int w, int h)
{
    g_windowWidth = w;
    g_windowHeight = h;

    glViewport(0,0,(GLsizei)w, (GLsizei)h);

    glfwSwapBuffers();
}

/// Scan a directory for jpg files to display and return the list of filenames.
std::vector<std::string> GetFileList(const std::string& datadir)
{
    std::vector<std::string> panoFiles;

    /// Thank you Toni Ronkko for the dirent Windows compatibility layer.
    /// http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c
    DIR* dir;
    struct dirent* ent;
    if ((dir = opendir(datadir.c_str())) != NULL)
    {
        while ((ent = readdir(dir)) != NULL)
        {
            std::string filename(ent->d_name);

            /// Check file suffixes
            if (filename.length() > 4)
            {
                std::string suffix = filename.substr(filename.length()-4, 4);
                if (
                    !suffix.compare(".jpg") ||
                    !suffix.compare(".JPG")
                    )
                {
                    printf("%s\n", filename.c_str());
                    std::string fullname = datadir;
                    fullname.append(filename);
                    panoFiles.push_back(fullname);
                }
            }
        }
        closedir(dir);
    }

    return panoFiles;
}

/// Load a panoramic pair from file, preferably over/under but we try to do pairs as well.
void InitPano(int argc, char *argv[])
{
    if (panoFiles.empty())
        return;

    delete g_pPano, g_pPano = NULL;
    display();

    std::string fullFilename(panoFiles[currentPano]);
    ++currentPano;
    currentPano %= panoFiles.size();

    if (argc == 1)
    {
        g_pPano = new PanoramaPatch(fullFilename.c_str());
    }
    else if (argc == 2) ///< Specify over/under image on cmd line
    {
        fullFilename.assign(argv[1]);
        g_pPano = new PanoramaPatch(fullFilename.c_str());
    }
    else if (argc == 3) ///< Specify pair of images on cmd line
    {
        std::string fileL(argv[1]);
        std::string fileR(argv[2]);
        g_pPano = new PanoramaPatch(fileL.c_str(), fileR.c_str());
    }
}

// Initialize then enter the main loop
int main(int argc, char *argv[])
{
    /// Find stereo panoramas checking parent directories.
    const std::string originalDatadir = datadir;
    panoFiles = GetFileList(datadir);
    const int outdepth = 5;
    for (int i=0; i<outdepth; ++i)
    {
        if (panoFiles.empty())
        {
            datadir = "../" + datadir;
            panoFiles = GetFileList(datadir);
        }
    }

    if (panoFiles.empty())
    {
        //running = GL_FALSE;
        std::ostringstream oss;
        oss << std::endl
            << "No files found from "
            << originalDatadir
            << " to "
            << datadir
            << ", so we are exiting."
            << std::endl
            << "Throw some stereo panoramas in there!"
            << std::endl;

        std::cerr << oss.str().c_str();
        LOG_INFO("%s", oss.str().c_str());

#ifdef _WIN32
        MessageBox(0, oss.str().c_str(), "No pano files found", 0);
        ///@note This will prevent console output from disappearing with the terminal on Windows,
        /// but makes for an unpleasant experience when run with the Rift on.
        //char ch;
        //std::cin >> ch;
#endif

        exit(0);
    }

    bool fullScreen = false;

#ifdef _WIN32
    if (!IsDebuggerPresent()) ///< Ctrl-F5 to run in Rift mode,  just F5 for windowed
#endif
    {
        fullScreen = true;
    }

    g_ok.InitOVR();

    if (fullScreen)
    {
        g_ok.SetDisplayMode(OVRkill::StereoWithDistortion);
    }
    else
    {
        g_ok.SetDisplayMode(OVRkill::SingleEye);
    }

    LOG_INFO("Initializing Glfw and window @ %d x %d", g_windowWidth, g_windowHeight);
    glfwInit();

    if (!glfwOpenWindow(
        g_windowWidth, g_windowHeight,
        8,8,8,8,
        0,8,
        fullScreen ?
            GLFW_FULLSCREEN :
            GLFW_WINDOW
        ))
    {
        glfwTerminate();
        return 0;
    }

    glfwSetWindowTitle        ("Oculus GLFW Skeleton");
    glfwSetKeyCallback        (keyhandler);
    glfwSetWindowSizeCallback (reshape);
    glfwSetMouseButtonCallback(clickhandler);
    glfwSetMousePosCallback   (motionhandler);
    glfwSetMouseWheelCallback (wheelhandler);

    /// Create window and context before calling glewInit
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        LOG_INFO("Glew error... %s", glewGetErrorString(err));
        printf("Glew error... %s\n", glewGetErrorString(err));
    }

    OpenGL_initialization();
    LOG_INFO("Initializing shaders.");
    g_ok.CreateShaders();
    g_ok.CreateRenderBuffer(1.71f);

    InitPano(argc, argv);

    /// Main loop
    running = GL_TRUE;
    g_timer.reset();
    while (running)
    {
        float dt = (float)g_timer.seconds();
        timestep(dt);
        g_timer.reset();
        display();
        running = running && glfwGetWindowParam(GLFW_OPENED);
    }

    g_ok.DestroyOVR();

    glfwTerminate();
    return 0;
}


text:
package com.bzh.dytt.data;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import static com.bzh.dytt.data.Status.ERROR;
import static com.bzh.dytt.data.Status.LOADING;
import static com.bzh.dytt.data.Status.SUCCESS;

/**
 * A generic class that holds a value with its loading status.
 *
 * @param <T>
 */
public class Resource<T> {

    @NonNull
    public final Status status;

    @Nullable
    public final String message;

    @Nullable
    public final T data;

    public Resource(@NonNull Status status, @Nullable T data, @Nullable String message) {
        this.status = status;
        this.data = data;
        this.message = message;
    }

    public static <T> Resource<T> success(@Nullable T data) {
        return new Resource<>(SUCCESS, data, null);
    }

    public static <T> Resource<T> error(String msg, @Nullable T data) {
        return new Resource<>(ERROR, data, msg);
    }

    public static <T> Resource<T> loading(@Nullable T data) {
        return new Resource<>(LOADING, data, null);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Resource<?> resource = (Resource<?>) o;

        if (status != resource.status) {
            return false;
        }
        return (message != null ? message.equals(resource.message) : resource.message == null) && (data != null ? data.equals(resource.data) : resource.data == null);
    }

    @Override
    public int hashCode() {
        int result = status.hashCode();
        result = 31 * result + (message != null ? message.hashCode() : 0);
        result = 31 * result + (data != null ? data.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Resource{" +
                "status=" + status +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}


text:
* fair timeslice mangement
    * allow timeslice fragmentation
    * concurrent request issuance from multiple tasks
* read preference combined with write blocking
    * write starvation

# 3 most important things

* during concurrent access, writes can dramatically affect the response time of
  read requests
* support for parallel IO
* the lack of seek overhead eliminates the performance benefit of anticipatory I/P,
  but proper I/O anticipation is still needed for the purpose of fairness.

# conclusion

* design a new Flash I/O scheduling approach to ensure fairness with high efficiency
    * timeslice management that allows timeslice fragmentation and concurrent request issuance
    * read/write interference management
    * I/O parallelism
    * I/O anticipation for fairness

# quote

```
While I/O anticipation was proposed as a performance-enhancing
seek-reduction technique for mechanical disks [17], its role
for maintaining fairness has been largely ignored.
```

```
Under this approach, a read is only blocked by a write when
the read arrives at the I/O scheduler after the write has already
been issued. This is due to the non-preemptibility of I/O
```

```
On mechanical disks, I/O anticipation can substantially improve the I/O
efficiency by reducing the seek and rotation overhead. In contrast, I/O
spatial proximity has much less benefic for Flash storage. Therefore
I/O anticipation has a negative performance effect and it must be
used judiciously for the purpose of maintaining fairness.
```

```
or predictor of the application inter-I/O thinktime. For
seek-reduction on mechanical disks, the I/O anticipation
bound is set to roughly the time of a disk I/O operation
which leads to competitive performance compared to the
optimal offline I/O anticipation
```


text:
using NPOI.HSSF.Model;
using NPOI.HSSF.Record.Chart;
using System.Diagnostics;
namespace NPOI.HSSF.Record.Aggregates.Chart
{
    /// <summary>
    /// DROPBAR = DropBar Begin LineFormat AreaFormat [GELFRAME] [SHAPEPROPS] End
    /// </summary>
    public class DropBarAggregate : ChartRecordAggregate
    {
        private DropBarRecord dropBar = null;
        private LineFormatRecord lineFormat = null;
        private AreaFormatRecord areaFormat = null;
        private GelFrameAggregate gelFrame = null;
        private ShapePropsAggregate shapProps = null;
        public DropBarAggregate(RecordStream rs, ChartRecordAggregate container)
            : base(RuleName_DROPBAR, container)
        {
            dropBar = (DropBarRecord)rs.GetNext();
            rs.GetNext();
            lineFormat = (LineFormatRecord)rs.GetNext();
            areaFormat = (AreaFormatRecord)rs.GetNext();

            if (rs.PeekNextChartSid() == GelFrameRecord.sid)
            {
                gelFrame = new GelFrameAggregate(rs, this);
            }
            if (rs.PeekNextChartSid() == ShapePropsStreamRecord.sid)
            {
                shapProps = new ShapePropsAggregate(rs, this);
            }

            Record r = rs.GetNext();//EndRecord
            Debug.Assert(r.GetType() == typeof(EndRecord));
        }

        public override void VisitContainedRecords(RecordVisitor rv)
        {
            rv.VisitRecord(dropBar);
            rv.VisitRecord(BeginRecord.instance);
            rv.VisitRecord(lineFormat);
            rv.VisitRecord(areaFormat);

            if (gelFrame != null)
                gelFrame.VisitContainedRecords(rv);
            if (shapProps != null)
                shapProps.VisitContainedRecords(rv);

            WriteEndBlock(rv);
            rv.VisitRecord(EndRecord.instance);
        }
    }
}


text:
package br.com.wagnersoft.esculapio.services;

import br.com.wagnersoft.esculapio.dao.BeneficiarioDao;
import br.com.wagnersoft.esculapio.dao.GuiaEncaminhamentoDao;
import br.com.wagnersoft.esculapio.dao.OcsPmDao;
import br.com.wagnersoft.esculapio.model.Beneficiario;
import br.com.wagnersoft.esculapio.model.GuiaEncaminhamento;
import br.com.wagnersoft.esculapio.model.GuiaOcsPm;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.transaction.annotation.Transactional;

/** Serviço para Guia de Encaminhamento. (Tabela GUIA_ENCAMINHAMENTO)
 * @author Abreu Lopes
 * @since 1.0
 * @version $Id$
 */
@Named("guiaEncaminhamentoService")
@RemoteProxy(name="guiaService")
public class GuiaEncaminhamentoService {

  @Inject
  private BeneficiarioDao benDao;

  @Inject
  private GuiaEncaminhamentoDao guiaDao;

  @Inject
  private OcsPmDao ocsPmDao;

  /** Construtor. */
  public GuiaEncaminhamentoService() {
  }

  @Transactional
  public void excluir(final GuiaEncaminhamento guia) throws Exception {
    final Beneficiario b = this.benDao.findById(guia.getBeneficiario().getId());
    b.removeGuia(guia);
    this.benDao.save(b);
  }

  public GuiaEncaminhamento recuperar(final Integer id) throws Exception {
    return this.guiaDao.findById(id);
  }

  @Transactional
  public GuiaEncaminhamento salvar(final GuiaEncaminhamento guia) throws Exception {
    final List<GuiaOcsPm> listaPM = guia.getGuiaOcsPm();
    if (guia.getEmissaoData() == null) {
      guia.setEmissaoData(new Date());
    }
    guia.setGuiaOcsPm(null);
    final GuiaEncaminhamento guiaNew = this.guiaDao.save(guia);
    this.guiaDao.getEntityManager().flush();
    if (listaPM != null && !listaPM.isEmpty()) {
      BigDecimal total = new BigDecimal("0");
      for (final GuiaOcsPm gop: listaPM) {
        gop.setOcsPm(this.ocsPmDao.findById(gop.getOcsPm().getId()));
        total = (gop.getOcsPm().getValor().multiply(BigDecimal.valueOf(gop.getPmQtd()))).add(total);
        guiaNew.getGuiaOcsPm().add(gop);
        gop.setGuiaEncaminhamento(guiaNew);
      }
      guiaNew.setValorTotal(total);
    }
    this.guiaDao.getEntityManager().flush();
    return this.guiaDao.save(guiaNew);
  }

  @RemoteMethod
  public Beneficiario[] listarBeneficiario(final String precCp) throws Exception {
    final List<Beneficiario> lista = this.benDao.findByNamedQuery("Beneficiario.findByPrecCp", precCp);
    return lista.toArray(new Beneficiario[0]);
  }

  public Integer calcularIdade(final Date dataNasc) {
    final Calendar hoje = new GregorianCalendar();
    final Calendar dn = new GregorianCalendar();
    dn.setTime(dataNasc);
    int idade = hoje.get(Calendar.YEAR) - dn.get(Calendar.YEAR);
    boolean isMesMaior = dn.get(Calendar.MONTH) >= hoje.get(Calendar.MONTH);
    boolean isMesIgualMasDiaMaior = dn.get(Calendar.MONTH) == hoje.get(Calendar.MONTH) && dn.get(Calendar.DAY_OF_MONTH) > hoje.get(Calendar.DAY_OF_MONTH);
    if (isMesMaior || isMesIgualMasDiaMaior) {
      idade -= 1;
    }
    return idade;
  }

}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * CancelConversionTaskRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CancelConversionTaskRequestMarshaller implements Marshaller<Request<CancelConversionTaskRequest>, CancelConversionTaskRequest> {

    public Request<CancelConversionTaskRequest> marshall(CancelConversionTaskRequest cancelConversionTaskRequest) {

        if (cancelConversionTaskRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<CancelConversionTaskRequest> request = new DefaultRequest<CancelConversionTaskRequest>(cancelConversionTaskRequest, "AmazonEC2");
        request.addParameter("Action", "CancelConversionTask");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (cancelConversionTaskRequest.getConversionTaskId() != null) {
            request.addParameter("ConversionTaskId", StringUtils.fromString(cancelConversionTaskRequest.getConversionTaskId()));
        }

        if (cancelConversionTaskRequest.getReasonMessage() != null) {
            request.addParameter("ReasonMessage", StringUtils.fromString(cancelConversionTaskRequest.getReasonMessage()));
        }

        return request;
    }

}


text:
package com.eagle.programmar.Perl.Statements;

import com.eagle.programmar.Perl.Perl_Expression;
import com.eagle.programmar.Perl.Perl_Statement;
import com.eagle.programmar.Perl.Terminals.Perl_Comment;
import com.eagle.programmar.Perl.Terminals.Perl_Keyword;
import com.eagle.programmar.Perl.Terminals.Perl_KeywordChoice;
import com.eagle.tokens.TokenChooser;
import com.eagle.tokens.TokenList;
import com.eagle.tokens.TokenSequence;
import com.eagle.tokens.punctuation.PunctuationHyphen;
import com.eagle.tokens.punctuation.PunctuationLeftParen;
import com.eagle.tokens.punctuation.PunctuationRightParen;

public class Perl_IfStatement extends TokenSequence
{
	public @DOC("control-structures.if.php") Perl_Keyword IF = new Perl_Keyword("if");
	public PunctuationLeftParen leftParen;
	public Perl_IfWhat condition;
	public @OPT TokenList<Perl_Comment> comments1;
	public PunctuationRightParen rightParen;
	public @OPT TokenList<Perl_Comment> comments2;
	public Perl_Statement thenStatement;
	public @OPT TokenList<Perl_Comment> comments3;
	public @OPT TokenList<Perl_IfElseIfClause> elseIfClauses;
	public @OPT TokenList<Perl_Comment> comments4;
	public @OPT Perl_IfElseClause elseClause;

	public static class Perl_IfWhat extends TokenChooser
	{
		public @LAST Perl_Expression condition;

		public @CHOICE static class Perl_IfExists extends TokenSequence
		{
			public PunctuationHyphen minus;
			public Perl_Keyword F = new Perl_Keyword("f");
			public Perl_Expression expr;
		}
	}

	public static class Perl_IfElseIfClause extends TokenSequence
	{
		public Perl_KeywordChoice ELSEIF = new Perl_KeywordChoice("elseif", "elsif");
		public PunctuationLeftParen leftParen;
		public Perl_Expression condition;
		public PunctuationRightParen rightParen;
		public @OPT TokenList<Perl_Comment> comments;
		public Perl_Statement elseIfStatement;
	}

	public static class Perl_IfElseClause extends TokenSequence
	{
		public Perl_Keyword ELSE = new Perl_Keyword("else");
		public @OPT TokenList<Perl_Comment> comments;
		public Perl_Statement elseStatement;
	}
}


text:
`else if` is spelled as two words in Ferret.

    if false {
        say("Nothing here will happen")
    }

    else if true {
        say("This will be said")
    }

    else {
        say("This will not be reached")
    }

And an example without braces.

    if false
        say("Nothing here will happen")
    else if true
        say("This will be said")
    else
        say("This will not be reached")

[Next: inside](18-inside.md)


text:
#include "config.h"
#include "core/platform/graphics/DrawLooper.h"

#include "core/platform/graphics/Color.h"
#include "core/platform/graphics/FloatSize.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkColorFilter.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkXfermode.h"
#include "third_party/skia/include/effects/SkBlurMaskFilter.h"

namespace WebCore {

DrawLooper::DrawLooper() : m_skDrawLooper(new SkLayerDrawLooper) { }

void DrawLooper::addUnmodifiedContent()
{
    SkLayerDrawLooper::LayerInfo info;
    m_skDrawLooper->addLayerOnTop(info);
}

void DrawLooper::addShadow(const FloatSize& offset, float blur, const Color& color,
    ShadowTransformMode shadowTransformMode, ShadowAlphaMode shadowAlphaMode)
{
    // Detect when there's no effective shadow.
    if (!color.isValid() || !color.alpha())
        return;

    SkColor skColor;
    if (color.isValid())
        skColor = color.rgb();
    else
        skColor = SkColorSetARGB(0xFF / 3, 0, 0, 0); // "std" apple shadow color.

    SkLayerDrawLooper::LayerInfo info;

    switch (shadowAlphaMode) {
    case ShadowRespectsAlpha:
        info.fColorMode = SkXfermode::kDst_Mode;
        break;
    case ShadowIgnoresAlpha:
        info.fColorMode = SkXfermode::kSrc_Mode;
        break;
    default:
        ASSERT_NOT_REACHED();
    }

    if (blur)
        info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; // our blur
    info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit;
    info.fOffset.set(offset.width(), offset.height());
    info.fPostTranslate = (shadowTransformMode == ShadowIgnoresTransforms);

    SkPaint* paint = m_skDrawLooper->addLayerOnTop(info);

    if (blur) {
        uint32_t mfFlags = SkBlurMaskFilter::kHighQuality_BlurFlag;
        if (shadowTransformMode == ShadowIgnoresTransforms)
            mfFlags |= SkBlurMaskFilter::kIgnoreTransform_BlurFlag;
        SkMaskFilter* mf = SkBlurMaskFilter::Create((double)blur / 2.0,
            SkBlurMaskFilter::kNormal_BlurStyle, mfFlags);
        SkSafeUnref(paint->setMaskFilter(mf));
    }

    SkColorFilter* cf = SkColorFilter::CreateModeFilter(skColor, SkXfermode::kSrcIn_Mode);
    SkSafeUnref(paint->setColorFilter(cf));
}

} // namespace WebCore


text:
package org.bsworks.x2.services.serialization.impl.json;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.NoSuchElementException;

import javax.json.JsonException;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
import javax.json.stream.JsonParsingException;

import org.bsworks.x2.Actor;
import org.bsworks.x2.resource.InvalidResourceDataException;
import org.bsworks.x2.resource.Ref;
import org.bsworks.x2.resource.ResourceReadSession;
import org.bsworks.x2.resource.ResourceReadSessionCache;
import org.bsworks.x2.resource.Resources;
import org.bsworks.x2.resource.TypePropertyHandler;

/**
 * Resource read session implementation for deserializing resource from JSON.
 *
 * @author Lev Himmelfarb
 */
class ResourceReadSessionImpl
	implements ResourceReadSession {

	/**
	 * JSON parser.
	 */
	private final JsonParser par;

	/**
	 * The providing actor.
	 */
	private final Actor actor;

	/**
	 * Parser for {@link Date} fields.
	 */
	private final DateFormat df;

	/**
	 * Resources manager.
	 */
	private final Resources resources;

	/**
	 * Tells if the last {@code null} value was because of the current
	 * collection end.
	 */
	private boolean wasCollectionEnd;

	/**
	 * Create new session.
	 *
	 * @param par JSON parser.
	 * @param actor The providing actor, or {@code null}.
	 * @param df Parser for {@link Date} fields.
	 * @param resources Resources manager.
	 */
	ResourceReadSessionImpl(final JsonParser par, final Actor actor,
			final DateFormat df, final Resources resources) {

		this.par = par;
		this.actor = actor;
		this.df = df;
		this.resources = resources;
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Actor getActor() {

		return this.actor;
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Date stringToDate(final String dateStr)
		throws InvalidResourceDataException {

		try {
			return this.df.parse(dateStr);
		} catch (final ParseException e) {
			throw new InvalidResourceDataException(
					"Invalid date value " + dateStr + ".", e);
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public ResourceReadSessionCache getSessionCache() {

		// caching is not used
		return null;
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public String nextProperty()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case KEY_NAME:
				return this.par.getString();
			case END_OBJECT:
				return null;
			default:
				throw new IllegalStateException("Received " + ev + ".");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public void swallowValue()
		throws InvalidResourceDataException, IOException {

		try {
			this.swallowValueInternal();
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/**
	 * Recursively swallow next value in the parser.
	 *
	 * @return Last swallowed parser event.
	 */
	private Event swallowValueInternal() {

		Event ev = this.par.next();
		switch (ev) {
		case START_ARRAY:
			while ((ev = this.swallowValueInternal())
					!= Event.END_ARRAY)  { /* nothing */ }
			return null;
		case START_OBJECT:
			while ((ev = this.swallowValueInternal())
					!= Event.END_OBJECT)  { /* nothing */ }
			return null;
		default:
		}

		return ev;
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public boolean enterObject()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case START_OBJECT:
				return true;
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return false;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return false;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid object or map property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public boolean enterCollection()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case START_ARRAY:
				return true;
			case VALUE_NULL:
				return false;
			case KEY_NAME:
			case END_ARRAY:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid collection property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public boolean enterMap()
		throws InvalidResourceDataException, IOException {

		return this.enterObject();
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public String readObjectType(final TypePropertyHandler typePropHandler)
		throws InvalidResourceDataException, IOException {

		try {
			Event ev = this.par.next();
			if (ev != Event.KEY_NAME)
				throw new IllegalStateException("Received " + ev + ".");
			final String typePropName = typePropHandler.getName();
			if (!this.par.getString().equals(typePropName))
				throw new InvalidResourceDataException("First property of the"
						+ " polymorphic object must be " + typePropName + ".");
			ev = this.par.next();
			if (ev != Event.VALUE_STRING)
				throw new InvalidResourceDataException("Value of "
						+ typePropName + " property must be string.");
			return this.par.getString();
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public String readKey()
		throws InvalidResourceDataException, IOException {

		return this.nextProperty();
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public String readStringValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_STRING:
				return this.par.getString();
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Byte readByteValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				final int val = this.par.getInt();
				if ((val < Byte.MIN_VALUE) || (val > Byte.MAX_VALUE))
					throw new InvalidResourceDataException(
							"Property value out of range.");
				return Byte.valueOf((byte) val);
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Short readShortValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				final int val = this.par.getInt();
				if ((val < Short.MIN_VALUE) || (val > Short.MAX_VALUE))
					throw new InvalidResourceDataException(
							"Property value out of range.");
				return Short.valueOf((short) val);
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Integer readIntegerValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				return Integer.valueOf(this.par.getInt());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Long readLongValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				return Long.valueOf(this.par.getLong());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Boolean readBooleanValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_TRUE:
				return Boolean.TRUE;
			case VALUE_FALSE:
				return Boolean.FALSE;
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Float readFloatValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				final double val = this.par.getBigDecimal().doubleValue();
				if ((val < Float.MIN_VALUE) || (val > Float.MAX_VALUE))
					throw new InvalidResourceDataException(
							"Property value out of range.");
				return Float.valueOf((float) val);
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Double readDoubleValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				return Double.valueOf(this.par.getBigDecimal().doubleValue());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public BigDecimal readBigDecimalValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_NUMBER:
				return this.par.getBigDecimal();
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public <E extends Enum<E>> E readEnumValue(final Class<E> enumClass)
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_STRING:
				return Enum.valueOf(enumClass, this.par.getString());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final IllegalArgumentException e) {
			throw new InvalidResourceDataException(
					"Invalid enumeration property value.", e);
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Date readDateValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_STRING:
				return this.df.parse(this.par.getString());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final ParseException e) {
			throw new InvalidResourceDataException(
					"Invalid date property value.", e);
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public Ref<?> readRefValue()
		throws InvalidResourceDataException, IOException {

		try {
			final Event ev = this.par.next();
			switch (ev) {
			case VALUE_STRING:
				return this.resources.parseRef(this.par.getString());
			case VALUE_NULL:
				this.wasCollectionEnd = false;
				return null;
			case END_ARRAY:
				this.wasCollectionEnd = true;
				return null;
			case KEY_NAME:
			case END_OBJECT:
				throw new IllegalStateException("Received " + ev + ".");
			default:
				throw new InvalidResourceDataException(
						"Invalid property value type.");
			}
		} catch (final IllegalArgumentException e) {
			throw new InvalidResourceDataException(
					"Invalid reference property value.", e);
		} catch (final JsonParsingException | NoSuchElementException e) {
			throw new InvalidResourceDataException("Invalid JSON.", e);
		} catch (final JsonException e) {
			if (e.getCause() instanceof IOException)
				throw (IOException) e.getCause();
			throw e;
		}
	}

	/* (non-Javadoc)
	 * See overridden method.
	 */
	@Override
	public boolean wasCollectionEnd() {

		return this.wasCollectionEnd;
	}
}


text:
using System.Linq;
using UnityEngine;

namespace UnityStandardAssets._2D
{
    public class Camera2DFollow : MonoBehaviour
    {
        public Transform target;
        public float damping = 1;
        public float lookAheadFactor = 10;
        public float lookAheadReturnSpeed = 0.5f;
        public float lookAheadMoveThreshold = 0.1f;

        private float m_OffsetZ;
        private Vector3 m_LastTargetPosition;
        private Vector3 m_CurrentVelocity;
        private Vector3 m_LookAheadPos;

        // Use this for initialization
        private void Start()
        {
            var childTransform = target.GetComponentsInChildren<Transform>().Last();
            m_LastTargetPosition = childTransform.position;
            m_OffsetZ = (transform.position - childTransform.position).z;
            transform.parent = null;
        }

        // Update is called once per frame
        private void Update()
        {
            var childTransform = target.GetComponentsInChildren<Transform>().Last();
            // only update lookahead pos if accelerating or changed direction
            float yMoveDelta = (childTransform.position - m_LastTargetPosition).y;

            bool updateLookAheadTarget = Mathf.Abs(yMoveDelta) > lookAheadMoveThreshold;

            if (updateLookAheadTarget)
            {
                m_LookAheadPos = lookAheadFactor * Vector3.up * Mathf.Sign(yMoveDelta);
            }
            else
            {
                m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime * lookAheadReturnSpeed);
            }

            Vector3 aheadTargetPos = childTransform.position + m_LookAheadPos + Vector3.forward * m_OffsetZ;
            Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);

            transform.position = newPos;

            m_LastTargetPosition = childTransform.position;
        }
    }
}


text:
package org.zstack.sdk;

import org.zstack.sdk.OssBucketInventory;

public class CreateOssBucketRemoteResult {
    public OssBucketInventory inventory;
    public void setInventory(OssBucketInventory inventory) {
        this.inventory = inventory;
    }
    public OssBucketInventory getInventory() {
        return this.inventory;
    }

}


text:
import json
from moto.core.responses import BaseResponse
from .models import config_backends

class ConfigResponse(BaseResponse):
    @property
    def config_backend(self):
        return config_backends[self.region]

    def put_configuration_recorder(self):
        self.config_backend.put_configuration_recorder(
            self._get_param("ConfigurationRecorder")
        )
        return ""

    def put_configuration_aggregator(self):
        aggregator = self.config_backend.put_configuration_aggregator(
            json.loads(self.body), self.region
        )
        schema = {"ConfigurationAggregator": aggregator}
        return json.dumps(schema)

    def describe_configuration_aggregators(self):
        aggregators = self.config_backend.describe_configuration_aggregators(
            self._get_param("ConfigurationAggregatorNames"),
            self._get_param("NextToken"),
            self._get_param("Limit"),
        )
        return json.dumps(aggregators)

    def delete_configuration_aggregator(self):
        self.config_backend.delete_configuration_aggregator(
            self._get_param("ConfigurationAggregatorName")
        )
        return ""

    def put_aggregation_authorization(self):
        agg_auth = self.config_backend.put_aggregation_authorization(
            self.region,
            self._get_param("AuthorizedAccountId"),
            self._get_param("AuthorizedAwsRegion"),
            self._get_param("Tags"),
        )
        schema = {"AggregationAuthorization": agg_auth}
        return json.dumps(schema)

    def describe_aggregation_authorizations(self):
        authorizations = self.config_backend.describe_aggregation_authorizations(
            self._get_param("NextToken"), self._get_param("Limit")
        )

        return json.dumps(authorizations)

    def delete_aggregation_authorization(self):
        self.config_backend.delete_aggregation_authorization(
            self._get_param("AuthorizedAccountId"),
            self._get_param("AuthorizedAwsRegion"),
        )

        return ""

    def describe_configuration_recorders(self):
        recorders = self.config_backend.describe_configuration_recorders(
            self._get_param("ConfigurationRecorderNames")
        )
        schema = {"ConfigurationRecorders": recorders}
        return json.dumps(schema)

    def describe_configuration_recorder_status(self):
        recorder_statuses = self.config_backend.describe_configuration_recorder_status(
            self._get_param("ConfigurationRecorderNames")
        )
        schema = {"ConfigurationRecordersStatus": recorder_statuses}
        return json.dumps(schema)

    def put_delivery_channel(self):
        self.config_backend.put_delivery_channel(self._get_param("DeliveryChannel"))
        return ""

    def describe_delivery_channels(self):
        delivery_channels = self.config_backend.describe_delivery_channels(
            self._get_param("DeliveryChannelNames")
        )
        schema = {"DeliveryChannels": delivery_channels}
        return json.dumps(schema)

    def describe_delivery_channel_status(self):
        raise NotImplementedError()

    def delete_delivery_channel(self):
        self.config_backend.delete_delivery_channel(
            self._get_param("DeliveryChannelName")
        )
        return ""

    def delete_configuration_recorder(self):
        self.config_backend.delete_configuration_recorder(
            self._get_param("ConfigurationRecorderName")
        )
        return ""

    def start_configuration_recorder(self):
        self.config_backend.start_configuration_recorder(
            self._get_param("ConfigurationRecorderName")
        )
        return ""

    def stop_configuration_recorder(self):
        self.config_backend.stop_configuration_recorder(
            self._get_param("ConfigurationRecorderName")
        )
        return ""

    def list_discovered_resources(self):
        schema = self.config_backend.list_discovered_resources(
            self._get_param("resourceType"),
            self.region,
            self._get_param("resourceIds"),
            self._get_param("resourceName"),
            self._get_param("limit"),
            self._get_param("nextToken"),
        )
        return json.dumps(schema)

    def list_aggregate_discovered_resources(self):
        schema = self.config_backend.list_aggregate_discovered_resources(
            self._get_param("ConfigurationAggregatorName"),
            self._get_param("ResourceType"),
            self._get_param("Filters"),
            self._get_param("Limit"),
            self._get_param("NextToken"),
        )
        return json.dumps(schema)

    def get_resource_config_history(self):
        schema = self.config_backend.get_resource_config_history(
            self._get_param("resourceType"), self._get_param("resourceId"), self.region
        )
        return json.dumps(schema)

    def batch_get_resource_config(self):
        schema = self.config_backend.batch_get_resource_config(
            self._get_param("resourceKeys"), self.region
        )
        return json.dumps(schema)

    def batch_get_aggregate_resource_config(self):
        schema = self.config_backend.batch_get_aggregate_resource_config(
            self._get_param("ConfigurationAggregatorName"),
            self._get_param("ResourceIdentifiers"),
        )
        return json.dumps(schema)

    def put_evaluations(self):
        evaluations = self.config_backend.put_evaluations(
            self._get_param("Evaluations"),
            self._get_param("ResultToken"),
            self._get_param("TestMode"),
        )
        return json.dumps(evaluations)

    def put_organization_conformance_pack(self):
        conformance_pack = self.config_backend.put_organization_conformance_pack(
            region=self.region,
            name=self._get_param("OrganizationConformancePackName"),
            template_s3_uri=self._get_param("TemplateS3Uri"),
            template_body=self._get_param("TemplateBody"),
            delivery_s3_bucket=self._get_param("DeliveryS3Bucket"),
            delivery_s3_key_prefix=self._get_param("DeliveryS3KeyPrefix"),
            input_parameters=self._get_param("ConformancePackInputParameters"),
            excluded_accounts=self._get_param("ExcludedAccounts"),
        )

        return json.dumps(conformance_pack)

    def describe_organization_conformance_packs(self):
        conformance_packs = self.config_backend.describe_organization_conformance_packs(
            self._get_param("OrganizationConformancePackNames")
        )

        return json.dumps(conformance_packs)

    def describe_organization_conformance_pack_statuses(self):
        statuses = self.config_backend.describe_organization_conformance_pack_statuses(
            self._get_param("OrganizationConformancePackNames")
        )

        return json.dumps(statuses)

    def get_organization_conformance_pack_detailed_status(self):
        # 'Filters' parameter is not implemented yet
        statuses = self.config_backend.get_organization_conformance_pack_detailed_status(
            self._get_param("OrganizationConformancePackName")
        )

        return json.dumps(statuses)

    def delete_organization_conformance_pack(self):
        self.config_backend.delete_organization_conformance_pack(
            self._get_param("OrganizationConformancePackName")
        )

        return ""


text:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { CitySetPoint } from 'components'
import { changeEditCity, updateCities } from 'actions'

const mapStateToProps = ({points: {data}, cities: {edit}}) => (({
  data, current: edit
}));

const mapDispatchToProps = {
  save: updateCities,
  change: changeEditCity
};

@connect(mapStateToProps, mapDispatchToProps)
export default class CitySetPointContainer extends Component {

  changeHandler = e => {
    const name = e.target.value;
    const data = this.props.data.find(it => it.name === name);
    let id = null;

    if (data) {
      id = data.id;
    }

    if (this.props.current.id) {
      return this.props.save([{
        id: this.props.current.id,
        main_point: id
      }])
    }

    this.props.change({
      main_point: id
    })
  };

  render() {
    return <CitySetPoint data={this.props.data}
                         current={this.props.current}
                         onChange={this.changeHandler}/>
  }
}


text:
<!DOCTYPE html>
<html lang="{{ blog.get_current_language }}">
    <head>
        <title>{{ blog.get_name }} - {% block title %}{% endblock %}</title>
    </head>
    <body>

    </body>
</html>


text:
package fm.liu.timo.mysql.packet;

import java.nio.ByteBuffer;
import fm.liu.timo.mysql.BufferUtil;
import fm.liu.timo.mysql.MySQLMessage;

/**
 * From server to client in response to command, if no error and no result set.
 *
 * <pre>
 * Bytes                       Name
 * -----                       ----
 * 1                           field_count, always = 0
 * 1-9 (Length Coded Binary)   affected_rows
 * 1-9 (Length Coded Binary)   insert_id
 * 2                           server_status
 * 2                           warning_count
 * n   (until end of packet)   message fix:(Length Coded String)
 *
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#OK_Packet
 * </pre>
 *
 */
public class OkPacket extends MySQLServerPacket {
    public static final byte   FIELD_COUNT = 0x00;
    public static final byte[] OK          = new byte[] {7, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0};

    public byte   fieldCount = FIELD_COUNT;
    public long   affectedRows;
    public long   insertId;
    public int    serverStatus;
    public int    warningCount;
    public byte[] message;

    @Override
    protected void readBody(MySQLMessage mm) {
        fieldCount = mm.read();
        affectedRows = mm.readLength();
        insertId = mm.readLength();
        serverStatus = mm.readUB2();
        warningCount = mm.readUB2();
        if (mm.hasRemaining()) {
            this.message = mm.readBytesWithLength();
        }
    }

    @Override
    protected void writeBody(ByteBuffer buffer) {
        buffer.put(fieldCount);
        BufferUtil.writeLength(buffer, affectedRows);
        BufferUtil.writeLength(buffer, insertId);
        BufferUtil.writeUB2(buffer, serverStatus);
        BufferUtil.writeUB2(buffer, warningCount);
        if (message != null) {
            BufferUtil.writeWithLength(buffer, message);
        }
    }

    @Override
    public int calcPacketSize() {
        int i = 1;
        i += BufferUtil.getLength(affectedRows);
        i += BufferUtil.getLength(insertId);
        i += 4;
        if (message != null) {
            i += BufferUtil.getLength(message);
        }
        return i;
    }

    @Override
    protected String getPacketInfo() {
        return "MySQL OK Packet";
    }

}


text:
using double_2 = std::tuple<double, double>;

template<std::size_t dim, typename T, typename A>
void update_overlap(const mpl::cartesian_communicator &communicator,
                    mpl::distributed_grid<dim, T, A> &distributed_grid,
                    mpl::tag_t tag = mpl::tag_t()) {
  mpl::shift_ranks ranks;
  mpl::irequest_pool r;
  for (std::size_t i{0}; i < dim; ++i) {
    // send to left
    ranks = communicator.shift(i, -1);
    r.push(communicator.isend(distributed_grid.data(), distributed_grid.left_border_layout(i),
                              ranks.destination, tag));
    r.push(communicator.irecv(distributed_grid.data(), distributed_grid.right_mirror_layout(i),
                              ranks.source, tag));
    // send to right
    ranks = communicator.shift(i, +1);
    r.push(communicator.isend(distributed_grid.data(), distributed_grid.right_border_layout(i),
                              ranks.destination, tag));
    r.push(communicator.irecv(distributed_grid.data(), distributed_grid.left_mirror_layout(i),
                              ranks.source, tag));
  }
  r.waitall();
}

template<std::size_t dim, typename T, typename A>
void scatter(const mpl::cartesian_communicator &communicator, int root,
             const mpl::local_grid<dim, T, A> &local_grid,
             mpl::distributed_grid<dim, T, A> &distributed_grid) {
  communicator.scatterv(root, local_grid.data(), local_grid.sub_layouts(),
                        distributed_grid.data(), distributed_grid.interior_layout());
}

template<std::size_t dim, typename T, typename A>
void scatter(const mpl::cartesian_communicator &communicator, int root,
             mpl::distributed_grid<dim, T, A> &distributed_grid) {
  communicator.scatterv(root, distributed_grid.data(), distributed_grid.interior_layout());
}

template<std::size_t dim, typename T, typename A>
void gather(const mpl::cartesian_communicator &communicator, int root,
            const mpl::distributed_grid<dim, T, A> &distributed_grid,
            mpl::local_grid<dim, T, A> &local_grid) {
  communicator.gatherv(root, distributed_grid.data(), distributed_grid.interior_layout(),
                       local_grid.data(), local_grid.sub_layouts());
}

template<std::size_t dim, typename T, typename A>
void gather(const mpl::cartesian_communicator &communicator, int root,
            const mpl::distributed_grid<dim, T, A> &distributed_grid) {
  communicator.gatherv(root, distributed_grid.data(), distributed_grid.interior_layout());
}

int main() {
  // world communicator
  const mpl::communicator &comm_world{mpl::environment::comm_world()};
  // construct a two-dimensional Cartesian communicator with no periodic boundary conditions
  mpl::cartesian_communicator::dimensions size{mpl::cartesian_communicator::non_periodic,
                                               mpl::cartesian_communicator::non_periodic};
  mpl::cartesian_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), size));
  // total number of inner grid points
  const int n_x{768}, n_y{512};
  // grid points with extremal indices (-1, Nx or Ny) hold fixed boundary data
  // grid lengths and grid spacings
  const double l_x{1.5}, l_y{1};
  const double dx{l_x / (n_x + 1)}, dy{l_y / (n_y + 1)};
  // distributed grid that holds each processor's subgrid plus one row and
  // one column of neighboring data
  mpl::distributed_grid<2, double> u_d{comm_c, {{n_x, 1}, {n_y, 1}}};
  // rank 0 initializes with some random data
  if (comm_c.rank() == 0) {
    std::default_random_engine engine;
    std::uniform_real_distribution<double> uniform{0, 1};
    // local grid to store the whole set of inner grid points
    mpl::local_grid<2, double> u{comm_c, {n_x, n_y}};
    for (auto j{u.begin(1)}, j_end{u.end(1)}; j < j_end; ++j)
      for (auto i{u.begin(0)}, i_end{u.end(0)}; i < i_end; ++i)
        u(i, j) = uniform(engine);
    // scatter data to each processors subgrid
    scatter(comm_c, 0, u, u_d);
  } else
    scatter(comm_c, 0, u_d);
  // initialize boundary data, loop with obegin and oend over all
  // data including the overlap
  for (auto j : {u_d.obegin(1), u_d.oend(1) - 1})
    for (auto i{u_d.obegin(0)}, i_end{u_d.oend(0)}; i < i_end; ++i) {
      if (u_d.gindex(0, i) < 0 or u_d.gindex(1, j) < 0)
        u_d(i, j) = 1;  // left boundary condition
      if (u_d.gindex(0, i) >= n_x or u_d.gindex(1, j) >= n_y)
        u_d(i, j) = 0;  // right boundary condition
    }
  for (auto i : {u_d.obegin(0), u_d.oend(0) - 1})
    for (auto j{u_d.obegin(1)}, j_end{u_d.oend(1)}; j < j_end; ++j) {
      if (u_d.gindex(0, i) < 0 or u_d.gindex(1, j) < 0)
        u_d(i, j) = 1;  // lower boundary condition
      if (u_d.gindex(0, i) >= n_x or u_d.gindex(1, j) >= n_y)
        u_d(i, j) = 0;  // upper boundary condition
    }
  double w{1.875};  // the over-relaxation parameter
  double dx_2{dx * dx}, dy_2{dy * dy};
  // loop until converged
  bool converged{false};
  while (not converged) {
    // exchange overlap data
    update_overlap(comm_c, u_d);
    // apply one successive over-relaxation step
    double delta_u{0}, sum_u{0};
    for (auto j{u_d.begin(1)}, j_end{u_d.end(1)}; j < j_end; ++j)
      for (auto i{u_d.begin(0)}, i_end{u_d.end(0)}; i < i_end; ++i) {
        double du = -w * u_d(i, j) + w *
                                         (dy_2 * (u_d(i - 1, j) + u_d(i + 1, j)) +
                                          dx_2 * (u_d(i, j - 1) + u_d(i, j + 1))) /
                                         (2 * (dx_2 + dy_2));
        u_d(i, j) += du;
        delta_u += std::abs(du);
        sum_u += std::abs(u_d(i, j));
      }
    // determine global sum of Delta_u and sum_u and distribute to all processors
    double_2 delta_sum_u{delta_u, sum_u};  // pack into pair
    // use a lambda function for global reduction
    comm_c.allreduce(
        [](double_2 a, double_2 b) {
          // reduction adds component-by-component
          return double_2{std::get<0>(a) + std::get<0>(b), std::get<1>(a) + std::get<1>(b)};
        },
        delta_sum_u);
    std::tie(delta_u, sum_u) = delta_sum_u;  // unpack from pair
    converged = delta_u / sum_u < 1e-6;      // check for convergence
  }
  if (comm_c.rank() == 0) {
    // local grid to store the whole set of inner grid points
    mpl::local_grid<2, double> u{comm_c, {n_x, n_y}};
    // gather data and print result
    gather(comm_c, 0, u_d, u);
    for (auto j{u.begin(1)}, j_end{u.end(1)}; j < j_end; ++j) {
      for (auto i{u.begin(0)}, i_end{u.end(0)}; i < i_end; ++i)
        std::cout << u(i, j) << '\t';
      std::cout << '\n';
    }
  } else
    gather(comm_c, 0, u_d);
  return EXIT_SUCCESS;
}


text:
<?php
namespace test\f\n;
class j { }


text:
// ****************************** Module Header ****************************** //
//
//
// Last Modified: 08:05:2017 / 17:59
// Creation: 08:05:2017
// Project: AstroSoundBoard
//
//
// <copyright file="FileSystem.cs" company="Patrick Hollweck" GitHub="https://github.com/FetzenRndy">//</copyright>
// *************************************************************************** //

using System.IO;

namespace AstroSoundBoard.Core.Utils
{
    public static class FileSystem
    {
        public static class FolderHelper
        {
            /// <summary>
            /// Creates a Folder if it does not exist
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            public static void CreateIfMissing(string path)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
        }
    }
}