text:
<?php

require_once dirname( __FILE__ ) . '/test_case.php';

/**
 * Tests for ezcGraph class.
 *
 * @package Graph
 * @subpackage Tests
 */
class ezcGraphBackgroundTest extends ezcGraphTestCase
{
    protected $testFiles = array(
        'jpeg'          => 'jpeg.jpg',
        'nonexistant'   => 'nonexisting.jpg',
        'invalid'       => 'text.txt',
    );

	public static function suite()
	{
		return new PHPUnit_Framework_TestSuite( "ezcGraphBackgroundTest" );
	}

    protected function setUp()
    {
        static $i = 0;

        $this->tempDir = $this->createTempDir( __CLASS__ . sprintf( '_%03d_', ++$i ) ) . '/';
        $this->basePath = dirname( __FILE__ ) . '/data/';
    }

    protected function tearDown()
    {
        if ( !$this->hasFailed() )
        {
            $this->removeTempDir();
        }
    }

    public function testSetOptionsInvalidBackgroundImage()
    {
        try
        {
            $pieChart = new ezcGraphPieChart();
            $pieChart->background->image = $this->basePath . $this->testFiles['invalid'];
        }
        catch ( ezcGraphInvalidImageFileException $e )
        {
            return true;
        }

        $this->fail( 'Expected ezcGraphInvalidImageFileException' );
    }

    public function testSetOptionsNonexistantBackgroundImage()
    {
        try
        {
            $pieChart = new ezcGraphPieChart();
            $pieChart->background->image = $this->basePath . $this->testFiles['nonexistant'];
        }
        catch ( ezcBaseFileNotFoundException $e )
        {
            return true;
        }

        $this->fail( 'Expected ezcBaseFileNotFoundException' );
    }

    public function testSetOptionsBackground()
    {
        $pieChart = new ezcGraphPieChart();
        $pieChart->background->color = '#FF0000';

        $this->assertEquals(
            ezcGraphColor::fromHex( 'FF0000' ),
            $pieChart->background->color
        );
    }

    public function testSetOptionsBorder()
    {
        $pieChart = new ezcGraphPieChart();
        $pieChart->background->border = '#FF0000';

        $this->assertEquals(
            ezcGraphColor::fromHex( 'FF0000' ),
            $pieChart->background->border
        );
    }

    public function testSetOptionsBorderLineChart()
    {
        $lineChart = new ezcGraphLineChart();
        $lineChart->background = '#FF0000';

        $this->assertEquals(
            ezcGraphColor::fromHex( 'FF0000' ),
            $lineChart->background->color
        );
    }

    public function testSetOptionsBorderWidth()
    {
        $pieChart = new ezcGraphPieChart();
        $pieChart->background->borderWidth = 3;

        $this->assertSame( 3, $pieChart->background->borderWidth );
    }

    public function testRenderPieChartWithBackgroundBorder()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->border = '#000000';
        $chart->background->borderWidth = 1;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBigBackgroundBorder()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->border = '#000000';
        $chart->background->borderWidth = 5;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBackgroundBorderAndPadding()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->border = '#000000';
        $chart->background->borderWidth = 1;
        $chart->background->padding = 2;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBackgroundBorderAndMargin()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->border = '#000000';
        $chart->background->borderWidth = 1;
        $chart->background->margin = 3;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBackgroundBorderAll()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->border = '#000000';
        $chart->background->borderWidth = 2;
        $chart->background->padding = 3;
        $chart->background->margin = 3;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBackgroundBottomRight()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->color = '#FFFFFFDD';
        $chart->background->image = dirname( __FILE__ ) . '/data/ez.png';
        $chart->background->position = ezcGraph::BOTTOM | ezcGraph::RIGHT;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithTextureBackground()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->color = '#FFFFFFDD';
        $chart->background->image = dirname( __FILE__ ) . '/data/texture.png';
        $chart->background->repeat = ezcGraph::HORIZONTAL | ezcGraph::VERTICAL;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithBackgroundBottomCenter()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->color = '#FFFFFFDD';
        $chart->background->image = dirname( __FILE__ ) . '/data/ez.png';
        $chart->background->position = ezcGraph::BOTTOM | ezcGraph::CENTER;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->renderer = new ezcGraphRenderer3d();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartWithHorizontalTextureBackground()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background->color = '#FFFFFFDD';
        $chart->background->image = dirname( __FILE__ ) . '/data/texture.png';
        $chart->background->repeat = ezcGraph::HORIZONTAL;
        $chart->background->position = ezcGraph::BOTTOM;

        $chart->driver = new ezcGraphSvgDriver();
        $chart->renderer = new ezcGraphRenderer3d();
        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderPieChartBackgroundColorShortcut()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphPieChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background = '#2e3436';

        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }

    public function testRenderLineChartBackgroundColorShortcut()
    {
        $filename = $this->tempDir . __FUNCTION__ . '.svg';

        $chart = new ezcGraphLineChart();
        $chart->data['sample'] = new ezcGraphArrayDataSet( array(
            'Mozilla' => 4375,
            'IE' => 345,
            'Opera' => 1204,
            'wget' => 231,
            'Safari' => 987,
        ) );

        $chart->background = '#2e3436';

        $chart->render( 500, 200, $filename );

        $this->compare(
            $filename,
            $this->basePath . 'compare/' . __CLASS__ . '_' . __FUNCTION__ . '.svg'
        );
    }
}
?>


text:
import xml.etree.ElementTree as ET
import hashlib
from random import Random
import urllib2

from config import WXPAY_CONIFG
from utils.encoding import smart_str, smart_unicode

__author__ = 'fengguanhua'

def para_filter(params):
    if params.get('sign'):
        filter_param = params
        filter_param.pop('sign')
        return filter_param
    return params

def sign_md5(params):
    keys = params.keys()
    keys.sort()
    array = []
    for key in keys:
        if not params[key] or params[key] == '':
            continue
        if key == 'sign':
            continue
        array.append("%s=%s" % (key, params[key]))
    string1 = "&".join(array)
    string_sign_temp = string1 + '&key=' + WXPAY_CONIFG['api_key']
    m = hashlib.md5(string_sign_temp.encode('utf-8'))
    return m.hexdigest().upper()

def verify_notify(params):
    wx_sign = params['sign']
    sign = sign_md5(params)
    return wx_sign == sign

def random_str(randomlength=32):
    str = ''
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str

def xml_to_dict(raw_str):
    raw_str = smart_str(raw_str)
    raw_str = str(raw_str)
    msg = {}
    root_elem = ET.fromstring(raw_str)
    if root_elem.tag == 'xml':
        for child in root_elem:
            msg[child.tag] = smart_unicode(child.text)
            msg[child.tag] = unicode(child.text)
        return msg
    else:
        return None

def dict_to_xml(params):
    xml_elements = ["<xml>", ]
    for (k, v) in params.items():
        if str(v).isdigit():
            xml_elements.append('<%s>%s</%s>' % (k, v, k))
        else:
            xml_elements.append('<%s><![CDATA[%s]]></%s>' % (k, v, k))
    xml_elements.append('</xml>')
    return ''.join(xml_elements)

def do_post(url, data):
    req = urllib2.Request(url)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    response = opener.open(req, data)
    return response.read()

def format_param_map(param_map):
    sort_list = sorted(param_map)
    buff = []
    for k in sort_list:
        buff.append("{0}={1}".format(k, param_map[k]))
    return "&".join(buff)

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
L10NObject.prototype.saveOverrideForCurrentLanguageFromUrl = function (url, callback) {
//------------------------------------------------------------------------------
  //Ti.API.debug('saveOverrideForCurrentLanguageFromUrl, url = "' + url + '"');
  var this_l10n = this;

  var c = Ti.Network.createHTTPClient();

  c.onerror = function() {
    //Ti.API.debug('c.onerror()');
    if (callback) {
      callback(false, 'Unable to load the document. Maybe server is down or you mistyped the URL?', url); // fail
    }
  };

  c.onload = function() {
    //Ti.API.debug('c.onload()');
    var f = Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory(),
                                  this_l10n.LangDir,
                                  this_l10n.LoadedLanguage + '.override.txt');

    if (!c.responseText.match(this_l10n.FileSignature)) {
      Ti.API.warn('Downloaded file has the wrong format');
      if (callback) {
        callback(false, 'Downloaded file has the wrong format. Probably you mistyped the URL?', url); // fail
      }
      return;
    }

    Ti.API.debug('Saving to file "' + f + '"');
    f.write(c.responseText);

    if (callback) {
      callback(true, c.statusText, url); // ok
    }
  };

  Ti.API.debug('Loading URL "' + url + '"');

  c.open('GET', url);
  c.send();
};

//------------------------------------------------------------------------------
L10NObject.prototype.deleteOverrideFiles = function () {
//------------------------------------------------------------------------------
  var result = false;
  for (var key in this.LanguageOverrideFiles) {
    if (true) { // to avoid warning message from Titanium compiler
      var file = this.LanguageOverrideFiles[key];

      var f = Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory(), this.LangDir, file);
      Ti.API.debug('Deleting file "' + f + '"');
      if (f.deleteFile()) { result = true; }
    }
  }
  if (result) { // if at least one file was deleted
    this.scanLocalizationFiles(); // rescan the contents of the directory
  }
  return result;
};

//----------------------------------------------------------------------------
L10NObject.prototype.showLanguageSelectionDialog = function () {
//----------------------------------------------------------------------------
  var this_l10n = this;

  var ACTION_DELETE = 0;
  var ACTION_LOAD = 1;
  var ACTION_SELECT = 2;
  var RESTART_MESSAGE = 'Please restart the application for changes to take effect.';

  var new_lang;
  var app_restart_required; // will be true if

  var win = Ti.UI.createWindow({
    title:'Language'
  });

  // spinner indicator (displayed when querying image from the server)

  var spinner = Ti.UI.createActivityIndicator({
    height: 50,
    width: 50,
    style: Ti.UI.iPhone.ActivityIndicatorStyle.BIG
  });

  // create and populate table view data object

  var data = [];

//  var row = Ti.UI.createTableViewRow({
//    title: 'Choose automatically',
//    selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.NONE,
//    className: 'control'
//  });
//  var sw = Ti.UI.createSwitch({
//    right: 7,
//    value: !!!this_l10n.getPreferredLanguage()
//  });
//
//  row.add(sw);

//  sw.addEventListener('change', function(e) {
//    if (!!!this_l10n.getPreferredLanguage() != e.value) {
//      app_restart_required = true;
//      if (e.value) { // switched on
//        this_l10n.setPreferredLanguage(false);
//      } else { // switched off
//        this_l10n.setPreferredLanguage(this_l10n.LoadedLanguage);
//      }
//    }
//  });

//  data.push(row);

  for (var i = 0; i < this.Languages.length; i++) {
    var l = this.Languages[i];
    var t = this_l10n.getLanguageDisplayName(l);
    //t = (this_l10n.LoadedLanguage == l) ? t + ' (current)' : t;
    data.push({
      title: t,
      lang: l,
      action: ACTION_SELECT,
      //hasCheck: !!this_l10n.getPreferredLanguage() && (this_l10n.LoadedLanguage == l)
      hasCheck: (this_l10n.LoadedLanguage == l)
    });
  }

//  row = Ti.UI.createTableViewRow();
//  var url = Ti.App.Properties.getString(this_l10n.LangUrlPreferenceName); // load url from preferences
//  if (!url) { url = 'http://mydomain/ru.txt'; }
//  var tf1 = Ti.UI.createTextField({
//    height: 35,
//    left: 10,
//    width: 280,
//    value: url,
//    autocorrect: false,
//    autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
//    keyboardType: Ti.UI.KEYBOARD_URL,
//    returnKeyType: Ti.UI.RETURNKEY_DONE,
//    borderStyle: Ti.UI.INPUT_BORDERSTYLE_NONE
//  });
//  row.add(tf1);
//  row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
//  row.className = 'control';
//  row.header = 'Testing localizations:';
//  data.push(row);
//
//  data.push({
//    title:'Load override for "' + this_l10n.LoadedLanguage + '" locale',
//    action: ACTION_LOAD/*,
//    header: 'Testing localizations:'*/
//  });
//
//  i = 0; for (var key in this_l10n.LanguageOverrideFiles) { if (true) { i++; } }
//  if (i > 0) {
//    data.push({title:'Delete override files (' + i + ')', action: ACTION_DELETE});
//  }

  // create table view
  var tableview = Ti.UI.createTableView({
    data:data,
    style:Ti.UI.iPhone.TableViewStyle.GROUPED
  });

  // create table view event listener
  tableview.addEventListener('click', function(e) {
    var rowdata = e.rowData;

    if (rowdata.action == ACTION_DELETE) { // delete override files
      if (this_l10n.deleteOverrideFiles()) {
        tableview.deleteRow(e.index);
        app_restart_required = true;
      } else {
        Ti.UI.createAlertDialog({
           title:'No Files Deleted',
           message:'No files were deleted. Something possibly went wrong.'
        }).show();
      }
    } else if (rowdata.action == ACTION_LOAD) { // load override file
      spinner.show();
      Ti.App.Properties.setString(this_l10n.LangUrlPreferenceName, tf1.value); // save url to preferences
      this_l10n.saveOverrideForCurrentLanguageFromUrl(tf1.value, function(success, error_message, url) {
        spinner.hide();
        if (success) {
          app_restart_required = true;
          Ti.UI.createAlertDialog({
             title:'File Loaded',
             message:'File loaded successfully. ' + RESTART_MESSAGE
          }).show();
        } else {
          Ti.UI.createAlertDialog({
             title:'Error',
             message:error_message
          }).show();
        }
      });
    } else if (rowdata.action == ACTION_SELECT) { // select language
      this_l10n.setPreferredLanguage(rowdata.lang);

//      sw.value = false; // turn off 'Auto' switch

      // reset checks
      for (var i = 0; i < e.section.rows.length; i++) {
        e.section.rows[i].hasCheck = false;
      }
      e.section.rows[e.index].hasCheck = true;

      new_lang = rowdata.lang;
      app_restart_required = true;
    }
  });

  win.add(tableview);

  win.add(spinner);

  // create a button to close window
  var b = Ti.UI.createButton({
    title:'Close',
    style:Ti.UI.iPhone.SystemButtonStyle.PLAIN
  });
  win.setRightNavButton(b);

  b.addEventListener('click', function() {
    if (app_restart_required) {
      if (new_lang) {
        Ti.UI.createAlertDialog({
           title:'Language Selected',
           message:'"' + this_l10n.getLanguageDisplayName(new_lang) +
                   '" is now a preferred language. ' + RESTART_MESSAGE
        }).show();
      } else {
        Ti.UI.createAlertDialog({
           title:'Configuration Changed',
           message: RESTART_MESSAGE
        }).show();
      }
    }

    win.close();
  });

  win.open({modal:true});
};


text:
'use strict';

module.exports = {
	app: {
		title: 'BenCRM',
		description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
		keywords: 'MongoDB, Express, AngularJS, Node.js'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
				'public/lib/angular-material/angular-material.min.css',
				'//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-material/angular-material.min.js',
				'public/lib/angular-aria/angular-aria.min.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'//cdn.socket.io/socket.io-1.3.5.js',
				'public/lib/angular-socket-io/socket.min.js',
				'//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.6.0/lodash.min.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};


text:
This directory contains all smoke tests for Tectonic.
The smoke tests are a set of Golang test files that perform minimal validation of a running Tectonic cluster.
This directory is further partitioned into platform-specific directories and should conform to the following directory hierarchy:

```
smoke/
├── aws        # Smoke tests for AWS
│   └── vars   # Terraform tfvars files for AWS smoke tests
├── azure
│   └── vars   # Terraform tfvars files for Azure smoke tests
├── bare-metal
│   └── vars   # Terraform tfvars files for bare-metal smoke tests
├── *_test.go  # Smoke tests for all platforms
├── vendor     # Smoke test dependencies
└── ...
```

## Getting Started

The smoke tests assume a running Tectonic cluster, so before running any tests:
1. create a Tectonic cluster; and
2. download the cluster's kubeconfig to a known location.

## Running

The smoke tests require two parameters: the file path of the cluster kubeconfig and the number of nodes in the cluster.
Export the following variables to parameterize the smoke tests:

```
export TEST_KUBECONFIG=/path/to/kubeconfig
export NODE_COUNT=3
```

Tests can then be run using the `go test` tool:

```
go test -v github.com/coreos/tectonic-installer/installer/tests/sanity
```


text:
package server

import (
	"net/http"

	"github.com/juhovuori/builder/app"
	"github.com/juhovuori/builder/project"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Server is the HTTP server that implements Builder API
type Server interface {
	Run() error
}

type echoServer struct {
	echo  *echo.Echo
	app   app.App
	token *string
}

func (s echoServer) Run() error {
	return s.echo.Start(s.app.Config().ServerAddress)
}

func (s echoServer) setupRouteHandlers() error {
	s.echo.GET("/", s.hRoot)
	s.echo.GET("/health", s.hHealth)
	s.echo.GET("/metrics", echo.WrapHandler(promhttp.Handler()))
	s.echo.POST("/v1/builds", s.hCreateBuild)
	s.echo.GET("/v1/builds", s.hListBuilds)
	s.echo.GET("/v1/builds/:id", s.hGetBuild)
	s.echo.GET("/v1/builds/:id/stdout", s.hGetStdout)
	s.echo.POST("/v1/builds/:id", s.hAddStage)
	s.echo.GET("/v1/builds/:id/data/:stage", s.hGetStageData)
	s.echo.GET("/v1/projects", s.hListProjects)
	s.echo.GET("/v1/projects/:id", s.hGetProject)
	s.echo.GET("/v1/projects/:id/builds", s.hListProjectBuilds)
	s.echo.POST("/v1/projects/:id/trigger", s.hTriggerBuild)
	s.echo.GET("/v1/version", s.hVersion)
	s.echo.POST("/v1/shutdown", s.hShutdown)
	return nil
}

func (s echoServer) errorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	msg := err.Error()
	if he, ok := err.(*echo.HTTPError); ok {
		code = he.Code
	} else if err == project.ErrNotFound {
		code = 404
	}
	if !c.Response().Committed {
		if c.Request().Method == echo.HEAD { // Issue #608
			c.NoContent(code)
		} else {
			se := serverError{code, msg}
			c.JSON(code, se)
		}
	}
	s.echo.Logger.Error(err)
}

// New creates a new echo Server instance
func New(app app.App) (Server, error) {
	return NewWithSystemToken(app, nil)
}

// NewWithSystemToken creates a new echo Server instance
func NewWithSystemToken(app app.App, token *string) (Server, error) {
	server := echoServer{
		echo:  echo.New(),
		app:   app,
		token: token,
	}
	server.echo.HTTPErrorHandler = server.errorHandler
	server.echo.Pre(middleware.RemoveTrailingSlash())
	server.echo.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: "method=${method}, uri=${uri}, status=${status}\n",
	}))
	server.setupRouteHandlers()
	return server, nil
}

type serverError struct {
	Code  int    `json:"code"`
	Error string `json:"error"`
}


text:
package gore

import (
	"regexp"
	"strings"
	"sync"
	"time"
)

// Sentinel is a special Redis process that monitors other Redis instances,
// does fail-over, notifies client status of all monitored instances.
type Sentinel struct {
	servers   []string
	conn      *Conn
	subConn   *Conn // A dedicated connection for pubsub
	subs      *Subscriptions
	mutex     *sync.Mutex
	state     int
	instances map[string]*instance
}

// NewSentinel returns new Sentinel
func NewSentinel() *Sentinel {
	return &Sentinel{
		mutex:     &sync.Mutex{},
		state:     connStateNotConnected,
		instances: make(map[string]*instance),
	}
}

// AddServer adds new sentinel servers. Only one sentinel server is active
// at any time. If this server fails, gore will connect to other sentinel
// servers immediately.
//
// AddServer can be called at anytime, to add new server on the fly.
// In production environment, you should always have at least 3 sentinel
// servers up and running.
func (s *Sentinel) AddServer(addresses ...string) {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	s.servers = append(s.servers, addresses...)
}

// Dial connects to one sentinel server in the list. If it fails to connect,
// it moves to the next on the list. If all servers cannot be connected,
// Init return error.
func (s *Sentinel) Dial() (err error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if s.state != connStateNotConnected {
		return nil
	}
	return s.connect()
}

// Close gracefully closes the sentinel and all monitored connections
func (s *Sentinel) Close() {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	s.close()
}

// GetPool returns a pool of connection from a pool name.
// If the pool has not been retrieved before, gore will attempt to
// fetch the address from the sentinel server, and initialize connections
// with this address. The application should never call this function repeatedly
// to get the same pool, because internal locking can cause performance to drop.
// An error can be returned if the pool name is not monitored by the sentinel,
// or the redis server is currently dead, or the redis server cannot be connected
// (for example: firewall issues).
func (s *Sentinel) GetPool(name string) (*Pool, error) {
	return s.getPool(name, "")
}

// GetPoolWithPassword returns a pool of connection to a password-protected instance
func (s *Sentinel) GetPoolWithPassword(name string, password string) (*Pool, error) {
	return s.getPool(name, password)
}

func (s *Sentinel) getPool(name string, password string) (*Pool, error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if ins, ok := s.instances[name]; ok {
		return ins.pool, nil
	}
	rep, err := NewCommand("SENTINEL", "master", name).Run(s.conn)
	if err != nil {
		return nil, err
	}
	if rep.IsError() {
		return nil, ErrNil
	}
	master, err := rep.Map()
	if err != nil {
		return nil, err
	}
	flags := strings.Split(master["flags"], ",")
	for _, flag := range flags {
		if flag == "s_down" || flag == "o_down" {
			return nil, ErrNotConnected
		}
	}
	ins := &instance{
		name:    name,
		address: master["ip"] + ":" + master["port"],
		state:   connStateConnected,
		pool:    &Pool{sentinel: true, Password: password},
	}
	err = ins.pool.Dial(ins.address)
	if err != nil {
		return nil, err
	}
	s.instances[name] = ins
	return ins.pool, nil
}

// GetCluster returns a cluster monitored by the sentinel.
// The name of the cluster will determine name of Redis instances.
// For example, if the cluster name is "mycluster", the instances' name
// maybe "mycluster1", "mycluster2", ...
func (s *Sentinel) GetCluster(name string) (c *Cluster, err error) {
	return s.getCluster(name, "")
}

// GetClusterWithPassword returns a password-protected cluster monitored by the sentinel.
func (s *Sentinel) GetClusterWithPassword(name string, password string) (c *Cluster, err error) {
	return s.getCluster(name, password)
}

func (s *Sentinel) getCluster(name string, password string) (c *Cluster, err error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	rep, err := NewCommand("SENTINEL", "masters").Run(s.conn)
	if err != nil {
		return nil, err
	}
	replies, err := rep.Array()
	if err != nil {
		return nil, err
	}
	if len(replies) == 0 {
		return nil, ErrNoShard
	}
	instances := make(map[string]*instance)
	defer func() {
		if err != nil {
			for _, ins := range instances {
				ins.pool.Close()
			}
		}
	}()
	for _, r := range replies {
		master, err := r.Map()
		if err != nil {
			return nil, err
		}
		suffix := strings.TrimPrefix(master["name"], name)
		if !suffixRegex.MatchString(suffix) {
			continue
		}
		ins := &instance{
			name:    master["name"],
			address: master["ip"] + ":" + master["port"],
			state:   connStateConnected,
			pool:    &Pool{sentinel: true, Password: password},
		}
		err = ins.pool.Dial(ins.address)
		if err != nil {
			return nil, err
		}
		instances[ins.name] = ins
	}
	c = NewCluster()
	c.sentinel = true
	for _, ins := range instances {
		s.instances[ins.name] = ins
		c.addresses = append(c.addresses, &addressWithPassword{ins.address, password})
		c.shards = append(c.shards, ins.pool)
	}
	return c, nil
}

var suffixRegex = regexp.MustCompile("^\\d+$")

func (s *Sentinel) connect() (err error) {
	for i, server := range s.servers {
		s.conn, err = DialTimeout(server, time.Duration(Config.ConnectTimeout)*time.Second)
		if err != nil {
			continue
		}
		s.subConn, err = DialTimeout(server, time.Duration(Config.ConnectTimeout)*time.Second)
		if err != nil {
			s.conn.Close()
			continue
		}
		s.state = connStateConnected
		s.subs = NewSubscriptions(s.subConn)
		s.subs.throwError = true
		err = s.subs.Subscribe("+sdown", "-sdown", "+odown", "-odown", "+switch-master")
		if err != nil {
			s.close()
			continue
		}
		s.servers = append(s.servers[0:i], s.servers[i+1:]...)
		s.servers = append(s.servers, server)
		go s.monitor()
		return nil
	}
	return ErrNotConnected
}

func (s *Sentinel) close() {
	s.state = connStateNotConnected
	s.subs.Close()
	s.subConn.Close()
	s.conn.Close()
	for _, ins := range s.instances {
		ins.pool.Close()
	}
	s.instances = make(map[string]*instance)
}

func (s *Sentinel) fail() {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if s.state == connStateConnected {
		s.state = connStateNotConnected
		s.reconnect()
	}
}

func (s *Sentinel) reconnect() {
	s.subs.Close()
	s.subConn.Close()
	s.conn.Close()
	sleepTime := Config.ReconnectTime
	for {
		err := s.connect()
		if err == nil {
			break
		}
		time.Sleep(time.Duration(sleepTime) * time.Second)
		if sleepTime < 30 {
			sleepTime += 2
		}
	}
}

func (s *Sentinel) monitor() {
	for message := range s.subs.Message() {
		if message == nil {
			s.fail()
			return
		}
		s.mutex.Lock()
		ins := s.getInstanceFromMessage(message)
		if ins == nil {
			s.mutex.Unlock()
			continue
		}
		if message.Channel == "+sdown" || message.Channel == "+odown" {
			ins.down(message)
		} else if message.Channel == "-sdown" || message.Channel == "-odown" {
			ins.up(message)
		} else if message.Channel == "+switch-master" {
			ins.switchMaster(s)
		}
		s.mutex.Unlock()
	}
}

func (s *Sentinel) getInstanceFromMessage(message *Message) *instance {
	if message.Channel == "+sdown" || message.Channel == "+odown" ||
		message.Channel == "-sdown" || message.Channel == "-odown" {
		pieces := strings.Split(string(message.Message), " ")
		if len(pieces) < 2 || pieces[0] != "master" {
			return nil
		}
		return s.instances[pieces[1]]
	} else if message.Channel == "+switch-master" {
		pieces := strings.Split(string(message.Message), " ")
		if len(pieces) < 1 {
			return nil
		}
		return s.instances[pieces[0]]
	}
	return nil
}

func (s *Sentinel) getInstanceAddress(name string) string {
	for {
		rep, err := NewCommand("SENTINEL", "get-master-addr-by-name", name).Run(s.conn)
		if err != nil {
			time.Sleep(2 * time.Second)
			continue
		}
		if !rep.IsArray() {
			return ""
		}
		result := []string{}
		rep.Slice(&result)
		if len(result) != 2 {
			return ""
		}
		return result[0] + ":" + result[1]
	}
}

type instance struct {
	name    string
	address string
	sdown   bool
	odown   bool
	pool    *Pool
	state   int
}

func (ins *instance) down(message *Message) {
	if ins.state != connStateConnected {
		return
	}
	ins.state = connStateNotConnected
	if message.Channel == "+sdown" {
		ins.sdown = true
	} else if message.Channel == "+odown" {
		ins.odown = true
	}
	ins.pool.sentinelGonnaLetYouDown()
}

func (ins *instance) up(message *Message) {
	if ins.state == connStateConnected {
		return
	}
	if message.Channel == "-sdown" {
		ins.sdown = false
	} else if message.Channel == "-odown" {
		ins.odown = false
	}
	if !ins.sdown && !ins.odown {
		ins.pool.sentinelGonnaGiveYouUp()
		ins.state = connStateConnected
	}
}

func (ins *instance) switchMaster(s *Sentinel) {
	address := s.getInstanceAddress(ins.name)
	if address == "" {
		// WTF
		return
	}
	if ins.state == connStateConnected {
		ins.pool.sentinelGonnaLetYouDown()
	}
	ins.pool.address = address
	ins.pool.sentinelGonnaGiveYouUp()
	ins.state = connStateConnected
}


text:
read GCC CLANG ICC TEMPLIGHT < <(../../../detect_compiler $1)

if [ "$1" == "gcc" ] || [ "$1" == "g++" ]; then
	COMPILER=$GCC
	CRES=compilation_results_gcc
	BRES=binary_results_gcc
	RRES=runtime_results_gcc
elif [ "$1" == "clang" ] || [ "$1" == "clang++" ]; then
	COMPILER=$CLANG
	CRES=compilation_results_clang
	BRES=binary_results_clang
	RRES=runtime_results_clang
elif [ "$1" == "icc" ] || [ "$1" == "icpc" ]; then
	COMPILER=$ICC
	CRES=compilation_results_icc
	BRES=binary_results_icc
	RRES=runtime_results_icc
elif [ "$1" == "profile" ]; then
	templight=$TEMPLIGHT
else
	echo "Don't understand the compiler"
	exit 1
fi

# Test to run
if [ "$2" != "runtime_bench" ] && [ "$2" != "compile_time_bench" ]; then
	if [ "$1" != "profile" ]; then
		echo "Don't understand which benchmark test to run. I am going to assume you meant compile time benchmark"
		bench=compile_time_bench
	fi
else
	bench=$2
fi

if [ "$bench" == "compile_time_bench" ]; then
	make CXX=$COMPILER bench_test=$bench TIME_RES=$CRES > $BRES
elif [ "$bench" == "runtime_bench" ]; then
	make CXX=$COMPILER bench_test=$bench
	make run CXX=$COMPILER > $RRES
fi

if [ "$1" == "profile" ]; then
	make CXX=$templight bench_test=profiler
fi


text:
require "self_enumerable/version"

module SelfEnumerable
  WRAPPED_METHODS = [
    :collect, :collect_concat, :drop, :drop_while, :first, :find_all,
    :grep, :max, :min, :min_by, :partition, :reject, :select, :sort, :sort_by,
    :take, :take_while
  ] # map/flat_map are disabled because its often used to map something into another format

  def self.included(klass)
    klass.class_eval <<-eoruby
      include Enumerable
    eoruby

    # for every Enumerable method, e.g. #map, #select ...
    Enumerable.public_instance_methods.each do |_enum_method|
      if WRAPPED_METHODS.include?(_enum_method)
        if _enum_method == :partition # some special handling is needed
          klass.class_eval <<-eoruby
            def #{_enum_method}(*)
              (result = super).is_a?(Array) ? [self.class.new(result[0]), self.class.new(result[1])] : result
            end
          eoruby
        else
          klass.class_eval <<-eoruby
            def #{_enum_method}(*)
              (result = super).is_a?(Array) ? self.class.new(result) : result
            end
          eoruby
        end
      end
    end
  end
end


text:
package com.opengamma.analytics.financial.interestrate.annuity.definition;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;

import org.testng.annotations.Test;

import com.opengamma.analytics.financial.interestrate.annuity.derivative.AnnuityCouponFixed;
import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponFixed;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;

/**
 * @deprecated This class tests deprecated functionality
 */
@Deprecated
@Test(groups = TestGroup.UNIT)
public class DeprecatedFixedCouponAnnuityTest {
  private static final double[] PAYMENT_TIMES = new double[] {0.5, 1, 1.5, 2, 2.5, 3};
  private static final double NOTIONAL = 1000;
  private static final double COUPON_RATE = 0.05;
  private static final String CURVE_NAME = "A";
  private static final double[] YEAR_FRACTIONS = new double[] {0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
  private static final CouponFixed[] PAYMENTS;
  private static final double DIFF = 0.02;
  private static final CouponFixed[] HIGHER;
  private static final Currency CUR = Currency.EUR;

  static {
    final int n = PAYMENT_TIMES.length;
    PAYMENTS = new CouponFixed[n];
    HIGHER = new CouponFixed[n];
    for (int i = 0; i < n; i++) {
      PAYMENTS[i] = new CouponFixed(CUR, PAYMENT_TIMES[i], CURVE_NAME, YEAR_FRACTIONS[i], NOTIONAL, COUPON_RATE);
      HIGHER[i] = new CouponFixed(CUR, PAYMENT_TIMES[i], CURVE_NAME, YEAR_FRACTIONS[i], NOTIONAL, COUPON_RATE + DIFF);
    }
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullPaymentTimes() {
    new AnnuityCouponFixed(CUR, null, NOTIONAL, COUPON_RATE, CURVE_NAME, true);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testEmptyPaymentTimes() {
    new AnnuityCouponFixed(CUR, new double[0], NOTIONAL, COUPON_RATE, CURVE_NAME, true);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullYearFractions() {
    new AnnuityCouponFixed(CUR, PAYMENT_TIMES, NOTIONAL, COUPON_RATE, null, CURVE_NAME, true);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testEmptyYearFractions() {
    new AnnuityCouponFixed(CUR, PAYMENT_TIMES, NOTIONAL, COUPON_RATE, new double[0], CURVE_NAME, true);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullCurveName() {
    new AnnuityCouponFixed(CUR, PAYMENT_TIMES, NOTIONAL, COUPON_RATE, (String) null, true);
  }

  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testWrongArrayLength() {
    new AnnuityCouponFixed(CUR, new double[] {1, 2, 3}, NOTIONAL, COUPON_RATE, YEAR_FRACTIONS, CURVE_NAME, true);
  }

  @Test
  public void testConstructors() {
    final AnnuityCouponFixed annuity = new AnnuityCouponFixed(PAYMENTS);
    assertFalse(annuity.equals(new AnnuityCouponFixed(CUR, PAYMENT_TIMES, COUPON_RATE, CURVE_NAME, false)));
    assertEquals(new AnnuityCouponFixed(CUR, PAYMENT_TIMES, 1, COUPON_RATE, CURVE_NAME, true), new AnnuityCouponFixed(CUR, PAYMENT_TIMES, COUPON_RATE, CURVE_NAME, true));
    assertEquals(annuity, new AnnuityCouponFixed(CUR, PAYMENT_TIMES, NOTIONAL, COUPON_RATE, CURVE_NAME, false));
    assertEquals(annuity, new AnnuityCouponFixed(CUR, PAYMENT_TIMES, NOTIONAL, COUPON_RATE, YEAR_FRACTIONS, CURVE_NAME, false));
  }
  //
  // @Test
  // public void testWithRate() {
  // final FixedCouponAnnuity annuity = new FixedCouponAnnuity(PAYMENTS);
  // assertFalse(annuity.withRate(COUPON_RATE) == annuity);
  // assertEquals(annuity.withRate(COUPON_RATE), annuity);
  // assertEquals(annuity.withRate(COUPON_RATE + DIFF), new FixedCouponAnnuity(HIGHER));
  // }
}


text:
package com.zang.api.domain.list;

import com.zang.api.domain.CarrierLookup;
import com.zang.api.domain.ZangList;
import org.codehaus.jackson.annotate.JsonProperty;

import java.util.List;

public class CarrierLookupsList extends ZangList<CarrierLookup> {

    @Override
    @JsonProperty("carrier_lookups")
    protected void mapElements(List<CarrierLookup> elements) {
        setElements(elements);
    }

}


text:
package net.emaze.dysfunctional.collections;

import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author rferranti
 */
public class IsContainedInTest {

    @Test(expected=IllegalArgumentException.class)
    public void testTest() {
        new IsContainedIn<Object>(null);
    }

    @Test
    public void canCheckIfNullIsContained() {
        final List<Object> container = Arrays.asList((Object)null);
        boolean test = new IsContainedIn<Object>(container).test(null);
        Assert.assertTrue(test);
    }

}


text:
/**
 * @fileoverview Compact reporter
 * @author Nicholas C. Zakas
 */

//------------------------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------------------------

function getMessageType(message, rules) {

    // TODO: Get rule severity in a better way
    var severity = null;

    if (message.fatal) {
        return "Error";
    }

    severity = rules[message.ruleId][0] || rules[message.ruleId];

    if (severity === 2) {
        return "Error";
    }

    return "Warning";
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function(results, config) {

    var output = "",
        total = 0,
        rules = config.rules || {};

    results.forEach(function(result) {

        var messages = result.messages;
        total += messages.length;

        messages.forEach(function(message) {

            output += result.filePath + ": ";
            output += "line " + (message.line || 0) +  ", col " +
                (message.column || 0) + ", " + getMessageType(message, rules);
            output += " - " + message.message + "\n";
        });

    });

    output += "\n" + total + " problem" + (total !== 1 ? "s" : "");

    return output;
};


text:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include "platform.h"

#include "server.h"
#include "message.h"

server_t* server_create(int port, int backlog)
{
	server_t* server = 0;
	SOCKADDR_IN addr;
	int reuse;

#ifdef _WIN32
	// winsock initialization
	WORD version = MAKEWORD(2,2);
	WSADATA data;
	if (WSAStartup(version, &data) != 0)
	{
		fprintf(stderr, "error: winsock initialization\r\n");
		return NULL;
	}
#endif

	server = (server_t*)malloc(sizeof(server_t));
	memset(server, 0, sizeof(server_t));
	server->socket = INVALID_SOCKET;

	// list of pointers to pointers to connections
	server->connections = (vector_t*)malloc(sizeof(vector_t));
	vector_init(server->connections, sizeof(connection_t**), 0, 0);

	// socket creation
	server->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(server->socket == INVALID_SOCKET)
	{
		fprintf(stderr, "error: server socket creation\r\n");
		return NULL;
	}

	FD_ZERO(&server->read_fdset);
	FD_SET(server->socket, &server->read_fdset);

	// info structure
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = INADDR_ANY;

	// reusage of socket
	reuse = 1;
	setsockopt(server->socket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));

	// binding
	if(bind(server->socket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
	{
		fprintf(stderr, "error: server socket binding\r\n");
		return NULL;
	}

	// start listening
	if(listen(server->socket, backlog) == SOCKET_ERROR)
	{
		fprintf(stderr,"error: listening\r\n");
		return NULL;
	}

	// server is running
	server->status = 1;

	return server;
}

int server_destroy(server_t* server)
{
	if(server == NULL)
		return -1;

	if(server->connections != NULL)
	{
		int i;
		for(i=0; i<(int)vector_length(server->connections); i++)
		{
			connection_t* conn;
			vector_get(server->connections,i,&conn);
			connection_destroy(conn);
		}
		vector_dispose(server->connections);
		free(server->connections);
	}

	// close server socket
	if(server->socket != INVALID_SOCKET)
	{
		if(closesocket(server->socket) == SOCKET_ERROR)
		{
			fprintf(stderr, "error: closesocket\r\n");
			return -1;
		}
	}

	server->socket = INVALID_SOCKET;
	server->status = 0;

	free(server);
	server = NULL;

#ifdef _WIN32
	// winsock uninitialization
	WSACleanup();
#endif

	return 0;
}

int server_accept(server_t* server, connection_t* connection)
{
	int i, maxfds, rv;
	fd_set active_fdset;

	// exit the loop if server is stopped
	if(server->status == 0)
		return -1;

	maxfds = server->socket;
	for(i=0; i<(int)vector_length(server->connections); i++)
	{
		connection_t* conn;
		vector_get(server->connections,i,&conn);
		if(conn->socket > (unsigned int)maxfds)
			maxfds = conn->socket;
	}
	maxfds += 1;

	active_fdset = server->read_fdset;
	rv = select(maxfds, &active_fdset, NULL, NULL, NULL);
	if(rv == -1)
	{
		fprintf(stderr, "error: select\r\n");
		return -1;
	}
	else if(rv == 0)
	{
		fprintf(stderr, "error: select timeout\r\n");
		return -1;
	}
	else
	{
		if(FD_ISSET(server->socket, &active_fdset))
		{
			connection_t* conn;
			char* ip;

			// info about client
			SOCKADDR* client_info = (SOCKADDR*)malloc(sizeof(SOCKADDR));
			int client_info_size = sizeof(SOCKADDR);

			// accepting incoming connection on server socket
			SOCKET client_socket = accept(server->socket, client_info, &client_info_size);
			if(client_socket == INVALID_SOCKET)
			{
				fprintf(stderr, "error: accept incoming connection\r\n");
				return -1;
			}

			FD_SET(client_socket, &server->read_fdset);

			connection->info = client_info;
			connection->socket = client_socket;

			conn = connection_create();
			conn->info = client_info;
			conn->socket = client_socket;

			// insert pointer to connection to the connection list
			vector_push(server->connections,&conn);

			ip = inet_ntoa(((SOCKADDR_IN*)client_info)->sin_addr);
			fprintf(stderr,"client %s at socket %d connected\r\n", ip, client_socket);
		}
		else
		{
			int i;
			for(i=0; i<(int)vector_length(server->connections); i++)
			{
				connection_t* conn;
				vector_get(server->connections,i,&conn);
				if(FD_ISSET(conn->socket, &active_fdset))
				{
					connection->info = conn->info;
					connection->socket = conn->socket;
					break;
				}
			}
		}
	}

	return 0;
}

int server_close_connection(server_t* server, connection_t* connection)
{
	char* ip;
	int i;

	for(i=0; i<(int)vector_length(server->connections); i++)
	{
		connection_t* conn;
		vector_get(server->connections,i,&conn);

		// remove connection from vector if socket is found
		if(conn->socket == connection->socket)
		{
			connection_destroy(conn);
			vector_remove(server->connections,i);
			break;
		}
	}

	FD_CLR(connection->socket,&server->read_fdset);

	// close client socket
	if(connection->socket != INVALID_SOCKET)
		closesocket(connection->socket);

	ip = inet_ntoa(((SOCKADDR_IN*)connection->info)->sin_addr);
	fprintf(stderr,"client %s at socket %d disconnected\r\n", ip, connection->socket);

	memset(connection, 0, sizeof(connection_t));

	return 0;
}

message_t* server_recv_msg(server_t* server, connection_t* connection)
{
	// receive message (NULL if socket is closed or error occured)
	message_t* message = connection_recv(connection);
	if(message == NULL)
		server_close_connection(server, connection);

	return message;
}

int server_send_msg(server_t* server, message_t* message, connection_t* connection)
{
	// send message (NULL if socket is closed or error occured)
	connection_send(connection, message);

	return 0;
}


text:
package helpers;

import org.antlr.stringtemplate.StringTemplate;

public class VectorArgBundle {
	public int counter;
	public int lcounter;
	public int rcounter;
	public boolean freeleft;
	public boolean freeright;
	public StringTemplate lhs;
	public StringTemplate rhs;

	public VectorArgBundle(int counter, int lcounter, int rcounter, boolean freeleft, boolean freeright, StringTemplate lhs, StringTemplate rhs) {
		super();
		this.counter = counter;
		this.lcounter = lcounter;
		this.rcounter = rcounter;
		this.freeleft = freeleft;
		this.freeright = freeright;
		this.lhs = lhs;
		this.rhs = rhs;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Storage.Files.Shares.Models;

namespace Azure.Storage.Files.Shares
{
    internal partial class ServiceRestClient
    {
        private readonly HttpPipeline _pipeline;
        private readonly string _url;
        private readonly string _version;

        ///  The ClientDiagnostics is used to provide tracing support for the client library.
        internal ClientDiagnostics ClientDiagnostics { get; }

        ///  Initializes a new instance of ServiceRestClient.
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="url"> The URL of the service account, share, directory or file that is the target of the desired operation. </param>
        /// <param name="version"> Specifies the version of the operation to use for this request. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="clientDiagnostics"/>, <paramref name="pipeline"/>, <paramref name="url"/> or <paramref name="version"/> is null. </exception>
        public ServiceRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string url, string version = "2021-12-02")
        {
            ClientDiagnostics = clientDiagnostics ?? throw new ArgumentNullException(nameof(clientDiagnostics));
            _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
            _url = url ?? throw new ArgumentNullException(nameof(url));
            _version = version ?? throw new ArgumentNullException(nameof(version));
        }

        internal HttpMessage CreateSetPropertiesRequest(ShareServiceProperties storageServiceProperties, int? timeout)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Put;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(_url, false);
            uri.AppendPath("/", false);
            uri.AppendQuery("restype", "service", true);
            uri.AppendQuery("comp", "properties", true);
            if (timeout != null)
            {
                uri.AppendQuery("timeout", timeout.Value, true);
            }
            request.Uri = uri;
            request.Headers.Add("x-ms-version", _version);
            request.Headers.Add("Accept", "application/xml");
            request.Headers.Add("Content-Type", "application/xml");
            var content = new XmlWriterContent();
            content.XmlWriter.WriteObjectValue(storageServiceProperties, "StorageServiceProperties");
            request.Content = content;
            return message;
        }

        ///  Sets properties for a storage account's File service endpoint, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
        /// <param name="storageServiceProperties"> The StorageService properties. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="storageServiceProperties"/> is null. </exception>
        public async Task<ResponseWithHeaders<ServiceSetPropertiesHeaders>> SetPropertiesAsync(ShareServiceProperties storageServiceProperties, int? timeout = null, CancellationToken cancellationToken = default)
        {
            if (storageServiceProperties == null)
            {
                throw new ArgumentNullException(nameof(storageServiceProperties));
            }

            using var message = CreateSetPropertiesRequest(storageServiceProperties, timeout);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            var headers = new ServiceSetPropertiesHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 202:
                    return ResponseWithHeaders.FromValue(headers, message.Response);
                default:
                    throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        ///  Sets properties for a storage account's File service endpoint, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
        /// <param name="storageServiceProperties"> The StorageService properties. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="storageServiceProperties"/> is null. </exception>
        public ResponseWithHeaders<ServiceSetPropertiesHeaders> SetProperties(ShareServiceProperties storageServiceProperties, int? timeout = null, CancellationToken cancellationToken = default)
        {
            if (storageServiceProperties == null)
            {
                throw new ArgumentNullException(nameof(storageServiceProperties));
            }

            using var message = CreateSetPropertiesRequest(storageServiceProperties, timeout);
            _pipeline.Send(message, cancellationToken);
            var headers = new ServiceSetPropertiesHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 202:
                    return ResponseWithHeaders.FromValue(headers, message.Response);
                default:
                    throw ClientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateGetPropertiesRequest(int? timeout)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(_url, false);
            uri.AppendPath("/", false);
            uri.AppendQuery("restype", "service", true);
            uri.AppendQuery("comp", "properties", true);
            if (timeout != null)
            {
                uri.AppendQuery("timeout", timeout.Value, true);
            }
            request.Uri = uri;
            request.Headers.Add("x-ms-version", _version);
            request.Headers.Add("Accept", "application/xml");
            return message;
        }

        ///  Gets the properties of a storage account's File service, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public async Task<ResponseWithHeaders<ShareServiceProperties, ServiceGetPropertiesHeaders>> GetPropertiesAsync(int? timeout = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateGetPropertiesRequest(timeout);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            var headers = new ServiceGetPropertiesHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ShareServiceProperties value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("StorageServiceProperties") is XElement storageServicePropertiesElement)
                        {
                            value = ShareServiceProperties.DeserializeShareServiceProperties(storageServicePropertiesElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        ///  Gets the properties of a storage account's File service, including properties for Storage Analytics metrics and CORS (Cross-Origin Resource Sharing) rules.
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public ResponseWithHeaders<ShareServiceProperties, ServiceGetPropertiesHeaders> GetProperties(int? timeout = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateGetPropertiesRequest(timeout);
            _pipeline.Send(message, cancellationToken);
            var headers = new ServiceGetPropertiesHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ShareServiceProperties value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("StorageServiceProperties") is XElement storageServicePropertiesElement)
                        {
                            value = ShareServiceProperties.DeserializeShareServiceProperties(storageServicePropertiesElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw ClientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListSharesSegmentRequest(string prefix, string marker, int? maxresults, IEnumerable<ListSharesIncludeType> include, int? timeout)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(_url, false);
            uri.AppendPath("/", false);
            uri.AppendQuery("comp", "list", true);
            if (prefix != null)
            {
                uri.AppendQuery("prefix", prefix, true);
            }
            if (marker != null)
            {
                uri.AppendQuery("marker", marker, true);
            }
            if (maxresults != null)
            {
                uri.AppendQuery("maxresults", maxresults.Value, true);
            }
            if (include != null)
            {
                uri.AppendQueryDelimited("include", include, ",", true);
            }
            if (timeout != null)
            {
                uri.AppendQuery("timeout", timeout.Value, true);
            }
            request.Uri = uri;
            request.Headers.Add("x-ms-version", _version);
            request.Headers.Add("Accept", "application/xml");
            return message;
        }

        ///  The List Shares Segment operation returns a list of the shares and share snapshots under the specified account.
        /// <param name="prefix"> Filters the results to return only entries whose name begins with the specified prefix. </param>
        /// <param name="marker"> A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. </param>
        /// <param name="maxresults"> Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items. </param>
        /// <param name="include"> Include this parameter to specify one or more datasets to include in the response. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public async Task<ResponseWithHeaders<ListSharesResponse, ServiceListSharesSegmentHeaders>> ListSharesSegmentAsync(string prefix = null, string marker = null, int? maxresults = null, IEnumerable<ListSharesIncludeType> include = null, int? timeout = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateListSharesSegmentRequest(prefix, marker, maxresults, include, timeout);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            var headers = new ServiceListSharesSegmentHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ListSharesResponse value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("EnumerationResults") is XElement enumerationResultsElement)
                        {
                            value = ListSharesResponse.DeserializeListSharesResponse(enumerationResultsElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        ///  The List Shares Segment operation returns a list of the shares and share snapshots under the specified account.
        /// <param name="prefix"> Filters the results to return only entries whose name begins with the specified prefix. </param>
        /// <param name="marker"> A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. </param>
        /// <param name="maxresults"> Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items. </param>
        /// <param name="include"> Include this parameter to specify one or more datasets to include in the response. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public ResponseWithHeaders<ListSharesResponse, ServiceListSharesSegmentHeaders> ListSharesSegment(string prefix = null, string marker = null, int? maxresults = null, IEnumerable<ListSharesIncludeType> include = null, int? timeout = null, CancellationToken cancellationToken = default)
        {
            using var message = CreateListSharesSegmentRequest(prefix, marker, maxresults, include, timeout);
            _pipeline.Send(message, cancellationToken);
            var headers = new ServiceListSharesSegmentHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ListSharesResponse value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("EnumerationResults") is XElement enumerationResultsElement)
                        {
                            value = ListSharesResponse.DeserializeListSharesResponse(enumerationResultsElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw ClientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }

        internal HttpMessage CreateListSharesSegmentNextPageRequest(string nextLink, string prefix, string marker, int? maxresults, IEnumerable<ListSharesIncludeType> include, int? timeout)
        {
            var message = _pipeline.CreateMessage();
            var request = message.Request;
            request.Method = RequestMethod.Get;
            var uri = new RawRequestUriBuilder();
            uri.AppendRaw(_url, false);
            uri.AppendRawNextLink(nextLink, false);
            request.Uri = uri;
            request.Headers.Add("x-ms-version", _version);
            request.Headers.Add("Accept", "application/xml");
            return message;
        }

        ///  The List Shares Segment operation returns a list of the shares and share snapshots under the specified account.
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="prefix"> Filters the results to return only entries whose name begins with the specified prefix. </param>
        /// <param name="marker"> A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. </param>
        /// <param name="maxresults"> Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items. </param>
        /// <param name="include"> Include this parameter to specify one or more datasets to include in the response. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
        public async Task<ResponseWithHeaders<ListSharesResponse, ServiceListSharesSegmentHeaders>> ListSharesSegmentNextPageAsync(string nextLink, string prefix = null, string marker = null, int? maxresults = null, IEnumerable<ListSharesIncludeType> include = null, int? timeout = null, CancellationToken cancellationToken = default)
        {
            if (nextLink == null)
            {
                throw new ArgumentNullException(nameof(nextLink));
            }

            using var message = CreateListSharesSegmentNextPageRequest(nextLink, prefix, marker, maxresults, include, timeout);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
            var headers = new ServiceListSharesSegmentHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ListSharesResponse value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("EnumerationResults") is XElement enumerationResultsElement)
                        {
                            value = ListSharesResponse.DeserializeListSharesResponse(enumerationResultsElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
            }
        }

        ///  The List Shares Segment operation returns a list of the shares and share snapshots under the specified account.
        /// <param name="nextLink"> The URL to the next page of results. </param>
        /// <param name="prefix"> Filters the results to return only entries whose name begins with the specified prefix. </param>
        /// <param name="marker"> A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. </param>
        /// <param name="maxresults"> Specifies the maximum number of entries to return. If the request does not specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 items. </param>
        /// <param name="include"> Include this parameter to specify one or more datasets to include in the response. </param>
        /// <param name="timeout"> The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
        public ResponseWithHeaders<ListSharesResponse, ServiceListSharesSegmentHeaders> ListSharesSegmentNextPage(string nextLink, string prefix = null, string marker = null, int? maxresults = null, IEnumerable<ListSharesIncludeType> include = null, int? timeout = null, CancellationToken cancellationToken = default)
        {
            if (nextLink == null)
            {
                throw new ArgumentNullException(nameof(nextLink));
            }

            using var message = CreateListSharesSegmentNextPageRequest(nextLink, prefix, marker, maxresults, include, timeout);
            _pipeline.Send(message, cancellationToken);
            var headers = new ServiceListSharesSegmentHeaders(message.Response);
            switch (message.Response.Status)
            {
                case 200:
                    {
                        ListSharesResponse value = default;
                        var document = XDocument.Load(message.Response.ContentStream, LoadOptions.PreserveWhitespace);
                        if (document.Element("EnumerationResults") is XElement enumerationResultsElement)
                        {
                            value = ListSharesResponse.DeserializeListSharesResponse(enumerationResultsElement);
                        }
                        return ResponseWithHeaders.FromValue(value, headers, message.Response);
                    }
                default:
                    throw ClientDiagnostics.CreateRequestFailedException(message.Response);
            }
        }
    }
}


text:
layout: page
title: Purple Entertainment Award Ceremony
date: 2016-05-24
author: Benjamin Curry
tags: weekly links, java
status: published
summary: Sed dignissim, nulla eget blandit vestibulum.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/13/2017
  endDate: 10/17/2017
  ctyhocn: HSVHRHX
  groupCode: PEAC
published: true
---
Proin pretium efficitur est ultrices ullamcorper. Nam semper, ante id accumsan viverra, lectus magna dignissim quam, id sagittis mi enim quis ante. Integer at nunc maximus, condimentum tellus id, vulputate ex. Aliquam eu justo non risus malesuada consectetur sed luctus velit. Morbi aliquam ultricies nisl sit amet iaculis. Cras ut odio tempus eros rhoncus fringilla. Nullam tempus eros lorem. Nam sagittis nunc vel lectus hendrerit, tincidunt molestie libero finibus. Praesent tempus turpis purus, vel fringilla ipsum interdum sed. Vivamus condimentum massa quis lacus rhoncus gravida. Aliquam consectetur enim ac augue vestibulum, et faucibus justo pulvinar. Aenean sit amet neque magna. Sed eget efficitur lectus. Curabitur condimentum est ligula, id sollicitudin ante dapibus eget. Aenean interdum arcu non scelerisque sagittis.

1 In pharetra quam ut mi consequat faucibus.

Vivamus nec laoreet nibh, eu convallis arcu. Duis ullamcorper sem felis, at ornare ex sagittis et. Curabitur feugiat purus ut magna convallis aliquet. Etiam elementum suscipit condimentum. Duis malesuada nibh eget cursus lobortis. Nulla efficitur luctus accumsan. Duis rutrum mattis nibh, at vehicula risus. In ac placerat ante. Etiam non porta ligula, sed imperdiet urna. Aenean lacus est, pulvinar vitae nisl vel, faucibus suscipit risus. Donec et justo sapien. Maecenas consequat, dui sed rhoncus fermentum, tortor dui condimentum nulla, nec lacinia urna quam vitae urna. Ut suscipit fringilla tellus, ullamcorper mattis quam rutrum suscipit. Donec ex sapien, auctor quis nunc quis, tempus semper felis. Duis et augue cursus, ornare orci eu, gravida augue.


text:
I love this mock
# EasyMock
maybe you love this


text:
using Newtonsoft.Json;

namespace Jojatekok.MoneroAPI.RpcUtilities
{
    public class JsonRpcResponse<T>
    {
        [JsonProperty("result")]
        public T Result { get; private set; }

        [JsonProperty("error")]
        public JsonError Error { get; private set; }
    }
}


text:
/**
 */
package gluemodel.COSEM.COSEMObjects.impl;

import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage;
import gluemodel.COSEM.COSEMObjects.M_BusClientObject;

import gluemodel.COSEM.InterfaceClasses.impl.M_Bus_clientImpl;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'MBus Client Object'.
 *
 *
 * @generated
 */
public class M_BusClientObjectImpl extends M_Bus_clientImpl implements M_BusClientObject {
	/**
	 *
	 *
	 * @generated
	 */
	protected M_BusClientObjectImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return COSEMObjectsPackage.eINSTANCE.getM_BusClientObject();
	}

} //M_BusClientObjectImpl


text:
<?php

App::uses('AclInterface', 'Controller/Component/Acl');
App::uses('Hash', 'Utility');

/**
 * DbAcl implements an ACL control system in the database.  ARO's and ACO's are
 * structured into trees and a linking table is used to define permissions.  You
 * can install the schema for DbAcl with the Schema Shell.
 *
 * `$aco` and `$aro` parameters can be slash delimited paths to tree nodes.
 *
 * eg. `controllers/Users/edit`
 *
 * Would point to a tree structure like
 *
 * {{{
 *	controllers
 *		Users
 *			edit
 * }}}
 *
 * @package       Cake.Controller.Component.Acl
 */
class DbAcl extends Object implements AclInterface {

/**
 * Constructor
 *
 */
	public function __construct() {
		parent::__construct();
		$this->Permission = ClassRegistry::init(array('class' => 'Permission', 'alias' => 'Permission'));
		$this->Aro = $this->Permission->Aro;
		$this->Aco = $this->Permission->Aco;
	}

/**
 * Initializes the containing component and sets the Aro/Aco objects to it.
 *
 * @param AclComponent $component
 * @return void
 */
	public function initialize(Component $component) {
		$component->Aro = $this->Aro;
		$component->Aco = $this->Aco;
	}

/**
 * Checks if the given $aro has access to action $action in $aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $action Action (defaults to *)
 * @return boolean Success (true if ARO has access to action in ACO, false otherwise)
 * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#checking-permissions-the-acl-component
 */
	public function check($aro, $aco, $action = "*") {
		return $this->Permission->check($aro, $aco, $action);
	}

/**
 * Allow $aro to have access to action $actions in $aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $actions Action (defaults to *)
 * @param integer $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit)
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions
 */
	public function allow($aro, $aco, $actions = "*", $value = 1) {
		return $this->Permission->allow($aro, $aco, $actions, $value);
	}

/**
 * Deny access for $aro to action $action in $aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $action Action (defaults to *)
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions
 */
	public function deny($aro, $aco, $action = "*") {
		return $this->allow($aro, $aco, $action, -1);
	}

/**
 * Let access for $aro to action $action in $aco be inherited
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $action Action (defaults to *)
 * @return boolean Success
 */
	public function inherit($aro, $aco, $action = "*") {
		return $this->allow($aro, $aco, $action, 0);
	}

/**
 * Allow $aro to have access to action $actions in $aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $action Action (defaults to *)
 * @return boolean Success
 * @see allow()
 */
	public function grant($aro, $aco, $action = "*") {
		return $this->allow($aro, $aco, $action);
	}

/**
 * Deny access for $aro to action $action in $aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @param string $action Action (defaults to *)
 * @return boolean Success
 * @see deny()
 */
	public function revoke($aro, $aco, $action = "*") {
		return $this->deny($aro, $aco, $action);
	}

/**
 * Get an array of access-control links between the given Aro and Aco
 *
 * @param string $aro ARO The requesting object identifier.
 * @param string $aco ACO The controlled object identifier.
 * @return array Indexed array with: 'aro', 'aco' and 'link'
 */
	public function getAclLink($aro, $aco) {
		return $this->Permission->getAclLink($aro, $aco);
	}

/**
 * Get the keys used in an ACO
 *
 * @param array $keys Permission model info
 * @return array ACO keys
 */
	protected function _getAcoKeys($keys) {
		return $this->Permission->getAcoKeys($keys);
	}

}


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

namespace TextMergeTest
{
    class Class1
    {
        Branch1 Change;
        Here is abstract change from branch;
        Hello david;
        Here is another change;
    }
}


text:
module.exports = function(gulp, plugins,config,env){
  return function(){
    gulp.src(config.common.bowerDir + '/fontawesome/fonts/**.*')
        .pipe(gulp.dest('./public/ui/dashboard/fonts'));
    gulp.src(config.common.bowerDir + '/fontawesome/fonts/**.*')
        .pipe(gulp.dest('./public/ui/landingPage/fonts'));
  };
};


text:
<?php $assets = $this->app->assets; $url = $this->app->url; ?>

Blog

Blog Subtitle

Home

Blog

Gallery Post With Nice Lightbox

          <a class="lightbox" title="This is an image title" href="<?php echo $assets->images('blog-02.jpg') ?>" data-lightbox-gallery="gallery1">

            <img alt="" src="<?php echo $assets->images('blog-02.jpg') ?>">

          <a class="lightbox" title="This is an image title" href="<?php echo $assets->images('blog-03.jpg') ?>" data-lightbox-gallery="gallery1">

            <img alt="" src="<?php echo $assets->images('blog-03.jpg') ?>">

          <a class="lightbox" title="This is an image title" href="<?php echo $assets->images('blog-04.jpg') ?>" data-lightbox-gallery="gallery1">

            <img alt="" src="<?php echo $assets->images('blog-04.jpg') ?>">

Gallery Post With Nice Lightbox

By iThemesLab

December 30, 2013

WordPress, Graphic

4 Comments

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.

        Theme
        Mobile
        Design
        Wordpress
        Jquery

        Share This Post:

       <img alt="" src="<?php echo $assets->images('author.png') ?>" />

About The Author

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia desrut mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.

(4) Comments

<img alt="" src="<?php echo $assets->images('avatar.png') ?>" />

           John Doe
           February 15, 2013 at 11:39 pm
           Reply

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia desrut mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.

<img alt="" src="<?php echo $assets->images('avatar.png') ?>" />

              John Doe
              February 15, 2013 at 11:39 pm
              Reply

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

<img alt="" src="<?php echo $assets->images('avatar.png') ?>" />

                  John Doe
                  February 15, 2013 at 11:39 pm
                  Reply

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi.

<img alt="" src="<?php echo $assets->images('avatar.png') ?>" />

         John Doe
         February 15, 2013 at 11:39 pm
         Reply

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia desrut mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.

Leave a reply

 <form action="#">

       Name*
       <input id="author" name="author" type="text" value="" size="30" aria-required="true">

       Email*
       <input id="email" name="author" type="text" value="" size="30" aria-required="true">

       Website*
       <input id="url" name="url" type="text" value="" size="30" aria-required="true">

      Add Your Comment
      <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>
      <input name="submit" type="submit" id="submit" value="Submit Comment">

</form>

   <form action="#">
    <input type="search" placeholder="Enter Keywords..." />
    <button class="search-btn" type="submit"></button>
  </form>

Categories

   Brandign

   Design

   Development

   Graphic

Popular Post

     <img src="<?php echo $assets->images('blog-mini-01.jpg') ?>" alt="" />

How To Download The Google Fonts Catalog

     Jul 29 2013

     <img src="<?php echo $assets->images('blog-mini-02.jpg') ?>" alt="" />

How To Download The Google Fonts Catalog

     Jul 29 2013

     <img src="<?php echo $assets->images('blog-mini-03.jpg') ?>" alt="" />

How To Download The Google Fonts Catalog

     Jul 29 2013

Video

Tags

   Portfolio
   Theme
   Mobile
   Design
   Wordpress
   Jquery
   CSS
   Modern
   Theme
   Icons
   Google


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "equipment_models".
 *
 * @property integer $id
 * @property string $model
 * @property integer $brand_id
 * @property integer $is_allowed
 */
class EquipmentModels extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'equipment_models';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['id', 'brand_id', 'is_allowed'], 'integer'],
            [['model'], 'string', 'max' => 45]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'model' => Yii::t('app', 'Model'),
            'brand_id' => Yii::t('app', 'Brand ID'),
            'is_allowed' => Yii::t('app', 'Is Allowed'),
        ];
    }
}


text:
{% extends "banner_base.html" %}

{% load i18n %}

{% block head_title %}{% trans "Welcome" %}{% endblock %}

{% block body_class %}home{% endblock %}

{% block banner %}

{% trans "Welcome to IPython Notebook Server v1.0" %}

    {% if user.is_authenticated %}

{% blocktrans %}IPython Notebook Server is ready!

	Vist the settings page to grab the server password and run it.
        {% endblocktrans %}

    {% else %}
        {% url account_login as login_url %}
        {% url account_signup as signup_url %}

{% blocktrans %}You can Log In  to try out the Ipython Notebook Server.{% endblocktrans %}

    {% endif %}
{% endblock %}


text:
package java.awt;

import java.awt.event.*;

import java.lang.annotation.Native;

/**
 * The interface for objects which have an adjustable numeric value
 * contained within a bounded range of values.
 *
 * @author Amy Fowler
 * @author Tim Prinzing
 */
public interface Adjustable {

    /**
     * Indicates that the Adjustable has horizontal orientation.
     */
    @Native public static final int HORIZONTAL = 0;

    /**
     * Indicates that the Adjustable has vertical orientation.
     */
    @Native public static final int VERTICAL = 1;

    /**
     * Indicates that the Adjustable has no orientation.
     */
    @Native public static final int NO_ORIENTATION = 2;

    /**
     * Gets the orientation of the adjustable object.
     * @return the orientation of the adjustable object;
     *   either HORIZONTAL, VERTICAL,
     *   or NO_ORIENTATION
     */
    int getOrientation();

    /**
     * Sets the minimum value of the adjustable object.
     * @param min the minimum value
     */
    void setMinimum(int min);

    /**
     * Gets the minimum value of the adjustable object.
     * @return the minimum value of the adjustable object
     */
    int getMinimum();

    /**
     * Sets the maximum value of the adjustable object.
     * @param max the maximum value
     */
    void setMaximum(int max);

    /**
     * Gets the maximum value of the adjustable object.
     * @return the maximum value of the adjustable object
     */
    int getMaximum();

    /**
     * Sets the unit value increment for the adjustable object.
     * @param u the unit increment
     */
    void setUnitIncrement(int u);

    /**
     * Gets the unit value increment for the adjustable object.
     * @return the unit value increment for the adjustable object
     */
    int getUnitIncrement();

    /**
     * Sets the block value increment for the adjustable object.
     * @param b the block increment
     */
    void setBlockIncrement(int b);

    /**
     * Gets the block value increment for the adjustable object.
     * @return the block value increment for the adjustable object
     */
    int getBlockIncrement();

    /**
     * Sets the length of the proportional indicator of the
     * adjustable object.
     * @param v the length of the indicator
     */
    void setVisibleAmount(int v);

    /**
     * Gets the length of the proportional indicator.
     * @return the length of the proportional indicator
     */
    int getVisibleAmount();

    /**
     * Sets the current value of the adjustable object. If
     * the value supplied is less than minimum
     * or greater than maximum - visibleAmount,
     * then one of those values is substituted, as appropriate.
     *

     * Calling this method does not fire an
     * AdjustmentEvent.
     *
     * @param v the current value, between minimum
     *    and maximum - visibleAmount
     */
    void setValue(int v);

    /**
     * Gets the current value of the adjustable object.
     * @return the current value of the adjustable object
     */
    int getValue();

    /**
     * Adds a listener to receive adjustment events when the value of
     * the adjustable object changes.
     * @param l the listener to receive events
     * @see AdjustmentEvent
     */
    void addAdjustmentListener(AdjustmentListener l);

    /**
     * Removes an adjustment listener.
     * @param l the listener being removed
     * @see AdjustmentEvent
     */
    void removeAdjustmentListener(AdjustmentListener l);

}


text:
<?php

namespace AppBundle\Entity;

/**
 * Organizacja
 */
class Organizacja
{
    /**
     * @var string
     */
    private $shortName;

    /**
     * @var string
     */
    private $fullName;

    /**
     * @var string
     */
    private $city;

    /**
     * @var string
     */
    private $email;

    /**
     * @var string
     */
    private $contactPerson;

    /**
     * @var integer
     */
    private $id;

    /**
     * Set shortName
     *
     * @param string $shortName
     *
     * @return Organizacja
     */
    public function setShortName($shortName)
    {
        $this->shortName = $shortName;

        return $this;
    }

    /**
     * Get shortName
     *
     * @return string
     */
    public function getShortName()
    {
        return $this->shortName;
    }

    /**
     * Set fullName
     *
     * @param string $fullName
     *
     * @return Organizacja
     */
    public function setFullName($fullName)
    {
        $this->fullName = $fullName;

        return $this;
    }

    /**
     * Get fullName
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->fullName;
    }

    /**
     * Set city
     *
     * @param string $city
     *
     * @return Organizacja
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return Organizacja
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set contactPerson
     *
     * @param string $contactPerson
     *
     * @return Organizacja
     */
    public function setContactPerson($contactPerson)
    {
        $this->contactPerson = $contactPerson;

        return $this;
    }

    /**
     * Get contactPerson
     *
     * @return string
     */
    public function getContactPerson()
    {
        return $this->contactPerson;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
}