text:
/////////////////////////////////////////////////////////////////////////////
// Name:        sashwin.h
// Purpose:     interface of wxSashWindow
// Author:      wxWidgets team
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

/**
   wxSashWindow flags
*/
#define wxSW_NOBORDER         0x0000
#define wxSW_BORDER           0x0020
#define wxSW_3DSASH           0x0040
#define wxSW_3DBORDER         0x0080
#define wxSW_3D (wxSW_3DSASH | wxSW_3DBORDER)

/**
    See wxSashWindow.
*/
enum wxSashEdgePosition
{
    wxSASH_TOP = 0,
    wxSASH_RIGHT,
    wxSASH_BOTTOM,
    wxSASH_LEFT,
    wxSASH_NONE = 100
};

/**
    See wxSashEvent.
*/
enum wxSashDragStatus
{
    wxSASH_STATUS_OK,
    wxSASH_STATUS_OUT_OF_RANGE
};

/**
    @class wxSashWindow

    wxSashWindow allows any of its edges to have a sash which can be dragged
    to resize the window. The actual content window will be created by the
    application as a child of wxSashWindow.

    The window (or an ancestor) will be notified of a drag via a
    wxSashEvent notification.

    @beginStyleTable
    @style{wxSW_3D}
           Draws a 3D effect sash and border.
    @style{wxSW_3DSASH}
           Draws a 3D effect sash.
    @style{wxSW_3DBORDER}
           Draws a 3D effect border.
    @style{wxSW_BORDER}
           Draws a thin black border.
    @endStyleTable

    @beginEventEmissionTable{wxSashEvent}
    @event{EVT_SASH_DRAGGED(id, func)}
           Process a @c wxEVT_SASH_DRAGGED event, when the user has finished
           dragging a sash.
    @event{EVT_SASH_DRAGGED_RANGE(id1, id2, func)}
           Process a @c wxEVT_SASH_DRAGGED_RANGE event, when the user has
           finished dragging a sash. The event handler is called when windows
           with ids in the given range have their sashes dragged.
    @endEventTable

    @library{wxcore}
    @category{miscwnd}

    @see wxSashEvent, wxSashLayoutWindow, @ref overview_events
*/
class wxSashWindow : public wxWindow
{
public:
    /**
        Default ctor.
    */
    wxSashWindow();

    /**
        Constructs a sash window, which can be a child of a frame, dialog or any other
        non-control window.

        @param parent
            Pointer to a parent window.
        @param id
            Window identifier. If -1, will automatically create an identifier.
        @param pos
            Window position. wxDefaultPosition is (-1, -1) which indicates that
            wxSashWindows should generate a default position for the window.
            If using the wxSashWindow class directly, supply an actual position.
        @param size
            Window size. wxDefaultSize is (-1, -1) which indicates that wxSashWindows
            should generate a default size for the window.
        @param style
            Window style. For window styles, please see wxSashWindow.
        @param name
            Window name.
    */
    wxSashWindow(wxWindow* parent, wxWindowID id,
                 const wxPoint& pos = wxDefaultPosition,
                 const wxSize& size = wxDefaultSize,
                 long style = wxCLIP_CHILDREN | wxSW_3D,
                 const wxString& name = "sashWindow");

    /**
        Destructor.
    */
    virtual ~wxSashWindow();

    /**
        Gets the maximum window size in the x direction.
    */
    virtual int GetMaximumSizeX() const;

    /**
        Gets the maximum window size in the y direction.
    */
    virtual int GetMaximumSizeY() const;

    /**
        Gets the minimum window size in the x direction.
    */
    virtual int GetMinimumSizeX() const;

    /**
        Gets the minimum window size in the y direction.
    */
    virtual int GetMinimumSizeY() const;

    /**
        Returns @true if a sash is visible on the given edge, @false otherwise.

        @param edge
            Edge. One of wxSASH_TOP, wxSASH_RIGHT, wxSASH_BOTTOM, wxSASH_LEFT.

        @see SetSashVisible()
    */
    bool GetSashVisible(wxSashEdgePosition edge) const;

    /**
        Sets the maximum window size in the x direction.
    */
    virtual void SetMaximumSizeX(int min);

    /**
        Sets the maximum window size in the y direction.
    */
    virtual void SetMaximumSizeY(int min);

    /**
        Sets the minimum window size in the x direction.
    */
    virtual void SetMinimumSizeX(int min);

    /**
        Sets the minimum window size in the y direction.
    */
    virtual void SetMinimumSizeY(int min);

    /**
        Call this function to make a sash visible or invisible on a particular edge.

        @param edge
            Edge to change. One of wxSASH_TOP, wxSASH_RIGHT, wxSASH_BOTTOM, wxSASH_LEFT.
        @param visible
            @true to make the sash visible, @false to make it invisible.

        @see GetSashVisible()
    */
    void SetSashVisible(wxSashEdgePosition edge, bool visible);

    /**
       Get border size
    */
    int GetEdgeMargin(wxSashEdgePosition edge) const;

    /**
       Sets the default sash border size
    */
    void SetDefaultBorderSize(int width);

    /**
       Gets the default sash border size
    */
    int GetDefaultBorderSize() const;

    /**
       Sets the additional border size between child and sash window
    */
    void SetExtraBorderSize(int width);

    /**
       Gets the addition border size between child and sash window
    */
    int GetExtraBorderSize() const;

    /**
       Tests for x, y over sash
    */
    wxSashEdgePosition SashHitTest(int x, int y, int tolerance = 2);

    /**
       Resizes subwindows
    */
    void SizeWindows();
};

/**
    @class wxSashEvent

    A sash event is sent when the sash of a wxSashWindow has been
    dragged by the user.

    @remarks
    When a sash belonging to a sash window is dragged by the user, and then released,
    this event is sent to the window, where it may be processed by an event table
    entry in a derived class, a plug-in event handler or an ancestor class.
    Note that the wxSashWindow doesn't change the window's size itself.
    It relies on the application's event handler to do that.
    This is because the application may have to handle other consequences of the resize,
    or it may wish to veto it altogether. The event handler should look at the drag
    rectangle: see wxSashEvent::GetDragRect to see what the new size of the window
    would be if the resize were to be applied.
    It should also call wxSashEvent::GetDragStatus to see whether the drag was
    OK or out of the current allowed range.

    @beginEventTable{wxSashEvent}
    @event{EVT_SASH_DRAGGED(id, func)}
        Process a @c wxEVT_SASH_DRAGGED event, when the user has finished dragging a sash.
    @event{EVT_SASH_DRAGGED_RANGE(id1, id2, func)}
        Process a @c wxEVT_SASH_DRAGGED_RANGE event, when the user has finished
        dragging a sash. The event handler is called when windows with ids in
        the given range have their sashes dragged.
    @endEventTable

    @library{wxcore}
    @category{events}

    @see wxSashWindow, @ref overview_events
*/
class wxSashEvent : public wxCommandEvent
{
public:
    /**
        Constructor.
    */
    wxSashEvent(int id = 0, wxSashEdgePosition edge = wxSASH_NONE);

    /**
        Returns the rectangle representing the new size the window would be if the
        resize was applied. It is up to the application to set the window size if required.
    */
    wxRect GetDragRect() const;

    /**
        Returns the status of the sash: one of wxSASH_STATUS_OK, wxSASH_STATUS_OUT_OF_RANGE.

        If the drag caused the notional bounding box of the window to flip over, for
        example, the drag will be out of rage.
    */
    wxSashDragStatus GetDragStatus() const;

    /**
        Returns the dragged edge.

        The return value is one of wxSASH_TOP, wxSASH_RIGHT, wxSASH_BOTTOM, wxSASH_LEFT.
    */
    wxSashEdgePosition GetEdge() const;

    void SetEdge(wxSashEdgePosition edge);
    void SetDragRect(const wxRect& rect);
    void SetDragStatus(wxSashDragStatus status);
};

wxEventType wxEVT_SASH_DRAGGED;


text:
class GuiButton : public GuiEntry {
public:
	// Ctor and dtor ///////////////////////////////////////////////////////////

	// GuiButton ctor
	// guiComp - GuiComponent the GuiButton is in
	// msg - Text to display on the button
	GuiButton(GuiComponent* guiComp, const std::string& msg);

	// GuiButton dtor
	virtual ~GuiButton();

	// Methods /////////////////////////////////////////////////////////////////

	// What should occurs when the GuiButton is clicked?
	virtual void onClick() {};
};

redpajama_set_name: RedPajamaGithub


text:
// Type: Highsoft.Web.Mvc.Stocks.PlotOptionsAreaDataLabelsOverflow

namespace Highsoft.Web.Mvc.Stocks
{
    public enum PlotOptionsAreaDataLabelsOverflow
    {
        Justify,
        None,
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.carlos.snippets</groupId>
		<artifactId>snippets-pom</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>

	<name>Snippets: JMX</name>
	<description>Snippets: JMX</description>

	<artifactId>snippets-jmx</artifactId>
	<packaging>jar</packaging>

</project>


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Dimensions,
    TouchableOpacity,
    InteractionManager,
    ActivityIndicator,
} from 'react-native';

let {width, height} = Dimensions.get('window');

import Image from 'react-native-image-progress';
import ProgressBar from 'react-native-progress/Bar';

import Icon from 'react-native-vector-icons/Ionicons';

import SatinItem from './satinItem';
import PictureItem from './pictureItem';
import VideoItem from './videoItem';

export default class itemDetail extends Component {
    static defaultProps = {
        // itemData: string,
        picturePress:null,
        satinPress:null,
    };

    render() {
        // 图片
        if (this.props.itemData.type == '10'){
            return(
                <View>
                    <SatinItem satinData={this.props.itemData.text} satinPress={this.props.satinPress} />
                    <PictureItem pictureData={this.props.itemData}
                                 picturePress={this.props.picturePress}
                    />
                </View>

            )
        }
        // 段子
        if (this.props.itemData.type == '29'){
            return(
                <SatinItem satinData={this.props.itemData.text}
                           satinPress={this.props.satinPress}
                />
            )
        }
        // 声音
        if (this.props.itemData.type == '31'){
            return(
                <View>
                    <SatinItem satinData={this.props.itemData.text}
                               satinPress={this.props.satinPress}
                    />
                    <Text>{this.props.itemData.text}</Text>
                </View>
            )
        }
        // 视频
        if (this.props.itemData.type == '41'){
            return(
                <View>
                    <SatinItem satinData={this.props.itemData.text}
                               satinPress={this.props.satinPress}
                    />
                    <VideoItem videoData={this.props.itemData}/>
                </View>
            )
        }

    }
}

// 视频
class VideoItem1 extends Component{
    static defaultProps = {
        // videoData: React.PropTypes.string,
        satinPress:null,
    };
    constructor(props){
        super(props);
        let imageHeight = (width - 20) * this.props.videoData.height / this.props.videoData.width;
        let videoTime = this.props.videoData.videotime / 60;
        videoTime = videoTime.toFixed(1);
        videoTime = videoTime.substring(0,videoTime.lastIndexOf('.'));
        let videoLastTime = this.props.videoData.videotime % 60;
        if (videoTime == 0){
            videoTime = '0' + videoTime;
        }
        if (videoTime >= 1 && videoTime <= 9){
            videoTime = '0' + videoTime;
        }
        if (videoLastTime<=9 && videoLastTime>=0){
            videoLastTime = '0' + videoLastTime;
        }
        this.state={
            imageHeight:imageHeight,
            videoTime:videoTime,
            videoLastTime:videoLastTime,
        };
    }
    render(){
        return(
            <View style={styles.imageViewStyle}>
                <Image source={{uri:this.props.videoData.cdn_img}} style={{width:width-20,height:this.state.imageHeight}}
                       indicator={ProgressBar}>
                    <Icon
                        name="ios-play"
                        size={45}
                        color='white'
                        style={[styles.playStyle,{position:'absolute',top:this.state.imageHeight/2-20,left:width/2-30,
                        }]}
                    />
                <View style={styles.videoBottomStyle}>
                    <Text style={styles.videoPlayStyle}>{this.props.videoData.playcount + '播放'}</Text>
                    <Text style={styles.videoTimeStyle}>{this.state.videoTime + ':' + this.state.videoLastTime}</Text>
                </View>

                </Image>
            </View>
        )
    }
}

// 段子
class SatinItem1 extends Component{
    static defaultProps = {
        // satinData: React.PropTypes.string,
        satinPress:null,
    };

    render(){
        return(
            <TouchableOpacity activeOpacity={0.8} onPress={this.props.satinPress}>
                <View style={styles.satinViewStyle}>
                    <Text style={styles.satinStyle}>
                        {this.props.satinData}
                    </Text>
                </View>
            </TouchableOpacity>
        )
    }
}

// 图片
class PictureItem1 extends Component{
    static defaultProps = {
        // pictureData: React.PropTypes.string,
        picturePress: null,
        satinPress: null,
    };

    constructor(props){
        super(props);
        let imageHeight = (width - 20) * this.props.pictureData.height / this.props.pictureData.width;
        this.state={
            imageHeight:imageHeight
        };
        // console.log('屏幕高度' + height);
        // console.log('图片展示高度'+this.state.imageHeight);
    }
    renderPicture(){
        // gif图
        if (this.props.pictureData.is_gif == '1'){
            // console.log('gif图' + this.props.pictureData.height);
            return(
                <Image source={{uri:this.props.pictureData.cdn_img}} style={{width:width-20,height:this.state.imageHeight}}
                       indicator={ProgressBar} resizeMode='contain'
                />
            )
        }
        // 长图
        if (this.state.imageHeight > height){
            // console.log('长图'+this.props.pictureData.height);
            return(
                <Image source={{uri:this.props.pictureData.image0}} style={{width:width-20,height:300}}
                       resizeMode='contain' indicator={ProgressBar}
                >
                    <View style={styles.longImageViewStyle}>
                        <Text style={styles.longImageTextStyle}>点击查看全图</Text>
                    </View>
                </Image>
            )
        }
        return(
            <Image source={{uri:this.props.pictureData.cdn_img}} style={{width:width-20,height:this.state.imageHeight}}
                   indicator={ProgressBar}
            />
        )
    }
    // 普通图片
    render(){
        return(
                <View style={styles.imageViewStyle}>
                    <TouchableOpacity onPress={this.props.picturePress} activeOpacity={0.8}>
                        {this.renderPicture()}
                    </TouchableOpacity>

                </View>
        )
    }
}

const styles = StyleSheet.create({
    satinViewStyle:{
        margin:10,
    },
    satinStyle:{
        fontSize:16,
    },
    imageViewStyle:{
        marginBottom:10,
        marginLeft:10,
        marginRight:10,
    },
    longImageViewStyle:{
        position:'absolute',
        bottom:0,

        height:40,
        width:width,
        backgroundColor:'rgba(88, 87, 86, 0.3)',
    },
    longImageTextStyle: {
        fontSize: 18,
        justifyContent: 'center',
        alignSelf: 'center',
        marginTop: 10,
    },
    loadDataStyle: {
        marginVertical:20
    },
    videoBottomStyle:{
        flexDirection:'row',
        position:'absolute',
        bottom:0,
        width:width-20,
    },
    videoPlayStyle:{
        position:'relative',
        left:0,
        backgroundColor:'rgba(88, 87, 86, 0.6)',
        color:'white'

    },
    videoTimeStyle:{
        position:'absolute',
        right:0,
        backgroundColor:'rgba(88, 87, 86, 0.6)',
        color:'white'
    },
    playStyle:{
        height:60,
        width:60,
        backgroundColor:'transparent',
        borderColor:'white',
        borderWidth:2,
        borderRadius:30,
        paddingTop:8,
        paddingLeft:22,

    }

});


text:
<?php

namespace Diegoalvarezb\Versioner\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

class Generate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'versioner:git:new';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a new version tag in Git';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->line("\n");
        $this->line("Generate a new version tag in Git");
        $this->line("---------------------------------");
        $this->line("");

        $releaseType = $this->choice(
            'What kind of release do you want to generate?',
            ['MAJOR', 'MINOR', 'PATCH'],
            2
        );

        // get version tag list
        $process = new Process('git tag -l "v*.*.*" | tail -1');
        $process->run();
        if (!$process->isSuccessful()) {
            $this->error("Error retrieving git tag list");

            $this->info("\n");
            exit;
        }

        $currentVersion = trim($process->getOutput());

        // get latest version
        if (empty($currentVersion)) {
            $currentVersion = 'v0.0.0';
        }

        $this->line("Current version: " . $currentVersion);

        // get new version
        $newVersion = $this->upgradeVersion($currentVersion, $releaseType);

        $this->line("New version: $newVersion");

        // create new tag
        $process = new Process("git tag -a '$newVersion' master -m '$releaseType release $newVersion'");
        $process->run();
        if (!$process->isSuccessful()) {
            $this->error("Error creating new git tag");

            $this->info("\n");
            exit;
        }

        $this->info("The tag has been generated");

        // push new tag
        $process = new Process("git push origin $newVersion");
        $process->run();
        if (!$process->isSuccessful()) {
            $this->error("Error pushing tag to remote");

            $this->line("");
            $this->line("You have to push manually");
            $this->line("> git push origin $newVersion");

            $this->info("\n");
            exit;
        }

        $this->info("The tag has been pushed");
        $this->info("\n");
    }

    /**
     * Generate a new version of the release type recieved by console argument.
     *
     * @param  string $currentVersion
     * @param  string $releaseType
     * @return string
     */
    protected function upgradeVersion($currentVersion, $releaseType)
    {
        $versionParts = explode('.', substr($currentVersion, 1));

        switch ($releaseType) {
            case 'PATCH':
                $versionParts[2]++;
                break;
            case 'MINOR':
                $versionParts[1]++;
                $versionParts[2] = 0;
                break;
            case 'MAJOR':
                $versionParts[0]++;
                $versionParts[1] = 0;
                $versionParts[2] = 0;
                break;
            default:
                $this->error("Invalid release type");

                $this->info("\n");
                exit;
        }

        $newVersion = "v" . implode('.', $versionParts);

        return $newVersion;
    }
}


text:
var App = require('app');
var date = require('utils/date');
var numberUtils = require('utils/number_utils');

App.MainDashboardServiceYARNView = App.MainDashboardServiceView.extend({
  templateName: require('templates/main/dashboard/service/yarn'),
  serviceName: 'YARN',

  nodeHeap: function () {
    var memUsed = this.get('service').get('jvmMemoryHeapUsed');
    var memCommitted = this.get('service').get('jvmMemoryHeapCommitted');
    var percent = memCommitted > 0 ? ((100 * memUsed) / memCommitted) : 0;
    return this.t('dashboard.services.hdfs.nodes.heapUsed').format(
        numberUtils.bytesToSize(memUsed, 1, 'parseFloat', 1024 * 1024),
        numberUtils.bytesToSize(memCommitted, 1, 'parseFloat', 1024 * 1024),
        percent.toFixed(1));

  }.property('service.jvmMemoryHeapUsed', 'service.jvmMemoryHeapCommitted'),

  summaryHeader: function () {
    var text = this.t("dashboard.services.yarn.summary");
    var svc = this.get('service');
    var totalCount = svc.get('nodeManagerNodes').get('length');
    return text.format(totalCount, totalCount);
  }.property('service.nodeManagerNodes'),

  nodeManagerComponent: function () {
    return App.HostComponent.find().findProperty('componentName', 'NODEMANAGER');
  }.property(),

  yarnClientComponent: function () {
    return App.HostComponent.find().findProperty('componentName', 'YARN_CLIENT');
  }.property(),

  hasManyYarnClients: function () {
    return (this.get('service.yarnClientNodes.length') > 1);
  }.property('service.yarnClientNodes.length'),

  nodeUptime: function () {
    var uptime = this.get('service').get('resourceManagerStartTime');
    if (uptime && uptime > 0){
      var diff = (new Date()).getTime() - uptime;
      if (diff < 0) {
        diff = 0;
      }
      var formatted = date.timingFormat(diff);
      return this.t('dashboard.services.uptime').format(formatted);
    }
    return this.t('services.service.summary.notRunning');
  }.property("service.resourceManagerStartTime"),

  nodeManagersLive: function () {
    return this.get('service.nodeManagerLiveNodes.length');
  }.property('service.nodeManagerNodes', 'service.nodeManagerLiveNodes'),

  nodeManagerText: function () {
    if(this.get("service.nodeManagerNodes.length") > 1){
      return Em.I18n.t('services.service.summary.viewHosts');
    }else{
      return Em.I18n.t('services.service.summary.viewHost');
    }
  }.property("service.nodeManagerNodes"),

  nodeManagersLiveTextView: App.ComponentLiveTextView.extend({
    liveComponents: function() {
      return this.get("service.nodeManagerLiveNodes.length");
    }.property('service.nodeManagerNodes', 'service.nodeManagerLiveNodes', 'service.nodeManagerLiveNodes.length'),
    totalComponents: function() {
      return this.get("service.nodeManagerNodes.length");
    }.property("service.nodeManagerNodes.length")
  }),

  nodeManagersStatus: function () {
    var nmActive = this.get('service.nodeManagersCountActive');
    var nmLost = this.get('service.nodeManagersCountLost');
    var nmUnhealthy = this.get('service.nodeManagersCountUnhealthy');
    var nmRebooted = this.get('service.nodeManagersCountRebooted');
    var nmDecom = this.get('service.nodeManagersCountDecommissioned');
    return this.t('dashboard.services.yarn.nodeManagers.status.msg').format(
      this.formatUnavailable(nmActive),
      this.formatUnavailable(nmLost),
      this.formatUnavailable(nmUnhealthy),
      this.formatUnavailable(nmRebooted),
      this.formatUnavailable(nmDecom)
    );
  }.property('service.nodeManagersCountActive', 'service.nodeManagersCountLost',
      'service.nodeManagersCountUnhealthy', 'service.nodeManagersCountRebooted', 'service.nodeManagersCountDecommissioned'),

  containers: function () {
    var allocated = this.get('service.containersAllocated');
    var pending = this.get('service.containersPending');
    var reserved = this.get('service.containersReserved');
    return this.t('dashboard.services.yarn.containers.msg').format(
      this.formatUnavailable(allocated),
      this.formatUnavailable(pending),
      this.formatUnavailable(reserved)
    );
  }.property('service.containersAllocated', 'service.containersPending', 'service.containersReserved'),

  apps: function () {
    var appsSubmitted = this.get('service.appsSubmitted');
    var appsRunning = this.get('service.appsRunning');
    var appsPending = this.get('service.appsPending');
    var appsCompleted = this.get('service.appsCompleted');
    var appsKilled = this.get('service.appsKilled');
    var appsFailed = this.get('service.appsFailed');
    return this.t('dashboard.services.yarn.apps.msg').format(
      this.formatUnavailable(appsSubmitted),
      this.formatUnavailable(appsRunning),
      this.formatUnavailable(appsPending),
      this.formatUnavailable(appsCompleted),
      this.formatUnavailable(appsKilled),
      this.formatUnavailable(appsFailed));
  }.property('service.appsSubmitted', 'service.appsRunning', 'service.appsPending', 'service.appsCompleted', 'service.appsKilled', 'service.appsFailed'),

  memory: function () {
    return Em.I18n.t('dashboard.services.yarn.memory.msg').format(
        numberUtils.bytesToSize(this.get('service.allocatedMemory'), 1, 'parseFloat', 1024 * 1024),
        numberUtils.bytesToSize(this.get('service.reservedMemory'), 1, 'parseFloat', 1024 * 1024),
        numberUtils.bytesToSize(this.get('service.availableMemory'), 1, 'parseFloat', 1024 * 1024));
  }.property('service.allocatedMemory', 'service.reservedMemory', 'service.availableMemory'),

  queues: function() {
    return Em.I18n.t('dashboard.services.yarn.queues.msg').format(this.formatUnavailable(this.get('service.queuesCount')));
  }.property('service.queuesCount'),

  didInsertElement: function(){
    $("[rel='queue-tooltip']").tooltip({html: true, placement: "right"});
  }

});


text:
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, UndecidableInstances #-}

{- |
Copyright    : 2007 Eric Kidd
License      : BSD3
Stability    : experimental
Portability  : non-portable (multi-parameter type classes, undecidable instances)

The 'MaybeT' monad.  See
<http://www.haskell.org/haskellwiki/New_monads/MaybeT> for more widely-used
version.  Our 'Functor' instance and our implementation of '>>=' are
borrowed from there.

[Computation type:] Computations which may fail or return nothing.

[Binding strategy:] Failure returns the value 'Nothing', bypassing any
bound functions which follow.  Success returns a value wrapped in 'Just'.

[Useful for:] Building computations from steps which may fail.  No error
information is returned.  (If error information is required, see
'Control.Monad.Error'.)

-}

module Control.Monad.Maybe (
  MaybeT(..),

  maybeT, fromMaybeT, fromMaybeTM

  -- * Limitations
  -- $Limitations

  -- * Example
  -- $MaybeExample
  ) where

import Control.Monad()
import Control.Monad.Trans()
import Control.Monad.Cont
import Control.Monad.Fix()
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Data.Maybe

-- | A monad transformer which adds Maybe semantics to an existing monad.
newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }

instance (Functor m) => Functor (MaybeT m) where
  fmap f = MaybeT . fmap (fmap f) . runMaybeT

instance (Monad m) => Monad (MaybeT m) where
  fail _ = MaybeT (return Nothing)
  return = lift . return
  x >>= f = MaybeT (runMaybeT x >>= maybe (return Nothing) (runMaybeT . f))

instance (Monad m) => MonadPlus (MaybeT m) where
  mzero = MaybeT (return Nothing)
  mplus x y = MaybeT $ do v <- runMaybeT x
                          case v of
                            Nothing -> runMaybeT y
                            Just _  -> return v

instance MonadTrans MaybeT where
  lift x = MaybeT (liftM Just x)

instance (MonadCont m) => MonadCont (MaybeT m) where
  -- Again, I hope this is correct.
  callCC f = MaybeT (callCC (\c -> runMaybeT (f (wrap c))))
    where wrap :: (Maybe a -> m (Maybe b)) -> a -> MaybeT m b
          wrap c = MaybeT . c . Just

-- MonadError: MonadError has fairly weird semantics when lifted by MaybeT,
-- so let's skip it for now.

instance (MonadIO m) => MonadIO (MaybeT m) where
  liftIO = lift . liftIO

instance (MonadFix m) => MonadFix (MaybeT m) where
  -- I hope this is correct.  At a minimum, it typechecks.
  mfix f = MaybeT (mfix (maybe (return Nothing) (runMaybeT . f)))

-- MonadList: Not implemented.

-- MonadPlus: Ambiguous.  See note in introduction.

-- Requires -fallow-undecidable-instances.
instance (MonadReader r m) => MonadReader r (MaybeT m) where
  ask = lift ask
  local f m = MaybeT (local f (runMaybeT m))

-- MonadRWS: Not implemented.

-- Taken from http://www.haskell.org/haskellwiki/New_monads/MaybeT .
instance MonadState s m => MonadState s (MaybeT m) where
  get = lift get
  put = lift . put

-- Requires -fallow-undecidable-instances.
instance (MonadWriter w m) => MonadWriter w (MaybeT m) where
  tell = lift . tell
  listen m = MaybeT (listen (runMaybeT m) >>= (return . liftMaybe))
    where liftMaybe (Nothing, _) = Nothing
          liftMaybe (Just x,  w) = Just (x,w)
  -- I'm not sure this is useful, but it's the best I can do:
  pass m = MaybeT (runMaybeT m >>= maybe (return Nothing)
                                         (liftM Just . pass . return))

-- | Lift a `Maybe` value to a `MaybeT`.
maybeT :: Monad m => Maybe a -> MaybeT m a
maybeT = MaybeT . return

-- | Remove the `MaybeT` using a default value.
fromMaybeT :: Monad m => a -> MaybeT m a -> m a
fromMaybeT x = liftM (fromMaybe x) . runMaybeT

-- | Remove the `MaybeT` using a monadic default value.
fromMaybeTM :: Monad m => m a -> MaybeT m a -> m a
fromMaybeTM x m = runMaybeT m >>= maybe x return

{- $Limitations

The instance @MonadPlus@ is not provided, because it has ambiguous
semantics.  It could refer to either

>instance MonadPlus m => MonadPlus (MaybeT m)

...lifting the semantics of an underlying 'MaybeT' monad, or

>instance MonadPlus (MaybeT m)

...with semantics similar to @MonadPlus Maybe@.

-}

{- $MaybeExample

Here is an example that shows how to use 'MaybeT' to propagate an
end-of-file condition in the IO monad.  In the example below, both
@maybeReadLine@ and @failIfQuit@ may cause a failure, which will propagate
out to @main@ without further intervention.

>import System.Console.Readline
>import Data.Maybe
>import Control.Monad
>import Control.Monad.Trans
>import Control.Monad.Maybe
>
>-- 'MaybeIO' is the type of computations which do IO, and which may fail.
>type MaybeIO = MaybeT IO
>
>-- 'readline' already has type 'String -> IO (Maybe String)'; we just need
>-- to wrap it.
>maybeReadLine :: String -> MaybeIO String
>maybeReadLine prompt = MaybeT (readline prompt)
>
>-- Fail if 'str' equals "quit".
>failIfQuit :: (Monad m) => String -> m ()
>failIfQuit str = when (str == "quit") (fail "Quitting")
>
>-- This task may fail in several places.  Try typing Control-D or "quit" at
>-- any prompt.
>concatTwoInputs :: MaybeIO ()
>concatTwoInputs = do
>  s1 <- maybeReadLine "String 1> "
>  failIfQuit s1
>  s2 <- maybeReadLine "String 2> "
>  failIfQuit s2
>  liftIO (putStrLn ("Concatenated: " ++ s1 ++ s2))
>
>-- Loop until failure.
>main :: IO ()
>main = do
>  result <- runMaybeT concatTwoInputs
>  if isNothing result
>    then putStrLn "Bye!"
>    else main

-}


text:
If you have found any issues that might have security implications, please send a report privately to pyrech@gmail.com

Do not report security reports publicly.


text:
package com.taptrack.tcmptappy.ui.modules.tappyblesearcher;

import com.taptrack.tcmptappy.tappy.ble.TappyBleDeviceDefinition;
import com.taptrack.tcmptappy.ui.mvp.Presenter;
import com.taptrack.tcmptappy.utils.TappyBleDeviceSelectedListener;

public interface TappyBleDeviceSearchPresenter extends Presenter<TappyBleSearchListVista>, TappyBleDeviceSelectedListener {
    public interface TappyBleSelectedListener {
        void onTappySelected(TappyBleDeviceDefinition tappy);
    }

    void requestClearTappyList();
    void requestStartScanning();
    void requestStopScanning();
    public void setTappySelectedListener(TappyBleSelectedListener listener);
    public void unregisterTappySelectedListener();
}


text:
package com.google.cloud.bigquery;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Test;

public class GoogleSheetsOptionsTest {

  private static final long SKIP_LEADING_ROWS = 42L;
  private static final String RANGE = "sheet1!A1:B20";
  private static final GoogleSheetsOptions GOOGLE_SHEETS_OPTIONS =
      GoogleSheetsOptions.newBuilder().setSkipLeadingRows(SKIP_LEADING_ROWS).build();
  private static final GoogleSheetsOptions GOOGLE_SHEETS_OPTIONS_RANGE =
      GoogleSheetsOptions.newBuilder()
          .setSkipLeadingRows(SKIP_LEADING_ROWS)
          .setRange(RANGE)
          .build();

  @Test
  public void testToBuilder() {
    compareGoogleSheetsOptions(GOOGLE_SHEETS_OPTIONS, GOOGLE_SHEETS_OPTIONS.toBuilder().build());
    GoogleSheetsOptions googleSheetsOptions =
        GOOGLE_SHEETS_OPTIONS.toBuilder().setSkipLeadingRows(123).build();
    assertThat(googleSheetsOptions.getSkipLeadingRows()).isEqualTo(123);
    googleSheetsOptions =
        googleSheetsOptions.toBuilder().setSkipLeadingRows(SKIP_LEADING_ROWS).build();
    compareGoogleSheetsOptions(GOOGLE_SHEETS_OPTIONS, googleSheetsOptions);
    compareGoogleSheetsOptions(
        GOOGLE_SHEETS_OPTIONS_RANGE, GOOGLE_SHEETS_OPTIONS_RANGE.toBuilder().build());
    GoogleSheetsOptions googleSheetsOptionsRange =
        GOOGLE_SHEETS_OPTIONS_RANGE
            .toBuilder()
            .setSkipLeadingRows(123)
            .setRange("sheet1!A1:A100")
            .build();
    assertThat(googleSheetsOptionsRange.getSkipLeadingRows()).isEqualTo(123);
    assertThat(googleSheetsOptionsRange.getRange()).isEqualTo("sheet1!A1:A100");
    googleSheetsOptionsRange =
        googleSheetsOptionsRange
            .toBuilder()
            .setSkipLeadingRows(SKIP_LEADING_ROWS)
            .setRange(RANGE)
            .build();
    compareGoogleSheetsOptions(GOOGLE_SHEETS_OPTIONS_RANGE, googleSheetsOptionsRange);
  }

  @Test
  public void testToBuilderIncomplete() {
    GoogleSheetsOptions googleSheetsOptions = GoogleSheetsOptions.newBuilder().build();
    assertThat(googleSheetsOptions.toBuilder().build()).isEqualTo(googleSheetsOptions);
  }

  @Test
  public void testBuilder() {
    assertThat(GOOGLE_SHEETS_OPTIONS.getType()).isEqualTo(FormatOptions.GOOGLE_SHEETS);
    assertThat(GOOGLE_SHEETS_OPTIONS.getSkipLeadingRows()).isEqualTo(SKIP_LEADING_ROWS);
    assertThat(GOOGLE_SHEETS_OPTIONS_RANGE.getType()).isEqualTo(FormatOptions.GOOGLE_SHEETS);
    assertThat(GOOGLE_SHEETS_OPTIONS_RANGE.getSkipLeadingRows()).isEqualTo(SKIP_LEADING_ROWS);
    assertThat(GOOGLE_SHEETS_OPTIONS_RANGE.getRange()).isEqualTo(RANGE);
  }

  @Test
  public void testToAndFromPb() {
    compareGoogleSheetsOptions(
        GOOGLE_SHEETS_OPTIONS, GoogleSheetsOptions.fromPb(GOOGLE_SHEETS_OPTIONS.toPb()));
    GoogleSheetsOptions googleSheetsOptions = GoogleSheetsOptions.newBuilder().build();
    compareGoogleSheetsOptions(
        googleSheetsOptions, GoogleSheetsOptions.fromPb(googleSheetsOptions.toPb()));
    compareGoogleSheetsOptions(
        GOOGLE_SHEETS_OPTIONS_RANGE,
        GoogleSheetsOptions.fromPb(GOOGLE_SHEETS_OPTIONS_RANGE.toPb()));
    GoogleSheetsOptions googleSheetsOptionsRange = GoogleSheetsOptions.newBuilder().build();
    compareGoogleSheetsOptions(
        googleSheetsOptionsRange, GoogleSheetsOptions.fromPb(googleSheetsOptionsRange.toPb()));
  }

  private void compareGoogleSheetsOptions(GoogleSheetsOptions expected, GoogleSheetsOptions value) {
    assertThat(value).isEqualTo(expected);
    assertThat(value.getSkipLeadingRows()).isEqualTo(expected.getSkipLeadingRows());
    assertThat(value.getRange()).isEqualTo(expected.getRange());
  }
}


text:
from __future__ import unicode_literals

from django.db import models

from main.helpers import Redirect_Link as RL
from main.constants import SUPPORT_VALUES_MAX_LENGTH, ITEM_NAME_MAX_LENGTH

class Collections(models.Model):
    """Lista istniejących kolekcji."""
    class Meta():
        ordering = ["name"]
    name = models.CharField(max_length=64)
    description = models.CharField(max_length=255, blank=True, default='')

    def __unicode__(self):
        return self.name

    def make_link(self):
        return RL(url="collection_view",
                  title=self.name,
                  collection=self.id)

    def get_collections_support_tables(self):
        return Support_Tables.objects.filter(
            id__in=Additional_Attributes.objects.filter(
                collection=self
            ).values_list("support_table", flat=True).distinct()
        )

    def update_whole_collection(self):
        collection_items = Items.objects.filter(collection=self)
        collection_attributes = Additional_Attributes.objects.filter(collection=self)
        attributes_to_create = []
        for item in collection_items:
            item.set_additional_attributes_as_dict()
            for attr in collection_attributes:
                if attr not in item.additional_attributes.keys():
                    attributes_to_create.append(Attributes_Values(item=item,
                                                                  additional_attribute=attr,
                                                                  ))
        Attributes_Values.objects.bulk_create(attributes_to_create)

class Support_Tables(models.Model):
    """Lista list pomocniczych"""
    class Meta():
        ordering = ["name"]

    name = models.CharField(max_length=32, unique=True)

    def __unicode__(self):
        return self.name

    def get_values(self):
        return Support_Values.objects.filter(support_table=self)

    def set_values(self):
        self.values = list(self.get_values())

    def make_link(self):
        return RL(url="list_edit",
                  title=self.name,
                  supp_list=self.id)

class Support_Values(models.Model):
    """Wartości list pomocniczych"""
    class Meta():
        ordering = ["value"]

    value = models.CharField(max_length=SUPPORT_VALUES_MAX_LENGTH)
    support_table = models.ForeignKey(Support_Tables)

    def __unicode__(self):
        return self.value

class Attribute_Types(models.Model):
    """Typy atrybutów (liczba, tekst, itp). STATYCZNA"""
    name = models.CharField(max_length=16)
    field_name = models.CharField(max_length=16)
    short_name = models.CharField(max_length=3)

    def __unicode__(self):
        return self.name

class Additional_Attributes(models.Model):
    """Dodatkowe atrybuty kolekcji"""
    name = models.CharField(max_length=64)
    attribute_type = models.ForeignKey(Attribute_Types)
    collection = models.ForeignKey(Collections)
    support_table = models.ForeignKey(Support_Tables, null=True)

    def __unicode__(self):
        return self.name

class Amount_Types(models.Model):
    """Typy ilości (jednostki, kg, cm, itp). STATYCZNA"""
    name = models.CharField(max_length=16)
    short = models.CharField(max_length=4, blank=True)

    def __unicode__(self):
        return self.name

class Items(models.Model):
    """Spis elementów kolekcji"""
    class Meta():
        ordering = ["name"]

    name = models.CharField(max_length=ITEM_NAME_MAX_LENGTH)
    amount_type = models.ForeignKey(Amount_Types)
    collection = models.ForeignKey(Collections)
    amount = models.IntegerField(default=0)

    def make_link(self):
        return RL(url="item_view",
                  title=self.name,
                  collection=self.collection.id,
                  item=self.id)

    def get_all_attributes_with_values(self):
        return Attributes_Values.objects.filter(item=self)

    def set_additional_attributes_as_dict(self):
        self.additional_attributes = {}
        for each in self.get_all_attributes_with_values():
            if each.additional_attribute.attribute_type.field_name == "ChoiceField":
                self.additional_attributes[each.additional_attribute] = each.support_value
            else:
                self.additional_attributes[each.additional_attribute] = each.value

class Attributes_Values(models.Model):
    """Spis wartości atrybutów elementów kolekcji - Przedmiot(atrybut: wartość)"""
    item = models.ForeignKey(Items)
    additional_attribute = models.ForeignKey(Additional_Attributes)
    value = models.TextField(max_length=1024, blank=True, null=True, default='')
    support_value = models.ForeignKey(Support_Values, null=True, default=None)

    def __unicode__(self):
        return str(self.additional_attribute) + ": " + str(self.value)


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

		<item value="222" key="DIALOG_Y_ORIGIN"/>
		<item value="217" key="DIALOG_X_ORIGIN"/>

		<item value="false" key="WizardProjectsImportPage.STORE_ARCHIVE_SELECTED"/>
		<item value="false" key="WizardProjectsImportPage.STORE_COPY_PROJECT_ID"/>

		<list key="ENABLED_TRANSFERS">
		</list>


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

<!--
** Copyright 2017, mookie
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
-->

<resources>

    <!-- Icon colors -->
    <color name="icon_gray">#323232</color>
    <color name="icon_medium_gray">#353535</color>
    <color name="icon_light_gray">#5d5e5e</color>
    <color name="icon_dark_gray">#282828</color>
    <color name="icon_yellow">#edae20</color>
    <color name="icon_purple">#6d3390</color>
    <color name="icon_dark_blue">#424299</color>
    <color name="icon_light_blue">#206daf</color>
    <color name="icon_green">#109a59</color>
    <color name="icon_red">#b22b2b</color>
    <color name="icon_light_pink">#e24d55</color>
    <color name="icon_dark_pink">#a51e57</color>
    <color name="icon_orange">#f68c1f</color>

    <!-- Background colors -->
    <color name="app_bg">@color/icon_medium_gray</color>
    <color name="wall_bg">@color/icon_medium_gray</color>

    <!-- Colors for launcher apply view -->
    <color name="button_pressed_color">#99555555</color>
    <color name="apply_launcher_text_color">#ffffff</color>

    <!-- Standard colors -->
    <color name="black">#000000</color>
    <color name="white">#ffffff</color>
    <color name="white_50">#AAFFFFFF</color>
    <color name="black_50">#AA000000</color>
    <color name="gray">#efefef</color>
    <color name="gray_dark">#333333</color>

    <!-- Utility colors -->
    <color name="transparent">#00000000</color>
    <color name="transparent_black">#55000000</color>

</resources>


text:
#include "event2/event-config.h"

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif

#include <sys/types.h>
#ifndef WIN32
#include <sys/socket.h>
#endif
#ifdef _EVENT_HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/queue.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <errno.h>
#include <signal.h>
#include <string.h>

#include <sys/queue.h>

#include "event2/event.h"
#include "event2/event_struct.h"
#include "event2/rpc.h"
#include "event2/rpc_struct.h"
#include "evrpc-internal.h"
#include "event2/http.h"
#include "event2/buffer.h"
#include "event2/tag.h"
#include "event2/http_struct.h"
#include "event2/http_compat.h"
#include "event2/util.h"
#include "util-internal.h"
#include "log-internal.h"
#include "mm-internal.h"

struct evrpc_base *
evrpc_init(struct evhttp *http_server)
{
	struct evrpc_base* base = mm_calloc(1, sizeof(struct evrpc_base));
	if (base == NULL)
		return (NULL);

	/* we rely on the tagging sub system */
	evtag_init();

	TAILQ_INIT(&base->registered_rpcs);
	TAILQ_INIT(&base->input_hooks);
	TAILQ_INIT(&base->output_hooks);

	TAILQ_INIT(&base->paused_requests);

	base->http_server = http_server;

	return (base);
}

void
evrpc_free(struct evrpc_base *base)
{
	struct evrpc *rpc;
	struct evrpc_hook *hook;
	struct evrpc_hook_ctx *pause;
	int r;

	while ((rpc = TAILQ_FIRST(&base->registered_rpcs)) != NULL) {
		r = evrpc_unregister_rpc(base, rpc->uri);
		EVUTIL_ASSERT(r == 0);
	}
	while ((pause = TAILQ_FIRST(&base->paused_requests)) != NULL) {
		TAILQ_REMOVE(&base->paused_requests, pause, next);
		mm_free(pause);
	}
	while ((hook = TAILQ_FIRST(&base->input_hooks)) != NULL) {
		r = evrpc_remove_hook(base, EVRPC_INPUT, hook);
		EVUTIL_ASSERT(r);
	}
	while ((hook = TAILQ_FIRST(&base->output_hooks)) != NULL) {
		r = evrpc_remove_hook(base, EVRPC_OUTPUT, hook);
		EVUTIL_ASSERT(r);
	}
	mm_free(base);
}

void *
evrpc_add_hook(void *vbase,
    enum EVRPC_HOOK_TYPE hook_type,
    int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
    void *cb_arg)
{
	struct _evrpc_hooks *base = vbase;
	struct evrpc_hook_list *head = NULL;
	struct evrpc_hook *hook = NULL;
	switch (hook_type) {
	case EVRPC_INPUT:
		head = &base->in_hooks;
		break;
	case EVRPC_OUTPUT:
		head = &base->out_hooks;
		break;
	default:
		EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
	}

	hook = mm_calloc(1, sizeof(struct evrpc_hook));
	EVUTIL_ASSERT(hook != NULL);

	hook->process = cb;
	hook->process_arg = cb_arg;
	TAILQ_INSERT_TAIL(head, hook, next);

	return (hook);
}

static int
evrpc_remove_hook_internal(struct evrpc_hook_list *head, void *handle)
{
	struct evrpc_hook *hook = NULL;
	TAILQ_FOREACH(hook, head, next) {
		if (hook == handle) {
			TAILQ_REMOVE(head, hook, next);
			mm_free(hook);
			return (1);
		}
	}

	return (0);
}

/*
 * remove the hook specified by the handle
 */

int
evrpc_remove_hook(void *vbase, enum EVRPC_HOOK_TYPE hook_type, void *handle)
{
	struct _evrpc_hooks *base = vbase;
	struct evrpc_hook_list *head = NULL;
	switch (hook_type) {
	case EVRPC_INPUT:
		head = &base->in_hooks;
		break;
	case EVRPC_OUTPUT:
		head = &base->out_hooks;
		break;
	default:
		EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
	}

	return (evrpc_remove_hook_internal(head, handle));
}

static int
evrpc_process_hooks(struct evrpc_hook_list *head, void *ctx,
    struct evhttp_request *req, struct evbuffer *evbuf)
{
	struct evrpc_hook *hook;
	TAILQ_FOREACH(hook, head, next) {
		int res = hook->process(ctx, req, evbuf, hook->process_arg);
		if (res != EVRPC_CONTINUE)
			return (res);
	}

	return (EVRPC_CONTINUE);
}

static void evrpc_pool_schedule(struct evrpc_pool *pool);
static void evrpc_request_cb(struct evhttp_request *, void *);

/*
 * Registers a new RPC with the HTTP server.   The evrpc object is expected
 * to have been filled in via the EVRPC_REGISTER_OBJECT macro which in turn
 * calls this function.
 */

static char *
evrpc_construct_uri(const char *uri)
{
	char *constructed_uri;
	size_t constructed_uri_len;

	constructed_uri_len = strlen(EVRPC_URI_PREFIX) + strlen(uri) + 1;
	if ((constructed_uri = mm_malloc(constructed_uri_len)) == NULL)
		event_err(1, "%s: failed to register rpc at %s",
		    __func__, uri);
	memcpy(constructed_uri, EVRPC_URI_PREFIX, strlen(EVRPC_URI_PREFIX));
	memcpy(constructed_uri + strlen(EVRPC_URI_PREFIX), uri, strlen(uri));
	constructed_uri[constructed_uri_len - 1] = '\0';

	return (constructed_uri);
}

int
evrpc_register_rpc(struct evrpc_base *base, struct evrpc *rpc,
    void (*cb)(struct evrpc_req_generic *, void *), void *cb_arg)
{
	char *constructed_uri = evrpc_construct_uri(rpc->uri);

	rpc->base = base;
	rpc->cb = cb;
	rpc->cb_arg = cb_arg;

	TAILQ_INSERT_TAIL(&base->registered_rpcs, rpc, next);

	evhttp_set_cb(base->http_server,
	    constructed_uri,
	    evrpc_request_cb,
	    rpc);

	mm_free(constructed_uri);

	return (0);
}

int
evrpc_unregister_rpc(struct evrpc_base *base, const char *name)
{
	char *registered_uri = NULL;
	struct evrpc *rpc;
	int r;

	/* find the right rpc; linear search might be slow */
	TAILQ_FOREACH(rpc, &base->registered_rpcs, next) {
		if (strcmp(rpc->uri, name) == 0)
			break;
	}
	if (rpc == NULL) {
		/* We did not find an RPC with this name */
		return (-1);
	}
	TAILQ_REMOVE(&base->registered_rpcs, rpc, next);

	registered_uri = evrpc_construct_uri(name);

	/* remove the http server callback */
	r = evhttp_del_cb(base->http_server, registered_uri);
	EVUTIL_ASSERT(r == 0);

	mm_free(registered_uri);

	mm_free((char *)rpc->uri);
	mm_free(rpc);
	return (0);
}

static int evrpc_pause_request(void *vbase, void *ctx,
    void (*cb)(void *, enum EVRPC_HOOK_RESULT));
static void evrpc_request_cb_closure(void *, enum EVRPC_HOOK_RESULT);

static void
evrpc_request_cb(struct evhttp_request *req, void *arg)
{
	struct evrpc *rpc = arg;
	struct evrpc_req_generic *rpc_state = NULL;

	/* let's verify the outside parameters */
	if (req->type != EVHTTP_REQ_POST ||
	    evbuffer_get_length(req->input_buffer) <= 0)
		goto error;

	rpc_state = mm_calloc(1, sizeof(struct evrpc_req_generic));
	if (rpc_state == NULL)
		goto error;
	rpc_state->rpc = rpc;
	rpc_state->http_req = req;
	rpc_state->rpc_data = NULL;

	if (TAILQ_FIRST(&rpc->base->input_hooks) != NULL) {
		int hook_res;

		evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);

		/*
		 * allow hooks to modify the outgoing request
		 */
		hook_res = evrpc_process_hooks(&rpc->base->input_hooks,
		    rpc_state, req, req->input_buffer);
		switch (hook_res) {
		case EVRPC_TERMINATE:
			goto error;
		case EVRPC_PAUSE:
			evrpc_pause_request(rpc->base, rpc_state,
			    evrpc_request_cb_closure);
			return;
		case EVRPC_CONTINUE:
			break;
		default:
			EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
			    hook_res == EVRPC_CONTINUE ||
			    hook_res == EVRPC_PAUSE);
		}
	}

	evrpc_request_cb_closure(rpc_state, EVRPC_CONTINUE);
	return;

error:
	if (rpc_state != NULL)
		evrpc_reqstate_free(rpc_state);
	evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
	return;
}

static void
evrpc_request_cb_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
{
	struct evrpc_req_generic *rpc_state = arg;
	struct evrpc *rpc;
	struct evhttp_request *req;

	EVUTIL_ASSERT(rpc_state);
	rpc = rpc_state->rpc;
	req = rpc_state->http_req;

	if (hook_res == EVRPC_TERMINATE)
		goto error;

	/* let's check that we can parse the request */
	rpc_state->request = rpc->request_new(rpc->request_new_arg);
	if (rpc_state->request == NULL)
		goto error;

	if (rpc->request_unmarshal(
		    rpc_state->request, req->input_buffer) == -1) {
		/* we failed to parse the request; that's a bummer */
		goto error;
	}

	/* at this point, we have a well formed request, prepare the reply */

	rpc_state->reply = rpc->reply_new(rpc->reply_new_arg);
	if (rpc_state->reply == NULL)
		goto error;

	/* give the rpc to the user; they can deal with it */
	rpc->cb(rpc_state, rpc->cb_arg);

	return;

error:
	if (rpc_state != NULL)
		evrpc_reqstate_free(rpc_state);
	evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
	return;
}

void
evrpc_reqstate_free(struct evrpc_req_generic* rpc_state)
{
	struct evrpc *rpc;
	EVUTIL_ASSERT(rpc_state != NULL);
	rpc = rpc_state->rpc;

	/* clean up all memory */
	if (rpc_state->hook_meta != NULL)
		evrpc_hook_context_free(rpc_state->hook_meta);
	if (rpc_state->request != NULL)
		rpc->request_free(rpc_state->request);
	if (rpc_state->reply != NULL)
		rpc->reply_free(rpc_state->reply);
	if (rpc_state->rpc_data != NULL)
		evbuffer_free(rpc_state->rpc_data);
	mm_free(rpc_state);
}

static void
evrpc_request_done_closure(void *, enum EVRPC_HOOK_RESULT);

void
evrpc_request_done(struct evrpc_req_generic *rpc_state)
{
	struct evhttp_request *req;
	struct evrpc *rpc;

	EVUTIL_ASSERT(rpc_state);

	req = rpc_state->http_req;
	rpc = rpc_state->rpc;

	if (rpc->reply_complete(rpc_state->reply) == -1) {
		/* the reply was not completely filled in.  error out */
		goto error;
	}

	if ((rpc_state->rpc_data = evbuffer_new()) == NULL) {
		/* out of memory */
		goto error;
	}

	/* serialize the reply */
	rpc->reply_marshal(rpc_state->rpc_data, rpc_state->reply);

	if (TAILQ_FIRST(&rpc->base->output_hooks) != NULL) {
		int hook_res;

		evrpc_hook_associate_meta(&rpc_state->hook_meta, req->evcon);

		/* do hook based tweaks to the request */
		hook_res = evrpc_process_hooks(&rpc->base->output_hooks,
		    rpc_state, req, rpc_state->rpc_data);
		switch (hook_res) {
		case EVRPC_TERMINATE:
			goto error;
		case EVRPC_PAUSE:
			if (evrpc_pause_request(rpc->base, rpc_state,
				evrpc_request_done_closure) == -1)
				goto error;
			return;
		case EVRPC_CONTINUE:
			break;
		default:
			EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
			    hook_res == EVRPC_CONTINUE ||
			    hook_res == EVRPC_PAUSE);
		}
	}

	evrpc_request_done_closure(rpc_state, EVRPC_CONTINUE);
	return;

error:
	if (rpc_state != NULL)
		evrpc_reqstate_free(rpc_state);
	evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
	return;
}

void *
evrpc_get_request(struct evrpc_req_generic *req)
{
	return req->request;
}

void *
evrpc_get_reply(struct evrpc_req_generic *req)
{
	return req->reply;
}

static void
evrpc_request_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
{
	struct evrpc_req_generic *rpc_state = arg;
	struct evhttp_request *req;
	EVUTIL_ASSERT(rpc_state);
	req = rpc_state->http_req;

	if (hook_res == EVRPC_TERMINATE)
		goto error;

	/* on success, we are going to transmit marshaled binary data */
	if (evhttp_find_header(req->output_headers, "Content-Type") == NULL) {
		evhttp_add_header(req->output_headers,
		    "Content-Type", "application/octet-stream");
	}
	evhttp_send_reply(req, HTTP_OK, "OK", rpc_state->rpc_data);

	evrpc_reqstate_free(rpc_state);

	return;

error:
	if (rpc_state != NULL)
		evrpc_reqstate_free(rpc_state);
	evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
	return;
}

/* Client implementation of RPC site */

static int evrpc_schedule_request(struct evhttp_connection *connection,
    struct evrpc_request_wrapper *ctx);

struct evrpc_pool *
evrpc_pool_new(struct event_base *base)
{
	struct evrpc_pool *pool = mm_calloc(1, sizeof(struct evrpc_pool));
	if (pool == NULL)
		return (NULL);

	TAILQ_INIT(&pool->connections);
	TAILQ_INIT(&pool->requests);

	TAILQ_INIT(&pool->paused_requests);

	TAILQ_INIT(&pool->input_hooks);
	TAILQ_INIT(&pool->output_hooks);

	pool->base = base;
	pool->timeout = -1;

	return (pool);
}

static void
evrpc_request_wrapper_free(struct evrpc_request_wrapper *request)
{
	if (request->hook_meta != NULL)
		evrpc_hook_context_free(request->hook_meta);
	mm_free(request->name);
	mm_free(request);
}

void
evrpc_pool_free(struct evrpc_pool *pool)
{
	struct evhttp_connection *connection;
	struct evrpc_request_wrapper *request;
	struct evrpc_hook_ctx *pause;
	struct evrpc_hook *hook;
	int r;

	while ((request = TAILQ_FIRST(&pool->requests)) != NULL) {
		TAILQ_REMOVE(&pool->requests, request, next);
		evrpc_request_wrapper_free(request);
	}

	while ((pause = TAILQ_FIRST(&pool->paused_requests)) != NULL) {
		TAILQ_REMOVE(&pool->paused_requests, pause, next);
		mm_free(pause);
	}

	while ((connection = TAILQ_FIRST(&pool->connections)) != NULL) {
		TAILQ_REMOVE(&pool->connections, connection, next);
		evhttp_connection_free(connection);
	}

	while ((hook = TAILQ_FIRST(&pool->input_hooks)) != NULL) {
		r = evrpc_remove_hook(pool, EVRPC_INPUT, hook);
		EVUTIL_ASSERT(r);
	}

	while ((hook = TAILQ_FIRST(&pool->output_hooks)) != NULL) {
		r = evrpc_remove_hook(pool, EVRPC_OUTPUT, hook);
		EVUTIL_ASSERT(r);
	}

	mm_free(pool);
}

/*
 * Add a connection to the RPC pool.   A request scheduled on the pool
 * may use any available connection.
 */

void
evrpc_pool_add_connection(struct evrpc_pool *pool,
    struct evhttp_connection *connection)
{
	EVUTIL_ASSERT(connection->http_server == NULL);
	TAILQ_INSERT_TAIL(&pool->connections, connection, next);

	/*
	 * associate an event base with this connection
	 */
	if (pool->base != NULL)
		evhttp_connection_set_base(connection, pool->base);

	/*
	 * unless a timeout was specifically set for a connection,
	 * the connection inherits the timeout from the pool.
	 */
	if (connection->timeout == -1)
		connection->timeout = pool->timeout;

	/*
	 * if we have any requests pending, schedule them with the new
	 * connections.
	 */

	if (TAILQ_FIRST(&pool->requests) != NULL) {
		struct evrpc_request_wrapper *request =
		    TAILQ_FIRST(&pool->requests);
		TAILQ_REMOVE(&pool->requests, request, next);
		evrpc_schedule_request(connection, request);
	}
}

void
evrpc_pool_remove_connection(struct evrpc_pool *pool,
    struct evhttp_connection *connection)
{
	TAILQ_REMOVE(&pool->connections, connection, next);
}

void
evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs)
{
	struct evhttp_connection *evcon;
	TAILQ_FOREACH(evcon, &pool->connections, next) {
		evcon->timeout = timeout_in_secs;
	}
	pool->timeout = timeout_in_secs;
}

static void evrpc_reply_done(struct evhttp_request *, void *);
static void evrpc_request_timeout(evutil_socket_t, short, void *);

/*
 * Finds a connection object associated with the pool that is currently
 * idle and can be used to make a request.
 */
static struct evhttp_connection *
evrpc_pool_find_connection(struct evrpc_pool *pool)
{
	struct evhttp_connection *connection;
	TAILQ_FOREACH(connection, &pool->connections, next) {
		if (TAILQ_FIRST(&connection->requests) == NULL)
			return (connection);
	}

	return (NULL);
}

/*
 * Prototypes responsible for evrpc scheduling and hooking
 */

static void evrpc_schedule_request_closure(void *ctx, enum EVRPC_HOOK_RESULT);

/*
 * We assume that the ctx is no longer queued on the pool.
 */
static int
evrpc_schedule_request(struct evhttp_connection *connection,
    struct evrpc_request_wrapper *ctx)
{
	struct evhttp_request *req = NULL;
	struct evrpc_pool *pool = ctx->pool;
	struct evrpc_status status;

	if ((req = evhttp_request_new(evrpc_reply_done, ctx)) == NULL)
		goto error;

	/* serialize the request data into the output buffer */
	ctx->request_marshal(req->output_buffer, ctx->request);

	/* we need to know the connection that we might have to abort */
	ctx->evcon = connection;

	/* if we get paused we also need to know the request */
	ctx->req = req;

	if (TAILQ_FIRST(&pool->output_hooks) != NULL) {
		int hook_res;

		evrpc_hook_associate_meta(&ctx->hook_meta, connection);

		/* apply hooks to the outgoing request */
		hook_res = evrpc_process_hooks(&pool->output_hooks,
		    ctx, req, req->output_buffer);

		switch (hook_res) {
		case EVRPC_TERMINATE:
			goto error;
		case EVRPC_PAUSE:
			/* we need to be explicitly resumed */
			if (evrpc_pause_request(pool, ctx,
				evrpc_schedule_request_closure) == -1)
				goto error;
			return (0);
		case EVRPC_CONTINUE:
			/* we can just continue */
			break;
		default:
			EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
			    hook_res == EVRPC_CONTINUE ||
			    hook_res == EVRPC_PAUSE);
		}
	}

	evrpc_schedule_request_closure(ctx, EVRPC_CONTINUE);
	return (0);

error:
	memset(&status, 0, sizeof(status));
	status.error = EVRPC_STATUS_ERR_UNSTARTED;
	(*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
	evrpc_request_wrapper_free(ctx);
	return (-1);
}

static void
evrpc_schedule_request_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
{
	struct evrpc_request_wrapper *ctx = arg;
	struct evhttp_connection *connection = ctx->evcon;
	struct evhttp_request *req = ctx->req;
	struct evrpc_pool *pool = ctx->pool;
	struct evrpc_status status;
	char *uri = NULL;
	int res = 0;

	if (hook_res == EVRPC_TERMINATE)
		goto error;

	uri = evrpc_construct_uri(ctx->name);
	if (uri == NULL)
		goto error;

	if (pool->timeout > 0) {
		/*
		 * a timeout after which the whole rpc is going to be aborted.
		 */
		struct timeval tv;
		evutil_timerclear(&tv);
		tv.tv_sec = pool->timeout;
		evtimer_add(&ctx->ev_timeout, &tv);
	}

	/* start the request over the connection */
	res = evhttp_make_request(connection, req, EVHTTP_REQ_POST, uri);
	mm_free(uri);

	if (res == -1)
		goto error;

	return;

error:
	memset(&status, 0, sizeof(status));
	status.error = EVRPC_STATUS_ERR_UNSTARTED;
	(*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
	evrpc_request_wrapper_free(ctx);
}

/* we just queue the paused request on the pool under the req object */
static int
evrpc_pause_request(void *vbase, void *ctx,
    void (*cb)(void *, enum EVRPC_HOOK_RESULT))
{
	struct _evrpc_hooks *base = vbase;
	struct evrpc_hook_ctx *pause = mm_malloc(sizeof(*pause));
	if (pause == NULL)
		return (-1);

	pause->ctx = ctx;
	pause->cb = cb;

	TAILQ_INSERT_TAIL(&base->pause_requests, pause, next);
	return (0);
}

int
evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res)
{
	struct _evrpc_hooks *base = vbase;
	struct evrpc_pause_list *head = &base->pause_requests;
	struct evrpc_hook_ctx *pause;

	TAILQ_FOREACH(pause, head, next) {
		if (pause->ctx == ctx)
			break;
	}

	if (pause == NULL)
		return (-1);

	(*pause->cb)(pause->ctx, res);
	TAILQ_REMOVE(head, pause, next);
	mm_free(pause);
	return (0);
}

int
evrpc_make_request(struct evrpc_request_wrapper *ctx)
{
	struct evrpc_pool *pool = ctx->pool;

	/* initialize the event structure for this rpc */
	evtimer_assign(&ctx->ev_timeout, pool->base, evrpc_request_timeout, ctx);

	/* we better have some available connections on the pool */
	EVUTIL_ASSERT(TAILQ_FIRST(&pool->connections) != NULL);

	/*
	 * if no connection is available, we queue the request on the pool,
	 * the next time a connection is empty, the rpc will be send on that.
	 */
	TAILQ_INSERT_TAIL(&pool->requests, ctx, next);

	evrpc_pool_schedule(pool);

	return (0);
}

struct evrpc_request_wrapper *
evrpc_make_request_ctx(
	struct evrpc_pool *pool, void *request, void *reply,
	const char *rpcname,
	void (*req_marshal)(struct evbuffer*, void *),
	void (*rpl_clear)(void *),
	int (*rpl_unmarshal)(void *, struct evbuffer *),
	void (*cb)(struct evrpc_status *, void *, void *, void *),
	void *cbarg)
{
	struct evrpc_request_wrapper *ctx = (struct evrpc_request_wrapper *)
	    mm_malloc(sizeof(struct evrpc_request_wrapper));
	if (ctx == NULL)
		return (NULL);

	ctx->pool = pool;
	ctx->hook_meta = NULL;
	ctx->evcon = NULL;
	ctx->name = mm_strdup(rpcname);
	if (ctx->name == NULL) {
		mm_free(ctx);
		return (NULL);
	}
	ctx->cb = cb;
	ctx->cb_arg = cbarg;
	ctx->request = request;
	ctx->reply = reply;
	ctx->request_marshal = req_marshal;
	ctx->reply_clear = rpl_clear;
	ctx->reply_unmarshal = rpl_unmarshal;

	return (ctx);
}

static void
evrpc_reply_done_closure(void *, enum EVRPC_HOOK_RESULT);

static void
evrpc_reply_done(struct evhttp_request *req, void *arg)
{
	struct evrpc_request_wrapper *ctx = arg;
	struct evrpc_pool *pool = ctx->pool;
	int hook_res = EVRPC_CONTINUE;

	/* cancel any timeout we might have scheduled */
	event_del(&ctx->ev_timeout);

	ctx->req = req;

	/* we need to get the reply now */
	if (req == NULL) {
		evrpc_reply_done_closure(ctx, EVRPC_CONTINUE);
		return;
	}

	if (TAILQ_FIRST(&pool->input_hooks) != NULL) {
		evrpc_hook_associate_meta(&ctx->hook_meta, ctx->evcon);

		/* apply hooks to the incoming request */
		hook_res = evrpc_process_hooks(&pool->input_hooks,
		    ctx, req, req->input_buffer);

		switch (hook_res) {
		case EVRPC_TERMINATE:
		case EVRPC_CONTINUE:
			break;
		case EVRPC_PAUSE:
			/*
			 * if we get paused we also need to know the
			 * request.  unfortunately, the underlying
			 * layer is going to free it.  we need to
			 * request ownership explicitly
			 */
			if (req != NULL)
				evhttp_request_own(req);

			evrpc_pause_request(pool, ctx,
			    evrpc_reply_done_closure);
			return;
		default:
			EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
			    hook_res == EVRPC_CONTINUE ||
			    hook_res == EVRPC_PAUSE);
		}
	}

	evrpc_reply_done_closure(ctx, hook_res);

	/* http request is being freed by underlying layer */
}

static void
evrpc_reply_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
{
	struct evrpc_request_wrapper *ctx = arg;
	struct evhttp_request *req = ctx->req;
	struct evrpc_pool *pool = ctx->pool;
	struct evrpc_status status;
	int res = -1;

	memset(&status, 0, sizeof(status));
	status.http_req = req;

	/* we need to get the reply now */
	if (req == NULL) {
		status.error = EVRPC_STATUS_ERR_TIMEOUT;
	} else if (hook_res == EVRPC_TERMINATE) {
		status.error = EVRPC_STATUS_ERR_HOOKABORTED;
	} else {
		res = ctx->reply_unmarshal(ctx->reply, req->input_buffer);
		if (res == -1)
			status.error = EVRPC_STATUS_ERR_BADPAYLOAD;
	}

	if (res == -1) {
		/* clear everything that we might have written previously */
		ctx->reply_clear(ctx->reply);
	}

	(*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);

	evrpc_request_wrapper_free(ctx);

	/* the http layer owned the original request structure, but if we
	 * got paused, we asked for ownership and need to free it here. */
	if (req != NULL && evhttp_request_is_owned(req))
		evhttp_request_free(req);

	/* see if we can schedule another request */
	evrpc_pool_schedule(pool);
}

static void
evrpc_pool_schedule(struct evrpc_pool *pool)
{
	struct evrpc_request_wrapper *ctx = TAILQ_FIRST(&pool->requests);
	struct evhttp_connection *evcon;

	/* if no requests are pending, we have no work */
	if (ctx == NULL)
		return;

	if ((evcon = evrpc_pool_find_connection(pool)) != NULL) {
		TAILQ_REMOVE(&pool->requests, ctx, next);
		evrpc_schedule_request(evcon, ctx);
	}
}

static void
evrpc_request_timeout(evutil_socket_t fd, short what, void *arg)
{
	struct evrpc_request_wrapper *ctx = arg;
	struct evhttp_connection *evcon = ctx->evcon;
	EVUTIL_ASSERT(evcon != NULL);

	evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
}

/*
 * frees potential meta data associated with a request.
 */

static void
evrpc_meta_data_free(struct evrpc_meta_list *meta_data)
{
	struct evrpc_meta *entry;
	EVUTIL_ASSERT(meta_data != NULL);

	while ((entry = TAILQ_FIRST(meta_data)) != NULL) {
		TAILQ_REMOVE(meta_data, entry, next);
		mm_free(entry->key);
		mm_free(entry->data);
		mm_free(entry);
	}
}

static struct evrpc_hook_meta *
evrpc_hook_meta_new(void)
{
	struct evrpc_hook_meta *ctx;
	ctx = mm_malloc(sizeof(struct evrpc_hook_meta));
	EVUTIL_ASSERT(ctx != NULL);

	TAILQ_INIT(&ctx->meta_data);
	ctx->evcon = NULL;

	return (ctx);
}

static void
evrpc_hook_associate_meta(struct evrpc_hook_meta **pctx,
    struct evhttp_connection *evcon)
{
	struct evrpc_hook_meta *ctx = *pctx;
	if (ctx == NULL)
		*pctx = ctx = evrpc_hook_meta_new();
	ctx->evcon = evcon;
}

static void
evrpc_hook_context_free(struct evrpc_hook_meta *ctx)
{
	evrpc_meta_data_free(&ctx->meta_data);
	mm_free(ctx);
}

/* Adds meta data */
void
evrpc_hook_add_meta(void *ctx, const char *key,
    const void *data, size_t data_size)
{
	struct evrpc_request_wrapper *req = ctx;
	struct evrpc_hook_meta *store = NULL;
	struct evrpc_meta *meta = NULL;

	if ((store = req->hook_meta) == NULL)
		store = req->hook_meta = evrpc_hook_meta_new();

	meta = mm_malloc(sizeof(struct evrpc_meta));
	EVUTIL_ASSERT(meta != NULL);
	meta->key = mm_strdup(key);
	EVUTIL_ASSERT(meta->key != NULL);
	meta->data_size = data_size;
	meta->data = mm_malloc(data_size);
	EVUTIL_ASSERT(meta->data != NULL);
	memcpy(meta->data, data, data_size);

	TAILQ_INSERT_TAIL(&store->meta_data, meta, next);
}

int
evrpc_hook_find_meta(void *ctx, const char *key, void **data, size_t *data_size)
{
	struct evrpc_request_wrapper *req = ctx;
	struct evrpc_meta *meta = NULL;

	if (req->hook_meta == NULL)
		return (-1);

	TAILQ_FOREACH(meta, &req->hook_meta->meta_data, next) {
		if (strcmp(meta->key, key) == 0) {
			*data = meta->data;
			*data_size = meta->data_size;
			return (0);
		}
	}

	return (-1);
}

struct evhttp_connection *
evrpc_hook_get_connection(void *ctx)
{
	struct evrpc_request_wrapper *req = ctx;
	return (req->hook_meta != NULL ? req->hook_meta->evcon : NULL);
}

int
evrpc_send_request_generic(struct evrpc_pool *pool,
    void *request, void *reply,
    void (*cb)(struct evrpc_status *, void *, void *, void *),
    void *cb_arg,
    const char *rpcname,
    void (*req_marshal)(struct evbuffer *, void *),
    void (*rpl_clear)(void *),
    int (*rpl_unmarshal)(void *, struct evbuffer *))
{
	struct evrpc_status status;
	struct evrpc_request_wrapper *ctx;
	ctx = evrpc_make_request_ctx(pool, request, reply,
	    rpcname, req_marshal, rpl_clear, rpl_unmarshal, cb, cb_arg);
	if (ctx == NULL)
		goto error;
	return (evrpc_make_request(ctx));
error:
	memset(&status, 0, sizeof(status));
	status.error = EVRPC_STATUS_ERR_UNSTARTED;
	(*(cb))(&status, request, reply, cb_arg);
	return (-1);
}

/** Takes a request object and fills it in with the right magic */
static struct evrpc *
evrpc_register_object(const char *name,
    void *(*req_new)(void*), void *req_new_arg, void (*req_free)(void *),
    int (*req_unmarshal)(void *, struct evbuffer *),
    void *(*rpl_new)(void*), void *rpl_new_arg, void (*rpl_free)(void *),
    int (*rpl_complete)(void *),
    void (*rpl_marshal)(struct evbuffer *, void *))
{
	struct evrpc* rpc = (struct evrpc *)mm_calloc(1, sizeof(struct evrpc));
	if (rpc == NULL)
		return (NULL);
	rpc->uri = mm_strdup(name);
	if (rpc->uri == NULL) {
		mm_free(rpc);
		return (NULL);
	}
	rpc->request_new = req_new;
	rpc->request_new_arg = req_new_arg;
	rpc->request_free = req_free;
	rpc->request_unmarshal = req_unmarshal;
	rpc->reply_new = rpl_new;
	rpc->reply_new_arg = rpl_new_arg;
	rpc->reply_free = rpl_free;
	rpc->reply_complete = rpl_complete;
	rpc->reply_marshal = rpl_marshal;
	return (rpc);
}

int
evrpc_register_generic(struct evrpc_base *base, const char *name,
    void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
    void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
    int (*req_unmarshal)(void *, struct evbuffer *),
    void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
    int (*rpl_complete)(void *),
    void (*rpl_marshal)(struct evbuffer *, void *))
{
	struct evrpc* rpc =
	    evrpc_register_object(name, req_new, req_new_arg, req_free, req_unmarshal,
		rpl_new, rpl_new_arg, rpl_free, rpl_complete, rpl_marshal);
	if (rpc == NULL)
		return (-1);
	evrpc_register_rpc(base, rpc,
	    (void (*)(struct evrpc_req_generic*, void *))callback, cbarg);
	return (0);
}

/** accessors for obscure and undocumented functionality */
struct evrpc_pool *
evrpc_request_get_pool(struct evrpc_request_wrapper *ctx)
{
	return (ctx->pool);
}

void
evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
    struct evrpc_pool *pool)
{
	ctx->pool = pool;
}

void
evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
    void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
    void *cb_arg)
{
	ctx->cb = cb;
	ctx->cb_arg = cb_arg;
}


text:
package br.com.devmedia.cleancode.modelo.cliente;

import org.junit.Test;

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

public class CpfTest {

    private Cpf cpf;

    @Test
    public void deve_ser_igual_ao_proprio() {
        cpf = Cpf.valueOf("56470416470");
        assertCpfIgualA(cpf);
    }

    @Test
    public void deve_implementar_equals_consistente() {
        cpf = Cpf.valueOf("31628763973");
        assertCpfIgualA(Cpf.valueOf("31628763973"));
        assertCpfDiferenteDe(Cpf.valueOf("42263873090"));
    }

    @Test
    public void deve_formatar_corretamente() {
        cpf = Cpf.valueOf("31628763973");
        assertThat(String.format("%s", cpf)).isEqualTo("316.287.639-73");
    }

    private void assertCpfIgualA(Cpf cpfIgual) {
        assertThat(cpf).isEqualTo(cpfIgual);
        assertThat(cpf.hashCode()).isEqualTo(cpfIgual.hashCode());
    }

    private void assertCpfDiferenteDe(Cpf cpfDiferente) {
        assertThat(cpf).isNotEqualTo(cpfDiferente);
        assertThat(cpf.hashCode()).isNotEqualTo(cpfDiferente.hashCode());
    }

}


text:
using System;
using System.Html;
using System.Runtime.CompilerServices;

namespace jQueryApi.UI.Effects {

    [Imported]
    [IgnoreNamespace]
    [Serializable]
    public sealed class SwitchClassOptions {

        ///
        /// Whether the animation should additionally be applied to all descendants of the matched elements. This feature should be used with caution as the cost of determining which descendants to animate can be very expensive, and grows linearly with the number of descendants.
        ///
        public bool Children {
            get; set;
        }

        ///
        /// A function to call once the animation is complete.
        ///
        public Delegate Complete {
            get; set;
        }

        ///
        /// A string or number determining how long the animation will run.
        ///
        public TypeOption<int, string> Duration {
            get; set;
        }

        ///
        /// A string indicating which easing function to use for the transition.
        ///
        public string Easing {
            get; set;
        }

        ///
        /// A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string.
        ///
        public TypeOption<bool, string> Queue {
            get; set;
        }
    }
}


text:
package io.github.carlomicieli.springbooks.domain;

import org.junit.Test;

import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author Carlo Micieli
 */
public class BookTests {

    @Test
    public void shouldBuildNewBooks() {
        Book newBook = new Book.Builder()
                .author("David Foster Wallace")
                .title("The pale king")
                .tag("tax")
                .tag("postmortem")
                .build();

        assertThat(newBook.getAuthor(), equalTo("David Foster Wallace"));
        assertThat(newBook.getTitle(), equalTo("The pale king"));
        assertThat(newBook.getTags(), hasItem("tax"));
        assertThat(newBook.getTags(), hasItem("postmortem"));
    }

    @Test
    public void shouldProduceEditorForBooks() {
        Book oldBook = new Book.Builder()
                .author("David Foster Wallace")
                .title("The pale king")
                .tag("tax")
                .tag("postmortem")
                .build();

        Book newBook = oldBook.editor()
                .title("Infinite jest")
                .author("DFW")
                .build();

        assertThat(oldBook.getTitle(), equalTo("The pale king"));
        assertThat(newBook.getTitle(), equalTo("Infinite jest"));
        assertThat(oldBook.getAuthor(), equalTo("David Foster Wallace"));
        assertThat(newBook.getAuthor(), equalTo("DFW"));

        assertThat(oldBook.getTags(), hasItem("tax"));
        assertThat(newBook.getTags(), hasItem("tax"));
    }
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START functions_hello_bigquery]
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

const functions = require('@google-cloud/functions-framework');

/**
 * HTTP Cloud Function that returns BigQuery query results
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
functions.http('helloBigQuery', async (req, res) => {
  // Define the SQL query
  // Queries the public Shakespeare dataset using named query parameter
  const sqlQuery = `
      SELECT word, word_count
            FROM \`bigquery-public-data.samples.shakespeare\`
            WHERE corpus = @corpus
            AND word_count >= @min_word_count
            ORDER BY word_count DESC`;

  const options = {
    query: sqlQuery,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
    params: {corpus: 'romeoandjuliet', min_word_count: 400},
  };

  // Execute the query
  try {
    const [rows] = await bigquery.query(options);
    // Send the results
    res.status(200).send(rows);
  } catch (err) {
    console.error(err);
    res.status(500).send(`Error querying BigQuery: ${err}`);
  }
});
// [END functions_hello_bigquery]


text:
module LiteHome
  class ApplicationController < ActionController::Base
    protect_from_forgery
    layout LiteHome.layout_name
    before_filter :get_user_class
    before_filter :require_login, :except => [:not_authenticated]
    helper_method :current_users_list

    protected

    def not_authenticated
      flash[:info] = t('lite_home.msg.require_login')
      redirect_to login_path
    end

    private

    def get_user_class
      @user_class = LiteHome::User
    end
  end
end


text:
package org.apereo.cas.oidc.web.flow;

import org.apereo.cas.config.CasCoreMultifactorAuthenticationConfiguration;
import org.apereo.cas.config.CasOAuth20AuthenticationServiceSelectionStrategyConfiguration;
import org.apereo.cas.config.CasOAuth20Configuration;
import org.apereo.cas.config.CasOAuth20EndpointsConfiguration;
import org.apereo.cas.config.CasOAuth20ThrottleConfiguration;
import org.apereo.cas.config.CasOAuth20WebflowConfiguration;
import org.apereo.cas.config.CasThrottlingConfiguration;
import org.apereo.cas.config.CasThymeleafConfiguration;
import org.apereo.cas.oidc.config.OidcComponentSerializationConfiguration;
import org.apereo.cas.oidc.config.OidcConfiguration;
import org.apereo.cas.oidc.config.OidcThrottleConfiguration;
import org.apereo.cas.services.web.config.CasThemesConfiguration;
import org.apereo.cas.web.flow.BaseWebflowConfigurerTests;
import org.apereo.cas.web.flow.CasWebflowConfigurer;
import org.apereo.cas.web.flow.config.CasMultifactorAuthenticationWebflowConfiguration;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.webflow.engine.Flow;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link OidcWebflowConfigurerTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@Import({
    CasThymeleafConfiguration.class,
    CasThemesConfiguration.class,
    OidcConfiguration.class,
    OidcComponentSerializationConfiguration.class,
    OidcThrottleConfiguration.class,
    CasOAuth20Configuration.class,
    CasOAuth20EndpointsConfiguration.class,
    CasOAuth20AuthenticationServiceSelectionStrategyConfiguration.class,
    CasOAuth20ThrottleConfiguration.class,
    CasOAuth20WebflowConfiguration.class,
    CasThrottlingConfiguration.class,
    CasCoreMultifactorAuthenticationConfiguration.class,
    CasMultifactorAuthenticationWebflowConfiguration.class,
    BaseWebflowConfigurerTests.SharedTestConfiguration.class
})
@TestPropertySource(properties = "cas.authn.oidc.jwks.jwksFile=classpath:keystore.jwks")
@Tag("OIDC")
public class OidcWebflowConfigurerTests extends BaseWebflowConfigurerTests {

    @Test
    public void verifyOperation() {
        assertFalse(casWebflowExecutionPlan.getWebflowConfigurers().isEmpty());
        val flow = (Flow) this.loginFlowDefinitionRegistry.getFlowDefinition(CasWebflowConfigurer.FLOW_ID_LOGIN);
        assertNotNull(flow);
    }
}