text:
package ru.istolbov.obt;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * OrderBook.
 * Created by istolbov on 24.05.2017.
 */
public class OrderBook {
    /**
     * name.
     */
    private final String name;
    /**
     * keysMap.
     */
    Map<Integer, Order> keysMap = new HashMap<>();
    /**
     * asks.
     */
    TreeMap<Float, Integer> asks = new TreeMap<>();
    /**
     * bids.
     */
    TreeMap<Float, Integer> bids = new TreeMap<>(new Comparator<Float>() {

        @Override
        public int compare(Float o1, Float o2) {
            return -o1.compareTo(o2);
        }
    });

    /**
     * constructor.
     * @param name - name
     */
    public OrderBook(String name) {
        this.name = name;
    }

    /**
     * getName.
     * @return name
     */
    public String getName() {
        return this.name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
mkdir -p "$PREFIX/lib/arb/lib"
for fn in libARBDB libCORE arb_tcp.dat; do
    mv install/lib/arb/lib/$fn* "$PREFIX/lib/arb/lib"
done

mkdir -p "${PREFIX}/etc/conda/activate.d"
mkdir -p "${PREFIX}/etc/conda/deactivate.d"
cp "$RECIPE_DIR/activate.sh" "$PREFIX/etc/conda/activate.d/arb_home.sh"
cp "$RECIPE_DIR/deactivate.sh" "$PREFIX/etc/conda/deactivate.d/arb_home.sh"


text:
Tool
CPAchecker 1.4-svn 15944M

Limits
timelimit: 10 s, memlimit: 3000 MB, CPU core limit: 1

Host
tortuga

OS
Linux 3.13.0-45-generic x86_64

System
CPU: Intel Core i7-2600 CPU @ 3.40GHz, cores: 8, frequency: 3401 MHz; RAM: 16389384 kB

Date of execution
2015-03-03 16:13:02 CET

Run set
predicateAnalysis
valueAnalysis

Options
-noout -setprop log.consoleLevel=WARNING -predicateAnalysis
-noout -setprop log.consoleLevel=WARNING -valueAnalysis

benchexec/tablegenerator/test_integration/results/
status
cputime (s)
walltime (s)
memUsage
status
cputime (s)
walltime (s)
memUsage

test/programs/simple/bitvectors/implicitunsignedconversion_false-unreach-label.i
unreach-label
true
2.17
2.18
128032768
false(reach)
2.12
2.13
133574656

test/programs/simple/compoundLiteral_true-unreach-label.c
unreach-label
true
2.23
2.24
132337664
unknown
2.20
2.21
130293760

test/programs/simple/builtin_expect_true-unreach-label.c
unreach-label
true
2.06
2.07
126312448
-

benchexec/tablegenerator/test_integration/results/
status
cputime (s)
walltime (s)
memUsage
status
cputime (s)
walltime (s)
memUsage

total
3
6.46
6.48
386682880
2
4.32
4.34
263868416

    correct results
2
4.29
4.30
258650112
1
2.12
2.13
133574656

        correct true
2
4.29
4.30
258650112
0

        correct false
0

1
2.12
2.13
133574656

    incorrect results
1
2.17
2.18
128032768
0

        incorrect true
1
2.17
2.18
128032768
0

        incorrect false
0

0

score (3 tasks, max score: 5)
-28

1

Run set
predicateAnalysis
valueAnalysis


text:
'use strict';

angular.module('core').directive('phraseEntry', [
	function() {
        function link(scope, element, attrs) {
            scope.SavePhrase = function() {
                scope.save();
            };
        }

		return {
			templateUrl: 'modules/core/views/directives/phraseentry.view.html',
			restrict: 'E',
            scope: {
                phrase: '=',
                save: '&'
            },
			link: link
		};
	}
]);


text:
import Event from "../../events/event.js";

function triggerBeforeInsert(args) {
  const { doc, stopOnFirstError, fields, simulation, trusted } = args;
  // Trigger the "beforeInsert" event handlers.
  if (
    !doc.dispatchEvent(
      new Event("beforeInsert", {
        cancelable: true,
        propagates: true,
        doc,
        stopOnFirstError,
        fields,
        simulation,
        trusted
      })
    )
  ) {
    // If an event was prevented, then we stop here.
    throw new Meteor.Error("prevented", "Operation prevented", {
      eventName: "beforeInsert"
    });
  }
}

export default triggerBeforeInsert;


text:
namespace gl
{
////////////////////////////////////////

/// @brief Write the current framebuffer to a PNG file.
void png_write( const char *file_name, size_t w, size_t h, size_t c );

void png_write_data(
    const char *   file_name,
    size_t         w,
    size_t         h,
    size_t         c,
    const uint8_t *buf,
    bool           flip );

/// @brief Load the PNG file into a texture.
gl::texture png_read( const char *file_name );

////////////////////////////////////////

} // namespace gl


text:
package com.pushtorefresh.storio.contentresolver.queries;

import android.net.Uri;

import com.pushtorefresh.storio.contentresolver.BuildConfig;
import com.pushtorefresh.storio.test.ToStringChecker;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import nl.jqno.equalsverifier.EqualsVerifier;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

@RunWith(RobolectricGradleTestRunner.class) // Required for correct Uri impl
@Config(constants = BuildConfig.class, sdk = 21)
public class QueryTest {

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullUriObject() {
        //noinspection ConstantConditions
        Query.builder()
                .uri((Uri) null)
                .build();
    }

    @Test(expected = NullPointerException.class)
    public void shouldNotAllowNullUriString() {
        //noinspection ConstantConditions
        Query.builder()
                .uri((String) null)
                .build();
    }

    @Test
    public void columnsShouldNotBeNull() {
        Query query = Query.builder()
                .uri(mock(Uri.class))
                .build();

        assertNotNull(query.columns());
        assertTrue(query.columns().isEmpty());
    }

    @Test
    public void whereClauseShouldNotBeNull() {
        Query query = Query.builder()
                .uri(mock(Uri.class))
                .build();

        assertNotNull(query.where());
        assertEquals("", query.where());
    }

    @Test
    public void whereArgsShouldNotBeNull() {
        Query query = Query.builder()
                .uri(mock(Uri.class))
                .build();

        assertNotNull(query.whereArgs());
        assertTrue(query.whereArgs().isEmpty());
    }

    @Test
    public void sortOrderShouldNotBeNull() {
        Query query = Query.builder()
                .uri(mock(Uri.class))
                .build();

        assertNotNull(query.sortOrder());
        assertEquals("", query.sortOrder());
    }

    @Test
    public void buildWithNormalValues() {
        final Uri uri = mock(Uri.class);
        final String[] columns = {"1", "2", "3"};
        final String where = "test_where";
        final Object[] whereArgs = {"arg1", "arg2", "arg3"};
        final String sortOrder = "test_order";

        final Query query = Query.builder()
                .uri(uri)
                .columns(columns)
                .where(where)
                .whereArgs(whereArgs)
                .sortOrder(sortOrder)
                .build();

        assertEquals(uri, query.uri());
        assertEquals(asList(columns), query.columns());
        assertEquals(where, query.where());
        assertEquals(asList(whereArgs), query.whereArgs());
        assertEquals(sortOrder, query.sortOrder());
    }

    @Test
    public void verifyEqualsAndHashCodeImplementation() {
        EqualsVerifier
                .forClass(Query.class)
                .allFieldsShouldBeUsed()
                .withPrefabValues(Uri.class, Uri.parse("content://1"), Uri.parse("content://2"))
                .verify();
    }

    @Test
    public void checkToStringImplementation() {
        ToStringChecker
                .forClass(Query.class)
                .check();
    }
}


text:
package com.christhoma.commuted;

import android.support.annotation.DrawableRes;
import android.util.Log;

import java.util.Random;

public class ImageProvider {

    static Random random = new Random();
    @DrawableRes
    static int[] firstBucket = {
            R.drawable.img_1858,
            R.drawable.img_1859,
            R.drawable.img_1860,
            R.drawable.img_1861,
            R.drawable.img_1862,
            R.drawable.img_1863,
            R.drawable.img_1864
    };
    @DrawableRes
    static int[] secondBucket = {
            R.drawable.img_1865,
            R.drawable.img_1866,
            R.drawable.img_1867,
            R.drawable.img_1868,
            R.drawable.img_1869,
            R.drawable.img_1870,
            R.drawable.img_1871
    };
    @DrawableRes
    static int[] thirdBucket = {
            R.drawable.img_1872,
            R.drawable.img_1873,
            R.drawable.img_1874,
            R.drawable.img_1875,
            R.drawable.img_1876,
            R.drawable.img_1877,
            R.drawable.img_1878
    };
    @DrawableRes
    static int[] fourthBucket = {
            R.drawable.img_1880,
            R.drawable.img_1881,
            R.drawable.img_1882,
            R.drawable.img_1886,
            R.drawable.img_1887,
            R.drawable.img_1888,
            R.drawable.img_1889
    };
    @DrawableRes
    static int[] fifthBucket = {
            R.drawable.img_1891,
            R.drawable.img_1892,
            R.drawable.img_1893,
            R.drawable.img_1894,
            R.drawable.img_1895,
            R.drawable.img_1896,
            R.drawable.img_1897
    };
    @DrawableRes
    static int[] sixthBucket = {
            R.drawable.img_1898,
            R.drawable.img_1899,
            R.drawable.img_1900,
            R.drawable.img_1901,
            R.drawable.img_1902,
            R.drawable.img_1903,
            R.drawable.img_1904
    };
    @DrawableRes
    static int[] seventhBucket = {
            R.drawable.img_1906,
            R.drawable.img_1907,
            R.drawable.img_1908,
            R.drawable.img_1909,
            R.drawable.img_1910,
            R.drawable.img_1911,
            R.drawable.img_1912
    };
    @DrawableRes
    static int[] eighthBucket = {
            R.drawable.img_1913,
            R.drawable.img_1914,
            R.drawable.img_1915,
            R.drawable.img_1916,
            R.drawable.img_1917
    };
    @DrawableRes
    static int[] ninthBucket = {
            R.drawable.img_1918,
            R.drawable.img_1919,
            R.drawable.img_1920,
            R.drawable.img_1921,
            R.drawable.img_1912,
            R.drawable.img_1923
    };

    private static final String TAG = "ImageProvider";

    @DrawableRes
    public static int getImageForBucket(int bucket) {
        int itemId;
        switch (bucket) {
            case 1:
                itemId = random.nextInt(firstBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return firstBucket[itemId];
            case 2:
                itemId = random.nextInt(secondBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return secondBucket[itemId];
            case 3:
                itemId = random.nextInt(thirdBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return thirdBucket[itemId];
            case 4:
                itemId = random.nextInt(fourthBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return fourthBucket[itemId];
            case 5:
                itemId = random.nextInt(fifthBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return fifthBucket[itemId];
            case 6:
                itemId = random.nextInt(sixthBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return sixthBucket[itemId];
            case 7:
                itemId = random.nextInt(seventhBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return seventhBucket[itemId];
            case 8:
                itemId = random.nextInt(eighthBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return eighthBucket[itemId];
            case 9:
                itemId = random.nextInt(ninthBucket.length - 1);
                Log.d(TAG, "getImageForBucket: " + itemId);
                return ninthBucket[itemId];
            default:
                return 0;
        }
    }
}


text:
package entry

import (
	"fmt"
	"github.com/braintree/manners"
	"github.com/pufferpanel/apufferi/v4/logging"
	"github.com/pufferpanel/pufferd/v2"
	"github.com/pufferpanel/pufferd/v2/environments"
	"github.com/pufferpanel/pufferd/v2/programs"
	"github.com/pufferpanel/pufferd/v2/routing"
	"github.com/pufferpanel/pufferd/v2/sftp"
	"github.com/pufferpanel/pufferd/v2/shutdown"
	"github.com/spf13/viper"
	"os"
	"os/signal"
	"runtime/debug"
	"syscall"
)

var runService = true

func Start() chan error {
	errChan := make(chan error)
	go entry(errChan)
	return errChan
}

func entry(errChan chan error) {
	logging.Info(pufferd.Display)

	environments.LoadModules()
	programs.Initialize()

	var err error

	if _, err = os.Stat(programs.ServerFolder); os.IsNotExist(err) {
		logging.Info("No server directory found, creating")
		err = os.MkdirAll(programs.ServerFolder, 0755)
		if err != nil && !os.IsExist(err) {
			errChan <- err
			return
		}
	}

	programs.LoadFromFolder()

	programs.InitService()

	for _, element := range programs.GetAll() {
		if element.IsEnabled() {
			element.GetEnvironment().DisplayToConsole(true, "Daemon has been started\n")
			if element.IsAutoStart() {
				logging.Info("Queued server %s", element.Id())
				element.GetEnvironment().DisplayToConsole(true, "Server has been queued to start\n")
				programs.StartViaService(element)
			}
		}
	}

	createHook()

	for runService && err == nil {
		err = runServices()
	}

	shutdown.Shutdown()

	errChan <- err
	return
}

func runServices() error {
	defer recoverPanic()

	router := routing.ConfigureWeb()

	useHttps := false

	httpsPem := viper.GetString("listen.webCert")
	httpsKey := viper.GetString("listen.webKey")

	if _, err := os.Stat(httpsPem); os.IsNotExist(err) {
		logging.Warn("No HTTPS.PEM found in data folder, will use http instead")
	} else if _, err := os.Stat(httpsKey); os.IsNotExist(err) {
		logging.Warn("No HTTPS.KEY found in data folder, will use http instead")
	} else {
		useHttps = true
	}

	sftp.Run()

	web := viper.GetString("listen.web")

	logging.Info("Starting web access on %s", web)
	var err error
	if useHttps {
		err = manners.ListenAndServeTLS(web, httpsPem, httpsKey, router)
	} else {
		err = manners.ListenAndServe(web, router)
	}

	return err
}

func createHook() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGPIPE)
	go func() {
		defer func() {
			if err := recover(); err != nil {
				logging.Error("%+v\n%s", err, debug.Stack())
			}
		}()

		var sig os.Signal

		for sig != syscall.SIGTERM {
			sig = <-c
			switch sig {
			case syscall.SIGHUP:
				//manners.Close()
				//sftp.Stop()
				_ = pufferd.LoadConfig()
			case syscall.SIGPIPE:
				//ignore SIGPIPEs for now, we're somehow getting them and it's causing issues
			}
		}

		runService = false
		shutdown.CompleteShutdown()
	}()
}

func recoverPanic() {
	if rec := recover(); rec != nil {
		err := rec.(error)
		fmt.Printf("CRITICAL: %s", err.Error())
		logging.Critical("Unhandled error: %s", err.Error())
	}
}


text:
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from mock import MagicMock
from thecut.forms.utils import add_css_class

class TestAddCssClass(TestCase):
    def test_add_new_css_class(self):
        widget = MagicMock()
        widget.attrs = {'class': 'a b'}
        widget = add_css_class(widget, 'c')
        self.assertEqual(set(widget.attrs.get('class', '').split()),
                         {'a', 'b', 'c'})

    def test_add_existing_css_class(self):
        widget = MagicMock()
        widget.attrs = {'class': 'a b'}
        widget = add_css_class(widget, 'b')
        self.assertEqual(set(widget.attrs.get('class', '').split()),
                         {'a', 'b'})


text:
CloudX-for-Windows
==================

CloudX for Windows


text:
Returns the wrapper's underlying nodes.

#### Returns

`Array<ReactElement>`: The retrieved nodes.

#### Examples

```jsx
class Test extends React.Component {
  render() {
    return (
      <div>
        <span />
        <span />
      </div>
    );
  }
}

const wrapper = mount(<Test />);
expect(wrapper.find('span').getNodes()).to.have.lengthOf(2);
```

#### Related Methods

- [`.getNode() => ReactElement`](getNode.md)


text:
require "amqp"

AMQP.start(:host => "localhost") do |connection|
  channel = AMQP::Channel.new(connection)
  queue   = channel.queue("task_queue", :durable => true)

  Signal.trap("INT") do
    connection.close do
      EM.stop { exit }
    end
  end

  puts " [*] Waiting for messages. To exit press CTRL+C"

  channel.prefetch(1)
  queue.subscribe(:ack => true) do |header, body|
    puts " [x] Received #{body}"
    EM.add_timer(body.count(".")) do
      puts " [x] Done"
      header.ack
    end
  end
end


text:
<?php

namespace Drupal\Tests\aggregator\Functional;

/**
 * Tests the fetcher plugins functionality and discoverability.
 *
 * @group aggregator
 * @group legacy
 *
 * @see \Drupal\aggregator_test\Plugin\aggregator\fetcher\TestFetcher.
 */
class FeedFetcherPluginTest extends AggregatorTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    // Enable test plugins.
    $this->enableTestPlugins();
    // Create some nodes.
    $this->createSampleNodes();
  }

  /**
   * Tests fetching functionality.
   */
  public function testfetch() {
    // Create feed with local url.
    $feed = $this->createFeed();
    $this->updateFeedItems($feed);
    $this->assertNotEmpty($feed->items);

    // Delete items and restore checked property to 0.
    $this->deleteFeedItems($feed);
    // Change its name and try again.
    $feed->setTitle('Do not fetch');
    $feed->save();
    $this->updateFeedItems($feed);
    // Fetch should fail due to feed name.
    $this->assertEmpty($feed->items);
  }

}


text:
{{model.thread.name}}

 0">
                        {{'MESSAGES_NO_MESSAGES' | translate}}

 0">

                            <div class="bubble"
                                 ng-class="{
                                    'bubble-left': message.from.id === model.thread.id,
                                    'bubble-right': message.from.id !== model.thread.id,
                                    'bubble-left-marked': message.from.id === model.thread.id && message.isRead === false,
                                    'bubble-right-marked': message.from.id !== model.thread.id && message.isRead === false
                                    }">

                                    {{message.title}}{{delimiter(message)}}
                                    {{'MESSAGES_RECEIVED' | translate}}
                                    {{message.sendDate | amDateFormat:'L'}}

                                    {{message.text}}

                    <button id="new-message-button"
                            class="button"
                            ng-click="newMessage()">
                        {{ 'MESSAGES_NEW_MESSAGE_BUTTON' | translate }}
                    </button>


text:
#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__
#define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__

#include <aleph/geometry/distances/Traits.hh>

#include <aleph/math/Statistics.hh>

#include <algorithm>
#include <map>
#include <stdexcept>
#include <vector>

#include <cmath>

namespace aleph
{

namespace containers
{

/*
 Wrapper class for representing a sequence of correlation dimension
 integral values. I want the interface to be as clear as possible.
*/

struct CorrelationDimensionSequence
{
  std::vector<double> x;
  std::vector<double> y;
};

/**
  Calculates samples of the correlation dimension integral for a given
  point cloud. This does *not* yet result in a dimension estimate, but
  only produces a set of points.
*/

template <
  class Distance,
  class Container
> CorrelationDimensionSequence correlationDimensionIntegral(
  const Container& container,
  Distance dist = Distance() )
{
  auto n = container.size();
  auto d = container.dimension();

  std::map<double, unsigned> distances;

  aleph::geometry::distances::Traits<Distance> traits;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto&& p = container[i];

    for( decltype(n) j = i+1; j < n; j++ )
    {
      auto&& q      = container[j];
      auto distance = dist( p.begin(),
                            q.begin(),
                            d );

      distances[ traits.from( distance ) ] += 1;
    }
  }

  CorrelationDimensionSequence cds;
  cds.x.reserve( distances.size() );
  cds.y.reserve( distances.size() );

  // Determine the correlation dimension integral for all potential
  // values. This only requires counting how many *pairs* have been
  // seen by the algorithm.

  unsigned seen = 0;
  for( auto&& pair : distances )
  {
    auto&& distance = pair.first;
    auto&& count    = pair.second;

    seen += count;

    if( distance > 0 )
    {
      cds.x.push_back( distance );
      cds.y.push_back( seen / ( static_cast<double>( n * (n-1) ) * 0.5 ) );
    }
  }

  return cds;
}

/**
  Estimates the correlation dimension from a correlation dimension
  sequence, which involves calculating a log-log plot of the data,
  and determining the best coefficient for a linear fit.
*/

double correlationDimension( const CorrelationDimensionSequence& cds )
{
  if( cds.x.size() != cds.y.size() )
    throw std::runtime_error( "Inconsistent correlation dimension sequence" );

  std::vector<double> X;
  std::vector<double> Y;

  X.reserve( cds.x.size() );
  Y.reserve( cds.y.size() );

  auto log = [] ( double x )
  {
    return std::log( x );
  };

  std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log );
  std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log );

  // This is a simple linear regression model. We are only interested in
  // the slope of the regression line, so this is sufficient.

  auto cov
    = aleph::math::sampleCovariance( X.begin(), X.end(),
                                     Y.begin(), Y.end() );

  auto var
    = aleph::math::sampleVariance( X.begin(), X.end() );

  return cov / var;
}

} // namespace containers

} // namespace aleph

#endif


text:
import os

from telegram.parsemode import ParseMode
from src.utils import read_to_string
from . import Base

class Help(Base):
    name = 'help'
    text = read_to_string(os.path.join('resources', 'info', 'help.md'))

    def execute(self, command):
        self.reply(command, self.text, parse_mode=ParseMode.MARKDOWN)


text:
BEGIN;
INSERT INTO t1 VALUES(NULL, randomblob(100+E(pid)));


text: java -jar Toast.jar -sim


text:
/**
 * Ported to node.js by Wentao Shang
 */

/*
 * Create a DynamicBuffer where this.array is a Buffer of size length.
 * If length is not supplied, use a default initial length.
 * The methods will update this.length.
 * To access the array, use this.array or call subarray.
 */
var DynamicBuffer = function DynamicBuffer(length) {
    if (!length)
        length = 16;

    this.array = new Buffer(length);
    this.length = length;
};

exports.DynamicBuffer = DynamicBuffer;

/*
 * Ensure that this.array has the length, reallocate and copy if necessary.
 * Update this.length which may be greater than length.
 */
DynamicBuffer.prototype.ensureLength = function(length) {
    if (this.array.length >= length)
        return;

    // See if double is enough.
    var newLength = this.array.length * 2;
    if (length > newLength)
        // The needed length is much greater, so use it.
        newLength = length;

    var newArray = new Buffer(newLength);
    this.array.copy(newArray);
    this.array = newArray;
    this.length = newLength;
};

/*
 * Call this.array.set(value, offset), reallocating if necessary.
 */
DynamicBuffer.prototype.set = function(value, offset) {
    this.ensureLength(value.length + offset);
    value.copy(this.array, offset);
};

/*
 * Return this.array.subarray(begin, end);
 */
DynamicBuffer.prototype.subarray = function(begin, end) {
    return this.array.slice(begin, end);
};

/*
 * The same as subarray()
 */
DynamicBuffer.prototype.slice = function(begin, end) {
    return this.array.slice(begin, end);
};


text:
shared_examples 'cluster application core specs' do |application_name|
  it { is_expected.to belong_to(:cluster) }
  it { is_expected.to validate_presence_of(:cluster) }

  describe '#name' do
    it 'is .application_name' do
      expect(subject.name).to eq(described_class.application_name)
    end

    it 'is recorded in Clusters::Cluster::APPLICATIONS' do
      expect(Clusters::Cluster::APPLICATIONS[subject.name]).to eq(described_class)
    end
  end

  describe 'status state machine' do
    describe '#make_installing' do
      subject { create(application_name, :scheduled) }

      it 'is installing' do
        subject.make_installing!

        expect(subject).to be_installing
      end
    end

    describe '#make_installed' do
      subject { create(application_name, :installing) }

      it 'is installed' do
        subject.make_installed

        expect(subject).to be_installed
      end
    end

    describe '#make_errored' do
      subject { create(application_name, :installing) }
      let(:reason) { 'some errors' }

      it 'is errored' do
        subject.make_errored(reason)

        expect(subject).to be_errored
        expect(subject.status_reason).to eq(reason)
      end
    end

    describe '#make_scheduled' do
      subject { create(application_name, :installable) }

      it 'is scheduled' do
        subject.make_scheduled

        expect(subject).to be_scheduled
      end

      describe 'when was errored' do
        subject { create(application_name, :errored) }

        it 'clears #status_reason' do
          expect(subject.status_reason).not_to be_nil

          subject.make_scheduled!

          expect(subject.status_reason).to be_nil
        end
      end
    end
  end
end


text:
(function() {
  'use strict';

  // login
  angular
    .module('app.auth')
    .controller('authLoginController', authLoginController);

  /** @ngInject **/
  function authLoginController($log, $state, $q, $auth, AuthLoginData, AUTH_REDIRECT, Toast) {
    var vm = this;
    var next;
    vm.login = login;
    vm.meta = AuthLoginData.options();
    vm.loading = true;

    activate();

    ////////////////

    function activate() {
      $q.when(vm.meta)
        .finally(function() {
          vm.loading = false;
        });

      var fallbackNext = {
        name:   AUTH_REDIRECT.postLogin,
        params: {}
      };

      next = $state.params.next || fallbackNext;
      next = next.name === 'auth.logout' ? fallbackNext : next;
    }

    function login(credentials) {
      return $auth.login(credentials)
                  .then(Toast.resolve.success('Signed in'))
                  .then(function(response) {
                    $state.go(next.name, next.params);
                    return response;
                  })
                  .catch(Toast.reject.error('Authentication failed.'))
                  .catch(function(error) {
                    $log.error('authLogin.controller error:', error);
                    return $q.reject(error);
                  });
    }
  }

})();


text:
using System.IO;
using Newtonsoft.Json;

namespace Realmius.Contracts.Helpers
{
    internal class DepthAwareJsonTextWriter : JsonTextWriter
    {
        public DepthAwareJsonTextWriter(TextWriter textWriter) : base(textWriter) { }

        public int CurrentDepth { get; private set; }

        public override void WriteStartObject()
        {
            CurrentDepth++;
            base.WriteStartObject();
        }

        public override void WriteEndObject()
        {
            CurrentDepth--;
            base.WriteEndObject();
        }
    }
}


text:
module Lobbyist
  module V2

    class EmailInvitation < Lobbyist::V2::Base
      attr_accessor :id, :contact_id, :status, :attempts, :max_attempts, :created_at
      attr_accessor :updated_at, :email_key, :accessed_at

      def self.list(company_id, params = {})
        create_collection_from_response(get("/v2/companies/#{company_id}/email_invitations.json", params))
      end

      def self.create(company_id, params = {})
        create_from_response(post("/v2/companies/#{company_id}/email_invitations.json", {'email_invitation' => params}))
      end

      def self.reset(id, company_id, params = {})
        create_from_response(put("/v2/companies/#{company_id}/email_invitations/#{id}/reset", {contact: params}))
      end

      def self.find_by_email_key(email_key, params = {})
        create_from_response(get("/v2/email_invitations/find_by_email_key/#{email_key}", params))
      end

      def self.update(id, params = {})
        create_from_response(put("/v2/email_invitations/update/#{id}", {'email_invitation' => params}))
      end
    end

  end
end


text:
/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifndef TAGLIB_ID3V2SYNCHDATA_H
#define TAGLIB_ID3V2SYNCHDATA_H

#include "tbytevector.h"
#include "taglib.h"

namespace TagLib {

  namespace ID3v2 {

    //! A few functions for ID3v2 synch safe integer conversion

    /*!
     * In the ID3v2.4 standard most integer values are encoded as "synch safe"
     * integers which are encoded in such a way that they will not give false
     * MPEG syncs and confuse MPEG decoders.  This namespace provides some
     * methods for converting to and from these values to ByteVectors for
     * things rendering and parsing ID3v2 data.
     */

    namespace SynchData
    {
      /*!
       * This returns the unsigned integer value of \a data where \a data is a
       * ByteVector that contains a \e synchsafe integer (Structure,
       * 6.2).  The default \a length of
       * 4 is used if another value is not specified.
       */
      TAGLIB_EXPORT uint toUInt(const ByteVector &data);

      /*!
       * Returns a 4 byte (32 bit) synchsafe integer based on \a value.
       */
      TAGLIB_EXPORT ByteVector fromUInt(uint value);

      /*!
       * Convert the data from unsynchronized data to its original format.
       */
      TAGLIB_EXPORT ByteVector decode(const ByteVector &input);
    }

  }
}

#endif


text:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ConnectionService } from './../../providers/connection-service/connection-service';

@Component({
  templateUrl: 'build/pages/generated-test/generated-test.html',
})
export class GeneratedTestPage {
  constructor(private nav: NavController, private connecionService: ConnectionService) {}

  buscarCep() : void{
    this.connecionService.getCep('24756660')
      .then((res) => {
        let json = res.json();

        console.log(json);
      }).catch((err)=>{
        console.log(err);
      });
  }
}


text:
<?php

namespace Biz\Course\Event;

use Biz\Task\Service\TaskService;
use Biz\System\Service\LogService;
use Biz\Course\Service\CourseService;
use Biz\Course\Service\MemberService;
use Codeages\Biz\Framework\Event\Event;
use Biz\Course\Service\CourseSetService;
use Codeages\PluginBundle\Event\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class StatisticsSubscriber extends EventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'course.task.create' => 'onTaskCreate',
            'course.task.update' => 'onTaskUpdate',
            'course.task.delete' => 'onTaskDelete',
            'course.task.publish' => 'onPublishTaskNumberChange',
            'course.task.unpublish' => 'onPublishTaskNumberChange',

            'course.thread.create' => 'onCourseThreadChange',
            'course.thread.delete' => 'onCourseThreadChange',

            'course.review.add' => 'onReviewNumberChange',
            'course.review.update' => 'onReviewNumberChange',
            'course.review.delete' => 'onReviewNumberChange',

            'course.marketing.update' => 'onCourseMarketingChange',
            'course.publish' => 'onCourseStatusChange',
            'course.close' => 'onCourseStatusChange',
        );
    }

    public function onCourseMarketingChange(Event $event)
    {
        $subject = $event->getSubject();
        $course = $subject['newCourse'];
        $this->getCourseSetService()->updateCourseSetMinAndMaxPublishedCoursePrice($course['courseSetId']);
    }

    public function onCourseStatusChange(Event $event)
    {
        $course = $event->getSubject();
        $this->getCourseSetService()->updateCourseSetMinAndMaxPublishedCoursePrice($course['courseSetId']);
        $this->getCourseSetService()->updateCourseSetDefaultCourseId($course['courseSetId']);
    }

    public function onTaskCreate(Event $event)
    {
        $this->onTaskNumberChange($event, array('taskNum'));
    }

    public function onTaskUpdate(Event $event)
    {
        $newTask = $event->getSubject();
        $oldTask = $event->getArguments();
        $isOptionalChange = isset($oldTask['isOptional']) && $newTask['isOptional'] != $oldTask['isOptional'];
        if ($isOptionalChange) {
            $this->onTaskNumberChange($event, array('taskNum', 'publishedTaskNum'));
        }
    }

    public function onTaskDelete(Event $event)
    {
        $this->onTaskNumberChange($event, array('taskNum', 'publishedTaskNum'));
    }

    public function onPublishTaskNumberChange(Event $event)
    {
        $task = $event->getSubject();
        $this->getCourseService()->updateCourseStatistics($task['courseId'], array(
            'publishedTaskNum',
        ));
    }

    public function onCourseThreadChange(Event $event)
    {
        $thread = $event->getSubject();
        $this->getCourseService()->updateCourseStatistics($thread['courseId'], array(
            'threadNum',
        ));
    }

    public function onReviewNumberChange(Event $event)
    {
        $review = $event->getSubject();

        $this->getCourseService()->updateCourseStatistics($review['courseId'], array(
            'ratingNum',
        ));
    }

    protected function onTaskNumberChange(Event $event, $fields)
    {
        $task = $event->getSubject();
        $this->getCourseService()->updateCourseStatistics($task['courseId'], $fields);
    }

    /**
     * @return CourseSetService
     */
    protected function getCourseSetService()
    {
        return $this->getBiz()->service('Course:CourseSetService');
    }

    /**
     * @return CourseService
     */
    protected function getCourseService()
    {
        return $this->getBiz()->service('Course:CourseService');
    }

    /**
     * @return LogService
     */
    protected function getLogService()
    {
        return $this->getBiz()->service('System:LogService');
    }

    /**
     * @return TaskService
     */
    protected function getTaskService()
    {
        return $this->getBiz()->service('Task:TaskService');
    }

    protected function getTaskResultService()
    {
        return $this->getBiz()->service('Task:TaskResultService');
    }

    /**
     * @return MemberService
     */
    protected function getMemberService()
    {
        return $this->getBiz()->service('Course:MemberService');
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="/static/style.css" />
    <title>minie links!</title>

Page not found

Try this one instead https://min.ie/WVFdWJMa

      Tweet or Fork. © Jonathan Cremin


text:
var app = angular.module("app", []);

app.directive("zippy", function() {
  return {
    restrict: "E",
    transclude:true,
    scope:{
      title:"@"
    },
    template:'

{{title}}

Hello world

',
    link: function (scope) {
      scope.isContentVisivle = false;
      scope.toggleContent = function () {
        scope.isContentVisible = !scope.isContentVisible;
      };
    }
  };
});


text:
<resources>
    <string name="app_name">rxeasyhttp</string>
</resources>


text:
package com.intellij.history.core.storage;

import com.intellij.history.core.IdPath;
import com.intellij.history.core.changes.*;
import com.intellij.history.core.tree.DirectoryEntry;
import com.intellij.history.core.tree.Entry;
import com.intellij.history.core.tree.FileEntry;
import com.intellij.history.core.tree.RootEntry;

import java.io.*;

public class Stream {
  private DataInputStream myIs;
  private DataOutputStream myOs;
  private Storage myStorage;

  public Stream(InputStream is, Storage s) {
    myStorage = s;
    myIs = new DataInputStream(is);
  }

  public Stream(OutputStream os) {
    myOs = new DataOutputStream(os);
  }

  public Storage getStorage() {
    return myStorage;
  }

  public IdPath readIdPath() throws IOException {
    return new IdPath(this);
  }

  public void writeIdPath(IdPath p) throws IOException {
    p.write(this);
  }

  public Content readContent() throws IOException {
    switch (myIs.readInt()) {
      case 0:
        return new StoredContent(this);
      case 1:
        return new UnavailableContent();
    }
    throw new IOException();
  }

  public void writeContent(Content content) throws IOException {
    int id = -1;

    Class c = content.getClass();
    if (c.equals(StoredContent.class)) id = 0;
    if (c.equals(UnavailableContent.class)) id = 1;

    myOs.writeInt(id);
    content.write(this);
  }

  public Entry readEntry() throws IOException {
    switch (myIs.readInt()) {
      case 0:
        return new FileEntry(this);
      case 1:
        return new DirectoryEntry(this);
      case 2:
        return new RootEntry(this);
    }
    throw new IOException();
  }

  public void writeEntry(Entry e) throws IOException {
    int id = -1;

    Class c = e.getClass();
    if (c.equals(FileEntry.class)) id = 0;
    if (c.equals(DirectoryEntry.class)) id = 1;
    if (c.equals(RootEntry.class)) id = 2;

    myOs.writeInt(id);
    e.write(this);
  }

  public Change readChange() throws IOException {
    switch (myIs.readInt()) {
      case 0:
        return new ChangeSet(this);
      case 1:
        return new CreateFileChange(this);
      case 2:
        return new CreateDirectoryChange(this);
      case 3:
        return new ContentChange(this);
      case 4:
        return new RenameChange(this);
      case 5:
        return new ROStatusChange(this);
      case 6:
        return new MoveChange(this);
      case 7:
        return new DeleteChange(this);
      case 8:
        return new PutLabelChange(this);
      case 9:
        return new PutEntryLabelChange(this);
      case 10:
        return new PutSystemLabelChange(this);
    }
    throw new IOException();
  }

  public void writeChange(Change change) throws IOException {
    int id = -1;

    Class c = change.getClass();
    if (c.equals(ChangeSet.class)) id = 0;
    if (c.equals(CreateFileChange.class)) id = 1;
    if (c.equals(CreateDirectoryChange.class)) id = 2;
    if (c.equals(ContentChange.class)) id = 3;
    if (c.equals(RenameChange.class)) id = 4;
    if (c.equals(ROStatusChange.class)) id = 5;
    if (c.equals(MoveChange.class)) id = 6;
    if (c.equals(DeleteChange.class)) id = 7;
    if (c.equals(PutLabelChange.class)) id = 8;
    if (c.equals(PutEntryLabelChange.class)) id = 9;
    if (c.equals(PutSystemLabelChange.class)) id = 10;

    assert id != -1;

    myOs.writeInt(id);
    change.write(this);
  }

  public ChangeList readChangeList() throws IOException {
    return new ChangeList(this);
  }

  public void writeChangeList(ChangeList c) throws IOException {
    c.write(this);
  }

  public String readString() throws IOException {
    return myIs.readUTF();
  }

  public void writeString(String s) throws IOException {
    myOs.writeUTF(s);
  }

  public String readStringOrNull() throws IOException {
    if (!myIs.readBoolean()) return null;
    return readString();
  }

  public void writeStringOrNull(String s) throws IOException {
    myOs.writeBoolean(s != null);
    if (s != null) writeString(s);
  }

  public int readInteger() throws IOException {
    return myIs.readInt();
  }

  public void writeInteger(int i) throws IOException {
    myOs.writeInt(i);
  }

  public long readLong() throws IOException {
    return myIs.readLong();
  }

  public void writeLong(long l) throws IOException {
    myOs.writeLong(l);
  }

  public boolean readBoolean() throws IOException {
    return myIs.readBoolean();
  }

  public void writeBoolean(boolean b) throws IOException {
    myOs.writeBoolean(b);
  }
}


text:
/*
 * Support and FAQ: visit Atmel Support
 */
#ifndef DAC_H
#define DAC_H

#include <compiler.h>
#include <nvm.h>
#include <sysclk.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \defgroup dac_group Digital to Analog Converter (DAC)
 *
 * See \ref dac_quickstart.
 *
 * This is a driver for versions 1 and 2, introduced with the XMEGA AU family,
 * of the AVR XMEGA DAC. It provides functions for enabling, disabling and
 * configuring the DAC and its channels.
 *
 * Note that functions for configuring refresh interval and conversion timing
 * are not present for version 2 of the DAC, since it does not need those
 * settings. The symbols \ref XMEGA_DAC_VERSION_1 and \ref XMEGA_DAC_VERSION_2
 * can be used to tell, at compile time, which DAC the driver is compiled for.
 *
 * The API functions and definitions can be divided in two groups:
 * - module management: direct access for enabling and disabling the DAC,
 * setting and getting channel values, waiting for conversion completion, etc.
 * - module configuration: create/change configurations and write/read them
 * to/from a DAC.
 *
 * The API makes use of a structure that contains the configuration. This
 * structure must be set up before the configuration is written to a DAC module.
 *
 * After the DAC has been configured, it must be enabled before any conversions
 * can be done or any of its channel values be changed.
 *
 * \pre The functions for creating/changing configurations are not protected
 * against interrupts. The functions that read from or write to the DAC's
 * registers are protected.
 *
 * \section dependencies Dependencies
 * This driver depends on the following modules:
 * - \ref sysclk_group for peripheral clock control.
 * - \ref interrupt_group for disabling interrupts during critical code
 * sections.
 * - \ref sleepmgr_group for setting allowed sleep mode.
 *
 * \note If both DAC channels are active, and one of them is run at maximum
 * conversion rate, automatic refresh can fail since the triggered conversions
 * have higher priority than the refresh.
 *
 * @{
 */

#if XMEGA_AU || XMEGA_B || XMEGA_E
#  define XMEGA_DAC_VERSION_2 true
#else
#  define XMEGA_DAC_VERSION_1 true
#endif

//! DAC configuration
struct dac_config {
	uint8_t ctrla;
	uint8_t ctrlb;
	uint8_t ctrlc;
	uint8_t evctrl;
#if XMEGA_DAC_VERSION_1
	uint8_t timctrl;
#endif
};

//! DAC reference settings
enum dac_reference {
	//! 1 V from internal bandgap reference.
	DAC_REF_BANDGAP = DAC_REFSEL_INT1V_gc,
	//! Analog VCC as reference.
	DAC_REF_AVCC    = DAC_REFSEL_AVCC_gc,
	//! External reference on AREF pin on port A.
	DAC_REF_AREFA   = DAC_REFSEL_AREFA_gc,
	//! External reference on AREF pin on port B.
	DAC_REF_AREFB   = DAC_REFSEL_AREFB_gc,
};

//! DAC value adjust settings
enum dac_adjust {
	DAC_ADJ_RIGHT,                     //!< Right-adjusted value.
	DAC_ADJ_LEFT  = DAC_LEFTADJ_bm,    //!< Left-adjusted value.
};

//! \name DAC channel masks
//@{

#define DAC_CH0    (1 << 0)                //!< DAC channel 0.
#define DAC_CH1    (1 << 1)                //!< DAC channel 1.

//@}

//! \name Calibration data addresses
//@{
#if XMEGA_DAC_VERSION_1

#  if defined(DACA)
//! DAC A, offset calibration.
#    define DACAOFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACAOFFCAL)
//! DAC A, gain calibration.
#    define DACAGAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACAGAINCAL)
#  endif

#  if defined(DACB)
//! DAC B, offset calibration.
#    define DACBOFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACBOFFCAL)
//! DAC B, gain calibration.
#    define DACBGAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACBGAINCAL)
#  endif

#elif XMEGA_DAC_VERSION_2

//! DAC A Channel 0, offset calibration.
#  define DACA0OFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACA0OFFCAL)
//! DAC A Channel 0, gain calibration.
#  define DACA0GAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACA0GAINCAL)
//! DAC A Channel 1, offset calibration.
#  define DACA1OFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACA1OFFCAL)
//! DAC A Channel 1, gain calibration.
#  define DACA1GAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACA1GAINCAL)

//! DAC B Channel 0, offset calibration.
#  define DACB0OFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACB0OFFCAL)
//! DAC B Channel 0, gain calibration.
#  define DACB0GAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACB0GAINCAL)
//! DAC B Channel 1, offset calibration.
#  define DACB1OFFCAL     offsetof(NVM_PROD_SIGNATURES_t, DACB1OFFCAL)
//! DAC B Channel 1, gain calibration.
#  define DACB1GAINCAL    offsetof(NVM_PROD_SIGNATURES_t, DACB1GAINCAL)

#endif
//@}

#if XMEGA_DAC_VERSION_1

//! DAC calibration data
enum dac_calibration_data {
#  if defined(DACA)
	DAC_CAL_DACA_OFFSET = DACAOFFCAL,    //!< DAC A offset calibration data.
	DAC_CAL_DACA_GAIN   = DACAGAINCAL,   //!< DAC A gain calibration data.
#  endif
#  if defined(DACB)
	DAC_CAL_DACB_OFFSET = DACBOFFCAL,    //!< DAC B offset calibration data.
	DAC_CAL_DACB_GAIN   = DACBGAINCAL,   //!< DAC B gain calibration data.
#  endif
};

#elif XMEGA_DAC_VERSION_2

//! DAC calibration data
enum dac_calibration_data {
#  if defined(DACA)
	DAC_CAL_DACA0_OFFSET = DACA0OFFCAL,    //!< DAC A Channel 0 offset calibration data.
	DAC_CAL_DACA0_GAIN   = DACA0GAINCAL,   //!< DAC A Channel 0 gain calibration data.
	DAC_CAL_DACA1_OFFSET = DACA1OFFCAL,    //!< DAC A Channel 1 offset calibration data.
	DAC_CAL_DACA1_GAIN   = DACA1GAINCAL,   //!< DAC A Channel 1 gain calibration data.
#  endif
#  if defined(DACB)
	DAC_CAL_DACB0_OFFSET = DACB0OFFCAL,    //!< DAC B Channel 0 offset calibration data.
	DAC_CAL_DACB0_GAIN   = DACB0GAINCAL,   //!< DAC B Channel 0 gain calibration data.
	DAC_CAL_DACB1_OFFSET = DACB1OFFCAL,    //!< DAC B Channel 1 offset calibration data.
	DAC_CAL_DACB1_GAIN   = DACB1GAINCAL,   //!< DAC B Channel 1 gain calibration data.
#  endif
};

#endif

//! \name DAC module and channel management
//@{

void dac_enable(DAC_t *dac);
void dac_disable(DAC_t *dac);
bool dac_is_enabled(DAC_t *dac);

/**
 * \brief Get calibration data
 *
 * Returns the specified calibration data from the production signature row.
 *
 * \param cal Identifier for calibration data to get.
 *
 * \return Byte with specified calibration data.
 */
__always_inline static uint8_t dac_get_calibration_data(
		enum dac_calibration_data cal)
{
	return nvm_read_production_signature_row(cal);
}

/**
 * \brief Set value of DAC channel
 *
 * \param dac Pointer to DAC module.
 * \param ch_mask Mask of DAC channel for which to set the value:
 * \arg \c DAC_CHn , where \c n specifies the channel.
 * \param val 12-bit value to set. (Must be adjusted as configured in the
 * conversion parameters with \ref dac_set_conversion_parameters.)
 *
 * \note This function has no effect if the DAC is not enabled.
 */
__always_inline static void dac_set_channel_value(DAC_t *dac, uint8_t ch_mask,
		uint16_t val)
{
	irqflags_t flags;
	uint16_t   *dac_ch;
	uint8_t    ch;

	Assert(ch_mask);
	ch = ilog2(ch_mask);
	Assert(ch <= 1);
	dac_ch = (uint16_t *)&dac->CH0DATA + ch;

	flags = cpu_irq_save();
	*dac_ch = val;
	cpu_irq_restore(flags);
}

/**
 * \brief Get value of DAC channel
 *
 * \param dac Pointer to DAC module.
 * \param ch_mask Mask of DAC channel from which to retrieve the value:
 * \arg \c DAC_CHn , where \c n specifies the channel.
 *
 * \return Current 12-bit value of the DAC channel.
 */
__always_inline static uint16_t dac_get_channel_value(DAC_t *dac,
		uint8_t ch_mask)
{
	irqflags_t flags;
	uint16_t   *dac_ch;
	uint16_t   val;
	uint8_t    ch;

	Assert(ch_mask);
	ch = ilog2(ch_mask);
	Assert(ch <= 1);
	dac_ch = (uint16_t *)&dac->CH0DATA + ch;

	flags = cpu_irq_save();
	val = *dac_ch;
	cpu_irq_restore(flags);

	return val;
}

/**
 * \brief Check whether DAC channel(s) are ready for data
 *
 * Checks if the data registers for all of the masked DAC channels are ready for
 * a new value. This indicates that a conversion with the current value has been
 * completed.
 *
 * \param dac Pointer to DAC module.
 * \param ch_mask Mask of DAC channel(s) to check whether are ready:
 * \arg \c DAC_CHn , where \c n specifies the channel. (These can be OR'ed
 * together.)
 *
 * \retval true if DAC channels are ready.
 * \retval false if a DAC channel is not ready.
 */
__always_inline static bool dac_channel_is_ready(DAC_t *dac, uint8_t ch_mask)
{
	Assert(dac);

	return (dac->STATUS & ch_mask) == ch_mask;
}

/**
 * \brief Wait for DAC channel(s) to get ready for data
 *
 * Busy-waits for all of the masked DAC channels' data registers to become ready
 * for new values.
 *
 * \param dac Pointer to DAC module.
 * \param ch_mask Mask of DAC channel(s) to wait for data ready:
 * \arg \c DAC_CHn , where \c n specifies the channel. (These can be OR'ed
 * together.)
 */
__always_inline static void dac_wait_for_channel_ready(DAC_t *dac,
		uint8_t ch_mask)
{
	Assert(dac);

	do { } while (!dac_channel_is_ready(dac, ch_mask));
}

//@}

//! \name DAC module and channel configuration
//@{

void dac_write_configuration(DAC_t *dac, struct dac_config *conf);
void dac_read_configuration(DAC_t *dac, struct dac_config *conf);

/**
 * \brief Set active DAC channel(s) and output(s)
 *
 * Enables the masked DAC channels and configures their output. Either of the
 * channels may be configured for internal output, but not both. Implicitly,
 * channels that are not masked for internal output are configured for output
 * on their respective pins.
 *
 * \param conf Pointer to DAC configuration.
 * \param ch_mask Mask of DAC channel(s) to enable:
 * \arg \c DAC_CHn , where \c n specifies the channel. (These can be OR'ed
 * together.)
 * \param int_out_ch_mask Mask of DAC channel to connect to internal output:
 * \arg \c 0 to connect all channels to output pin.
 * \arg \c DAC_CHn , where \c n specifies the channel.
 *
 * \note If both channels of a version 1 DAC are enabled, the refresh rate must
 * also be configured with \ref dac_set_refresh_interval().
 */
__always_inline static void dac_set_active_channel(struct dac_config *conf,
		uint8_t ch_mask, uint8_t int_out_ch_mask)
{
	uint8_t setting = 0;

	Assert(conf);
	Assert(ch_mask);
	Assert(ilog2(ch_mask) <= 2);
	Assert((ch_mask & int_out_ch_mask) == int_out_ch_mask);
	Assert(int_out_ch_mask != (DAC_CH0 | DAC_CH1));

	// Enable internal and external output channels.
	conf->ctrla = ((ch_mask ^ int_out_ch_mask) << DAC_CH0EN_bp) |
			(int_out_ch_mask ? DAC_IDOEN_bm : 0);

	// Enable the specified number of DAC channels.
	if (ch_mask == DAC_CH0) {
		setting = DAC_CHSEL_SINGLE_gc;
	} else if (ch_mask == DAC_CH1) {
#ifdef DAC_CHSEL_SINGLE1_gc
		setting = DAC_CHSEL_SINGLE1_gc;
#else
		Assert(false);
#endif
	} else {
		setting = DAC_CHSEL_DUAL_gc;
	}
	conf->ctrlb &= ~DAC_CHSEL_gm;
	conf->ctrlb |= setting;
}

// Timing configuration is only needed for version 1 of DAC
#if XMEGA_DAC_VERSION_1 || defined(__DOXYGEN__)

/**
 * \brief Set automatic refresh timing interval
 *
 * Sets or disables the automatic refresh timing interval for dual-channel mode
 * of the DAC. If it is disabled, the DAC channels must be manually refreshed by
 * updating the channel values and triggering new conversions.
 *
 * This interval is rounded downward to the closest setting.
 *
 * \param conf Pointer to DAC configuration.
 * \param us Microseconds between channel refresh:
 * \arg \c 1 to \c 30 to enable.
 * \arg \c 0 to disable.
 *
 * \note The refresh interval should not exceed 30 us.
 */
__always_inline static void dac_set_refresh_interval(struct dac_config *conf,
		uint8_t us)
{
	uint32_t cycles;
	uint8_t  cycles_log2;
	uint8_t  setting;

	Assert(conf);
	Assert(us <= 30);

	// Enabling automatic refresh?
	if (us) {
		// Compute the corresponding number of peripheral clock cycles.
		cycles = sysclk_get_per_hz();
		cycles *= us;
		cycles /= 1000000;

		// Get the integer number of bits for cycle count.
		cycles_log2 = cycles ? ilog2(cycles) : 0;

		// Handle out-of-bounds settings.
		if (cycles_log2 < 4) {
			setting = DAC_REFRESH_16CLK_gc;
		} else if (cycles_log2 > 16) {
			setting = DAC_REFRESH_65536CLK_gc;
		// Handle within-bounds settings.
		} else {
			setting = (cycles_log2 - 4) << DAC_REFRESH_gp;
		}
	// Disabling automatic refresh.
	} else {
		setting = DAC_REFRESH_OFF_gc;
	}
	conf->timctrl &= ~DAC_REFRESH_gm;
	conf->timctrl |= setting;
}

/**
 * \brief Set conversion timing interval
 *
 * Sets the timing interval from a conversion is completed until a new one can
 * be started. This settings depends on whether single- or dual-channel mode is
 * used, and so the channels should be configured before this function is
 * called to ensure the proper configuration.
 *
 * This interval is rounded downward to the closest setting.
 *
 * \param conf Pointer to DAC configuration.
 * \param us Microseconds between conversions:
 * \arg \c 1 to \c 127 for single-channel.
 * \arg \c 2 to \c 127 for dual-channel.
 *
 * \note The conversion interval should not exceed 127.
 */
__always_inline static void dac_set_conversion_interval(struct dac_config *conf,
		uint8_t us)
{
	uint32_t cycles;
	uint8_t  cycles_log2;
	uint8_t  setting;

	Assert(us);
	Assert(us <= 127);

	// Compute the corresponding number of peripheral clock cycles.
	cycles = sysclk_get_per_hz();
	cycles *= us;
	cycles /= 1000000;

	// Compensate for 50% cycle addition for dual-channel mode.
	if ((conf->ctrlb & DAC_CHSEL_gm) == DAC_CHSEL_DUAL_gc) {
		cycles *= 2;
		cycles /= 3;
	}

	// Get the integer number of bits for cycle count.
	cycles_log2 = cycles ? ilog2(cycles) : 0;

	if (cycles_log2 < 7) {
		setting = cycles_log2 << DAC_CONINTVAL_gp;
	} else {
		setting = DAC_CONINTVAL_128CLK_gc;
	}
	conf->timctrl &= ~DAC_CONINTVAL_gm;
	conf->timctrl |= setting;
}

#endif // XMEGA_DAC_VERSION_1

/**
 * \brief Set DA conversion parameters
 *
 * Sets up the voltage reference and channel value adjust, i.e., whether the
 * 12-bit value is shifted to the most significant (left) or least significant
 * (right) bits in the channels' 16-bit data registers.
 *
 * \param conf Pointer to DAC configuration.
 * \param ref DAC voltage reference setting.
 * \param adj DAC value adjust setting.
 */
__always_inline static void dac_set_conversion_parameters(
		struct dac_config *conf, enum dac_reference ref,
		enum dac_adjust adj)
{
	conf->ctrlc = (uint8_t)ref | (uint8_t)adj;
}

/**
 * \brief Set DA conversions triggers
 *
 * Sets up event-triggering of conversions on the masked channels, and manual
 * triggering on the others. Conversions are manually triggered by setting new
 * channel values, while events only trigger new conversions if a new channel
 * value was set since the last conversion.
 *
 * \param conf Pointer to DAC configuration.
 * \param ev_ch Event channel to use.
 * \param ch_mask Mask of DAC channel(s) to use event-triggering on:
 * \arg \c DAC_CHn , where \c n specifies the channel. (These can be OR'ed
 * together.)
 * \arg \c 0 to disable.
 *
 * \note The specified event channel is common to all DAC channels on which
 * event-triggering of conversions is configured.
 */
__always_inline static void dac_set_conversion_trigger(struct dac_config *conf,
		uint8_t ch_mask, uint8_t ev_ch)
{
	Assert(ev_ch <= 7);

	conf->ctrlb &= ~(DAC_CH1TRIG_bm | DAC_CH0TRIG_bm);
	conf->ctrlb |= (ch_mask << DAC_CH0TRIG_bp);
	conf->evctrl = ev_ch << DAC_EVSEL_gp;
}

//@}

//! @}

/**
 * \page dac_quickstart Quick start guide for XMEGA DAC
 *
 * This is the quick start guide for the \ref dac_group, with
 * step-by-step instructions on how to configure and use the driver in a
 * selection of use cases.
 *
 * The use cases contain several code fragments. The code fragments in the
 * steps for setup can be copied into a custom initialization function, while
 * the steps for usage can be copied into, e.g., the main application function.
 *
 * \section dac_use_cases DAC use cases
 * - \ref dac_basic_use_case
 * - \subpage dac_use_case_1
 *
 * \section dac_basic_use_case Basic use case - DA conversion on one channel
 * In this use case, the DAC is configured for:
 * - Using DAC on port B, channel 0
 * - 1V from bandgap as reference, left adjusted channel value
 * - one active DAC channel, no internal output
 * - conversions triggered by event channel 0
 * - 1 us conversion intervals
 *
 * This use case sets up the DAC to perform DA conversions on one channel,
 * with output to a pin, every time it receives events in event channel 0.
 * The output pin may, e.g., be connected to an oscilloscope or an amplifier
 * and speaker.
 *
 * \section dac_basic_use_case_setup Setup steps
 *
 * \subsection dac_basic_use_case_setup_prereq Prerequisites
 * -# \ref sysclk_group "System Clock Management"
 * -# \ref tc_group "Timer/Counter Driver"
 *
 * \subsection dac_basic_use_case_setup_code Example code
 * The following configuration must be added to the project (typically to a
 * conf_dac.h file, but it can also be added to your main application file):
 * \code
	#define SPEAKER_DAC              DACB
	#define SPEAKER_DAC_CHANNEL      DAC_CH0
	#define RATE_OF_CONVERSION       22050
	#define NR_OF_SAMPLES            32
\endcode
 *
 * A static const sample buffer with one period of a sine wave must be added:
 * \code static const uint16_t sine[NR_OF_SAMPLES] = {
	    32768, 35325, 37784, 40050, 42036, 43666, 44877, 45623,
	    45875, 45623, 44877, 43666, 42036, 40050, 37784, 35325,
	    32768, 30211, 27752, 25486, 23500, 21870, 20659, 19913,
	    19661, 19913, 20659, 21870, 23500, 25486, 27752, 30211,
	};
\endcode
 *
 * Add to application initialization:
 * \code
	 static void evsys_init(void)
	 {
	     sysclk_enable_module(SYSCLK_PORT_GEN, SYSCLK_EVSYS);
	     EVSYS.CH3MUX = EVSYS_CHMUX_TCC0_OVF_gc;
	 }

	 void tc_init(void)
	 {
	     tc_enable(&TCC0);
	     tc_set_wgm(&TCC0, TC_WG_NORMAL);
	     tc_write_period(&TCC0, (sysclk_get_per_hz() / RATE_OF_CONVERSION) - 1);
	     tc_write_clock_source(&TCC0, TC_CLKSEL_DIV1_gc);
	 }

	 void dac_init(void)
	 {
	     struct dac_config conf;

	     dac_read_configuration(&SPEAKER_DAC, &conf);
	     dac_set_conversion_parameters(&conf, DAC_REF_BANDGAP, DAC_ADJ_LEFT);
	     dac_set_active_channel(&conf, SPEAKER_DAC_CHANNEL, 0);
	     dac_set_conversion_trigger(&conf, SPEAKER_DAC_CHANNEL, 3);
	     #ifdef XMEGA_DAC_VERSION_1
	     dac_set_conversion_interval(&conf, 1);
	     #endif
	     dac_write_configuration(&SPEAKER_DAC, &conf);
	     dac_enable(&SPEAKER_DAC);
	 }
\endcode
 *
 * Add to \c main():
 * \code
	sysclk_init();
	evsys_init();
	tc_init();
	dac_init();
\endcode
 *
 * \subsection dac_basic_use_case_setup_flow Workflow
 * -# Create a function \c evsys_init() to intialize the event system clocks and
 *    to link the conversion timer to the correct event channel:
 *     - \code
	static void evsys_init(void)
	{
	    // ...
	}
\endcode
 * -# Use the sysclk service to enable the clock to the event system:
 *     - \code sysclk_enable_module(SYSCLK_PORT_GEN, SYSCLK_EVSYS); \endcode
 * -# Connect the TCC0 overflow event to event channel 3:
 *     - \code EVSYS.CH3MUX = EVSYS_CHMUX_TCC0_OVF_gc; \endcode
 *    \note If the DAC trigger timer is changed from TCC0, the \c EVSYS_CHMUX_*
 *          mask here will also need to be altered.
 * -# Create a function \c tc_init() to intialize the DAC trigger timer:
 *     - \code
	static void tc_init(void)
	{
	    // ...
	}
\endcode
 * -# Enable the clock to the DAC trigger timer:
 *     - \code tc_enable(&TCC0); \endcode
 * -# Configure the DAC trigger timer in normal Waveform Generation mode:
 *     - \code tc_set_wgm(&TCC0, TC_WG_NORMAL); \endcode
 * -# Configure the DAC trigger timer period to overflow at at the specified
 *    rate of conversion in Hz:
 *     - \code tc_write_period(&TCC0, (sysclk_get_per_hz() / RATE_OF_CONVERSION) - 1); \endcode
 * -# Configure the DAC trigger timer clock source to use the peripheral bus
 *    frequency:
 *     - \code tc_write_clock_source(&TCC0, TC_CLKSEL_DIV1_gc); \endcode
 * -# Create a function \c dac_init() to intialize the DAC:
 *     - \code
	static void dac_init(void)
	{
	    // ...
	}
\endcode
 * -# Config struct for the DAC:
 *   - \code struct dac_config conf; \endcode
 * -# Initialize the dac configuration by reading back the configuration from the peripheral:
 *   - \code dac_read_configuration(&SPEAKER_DAC, &conf); \endcode
 * -# Create and set configuration:
 *   - \code
	dac_set_conversion_parameters(&conf, DAC_REF_BANDGAP, DAC_ADJ_LEFT);
	dac_set_active_channel(&conf, SPEAKER_DAC_CHANNEL, 0);
	dac_set_conversion_trigger(&conf, SPEAKER_DAC_CHANNEL, 3);
	#ifdef XMEGA_DAC_VERSION_1
	dac_set_conversion_interval(&conf, 1);
	#endif
	dac_write_configuration(&SPEAKER_DAC, &conf);
\endcode
 *    \note If the DAC trigger event channel is changed from channel 3, the
 *          parameter to dac_set_conversion_trigger() here will also need to be
 *          altered.
 * -# Enable DAC:
 *   - \code dac_enable(&SPEAKER_DAC); \endcode
 * -# Initialize the clock system, event system, DAC trigger timer, and the DAC:
 *     - \code
	sysclk_init();
	evsys_init();
	tc_init();
	dac_init();
\endcode
 *
 * \section dac_basic_use_case_usage Usage steps
 *
 * \subsection dac_basic_use_case_usage_code Example code
 * Add to application C-file:
 * \code
	uint8_t i = 0;
	while (1) {
	    dac_wait_for_channel_ready(&SPEAKER_DAC, SPEAKER_DAC_CHANNEL);
	    dac_set_channel_value(&SPEAKER_DAC, SPEAKER_DAC_CHANNEL, sine[i]);
	    i++;
	    i %= NR_OF_SAMPLES;
	}
\endcode
 *
 * \subsection dac_basic_use_case_usage_flow Workflow
 * -# Create a local variable to hold the current sine wave lookup table index:
 *   - \code uint8_t i = 0; \endcode
 * -# Wait for DAC channel to be ready for new data:
 *   - \code
	dac_wait_for_channel_ready(&SPEAKER_DAC, SPEAKER_DAC_CHANNEL);
\endcode
 * -# Set the current sine wave table element as new channel value:
 *   - \code
	dac_set_channel_value(&SPEAKER_DAC, SPEAKER_DAC_CHANNEL, sine[i]);
\endcode
 * \note Conversion is triggered by the timer/counter
 * -# Get next index in sine wave array to convert, wrapping around at NR_OF_SAMPLES:
 *   - \code
	i++;
	i %= NR_OF_SAMPLES;
\endcode
 */

/**
 * \page dac_use_case_1 DA conversions on two channels
 *
 * In this use case, the DAC module is configured for:
 * - AVCC as reference, right adjusted channel value
 * - Both DAC channels active, no internal output
 * - Manually triggered conversions on both channels
 * - 2 us conversion intervals
 * - 10 us refresh intervals
 *
 * This use case configures the DAC to perform DA conversions on both channels,
 * with output to their respective pins every time it receives an event on event
 * channel 0.
 * \section dac_use_case_1_setup Setup steps
 *
 * \subsection dac_use_case_1_setup_prereq Prerequisites
 * -# \ref sysclk_group "System Clock Management"
 * -# \ref tc_group "Timer/Counter Driver"
 *
 * \subsection dac_use_case_1_setup_code Example code
 * -# The following configuration must be added to the project (typically to a
 * conf_dac.h file, but it can also be added to your main application file.):
 * \code
	#define RATE_OF_CONVERSION       500
	#define OUTPUT_DAC               DACA
\endcode
 *
 * -# Add to application initialization:
 * \code
	 void tc_init(void)
	 {
	     tc_enable(&TCC0);
	     tc_set_wgm(&TCC0, TC_WG_NORMAL);
	     tc_write_period(&TCC0, (sysclk_get_per_hz() / RATE_OF_CONVERSION) - 1);
	     tc_write_clock_source(&TCC0, TC_CLKSEL_DIV1_gc);
	 }

	 void dac_init(void)
	 {
	     struct dac_config conf;

	     dac_read_configuration(&OUTPUT_DAC, &conf);
	     dac_set_conversion_parameters(&conf, DAC_REF_AVCC, DAC_ADJ_RIGHT);
	     dac_set_active_channel(&conf, DAC_CH0 | DAC_CH1, 0);
	     #ifdef XMEGA_DAC_VERSION_1
	     dac_set_conversion_interval(&conf, 10);
	     dac_set_refresh_interval(&conf, 20);
	     #endif
	     dac_write_configuration(&OUTPUT_DAC, &conf);
	     dac_enable(&OUTPUT_DAC);
	 }
\endcode
 *
 * Add to \c main():
 * \code
	sysclk_init();
	tc_init();
	dac_init();
\endcode
 *
 * \subsection dac_use_case_1_setup_flow Workflow
 * -# Create a function \c tc_init() to intialize the DAC trigger timer:
 *     - \code
	static void tc_init(void)
	{
	    // ...
	}
\endcode
 * -# Enable the clock to the DAC trigger timer:
 *     - \code tc_enable(&TCC0); \endcode
 * -# Configure the DAC trigger timer in normal Waveform Generation mode:
 *     - \code tc_set_wgm(&TCC0, TC_WG_NORMAL); \endcode
 * -# Configure the DAC trigger timer period to overflow at at the specified
 *    rate of conversion in Hz:
 *     - \code tc_write_period(&TCC0, (sysclk_get_per_hz() / RATE_OF_CONVERSION) - 1); \endcode
 * -# Configure the DAC trigger timer clock source to use the peripheral bus
 *    frequency:
 *     - \code tc_write_clock_source(&TCC0, TC_CLKSEL_DIV1_gc); \endcode
 * -# Create a function \c dac_init() to intialize the DAC:
 *     - \code
	static void dac_init(void)
	{
	    // ...
	}
\endcode
 * -# Config struct for the DAC:
 *   - \code struct dac_config conf; \endcode
 * -# Initialize system clock:
 *   - \code sysclk_init(); \endcode
 * -# Initialize the dac configuration by reading back the configuration from the peripheral:
 *   - \code dac_read_configuration(&SPEAKER_DAC, &conf); \endcode
 * -# Create and set configuration:
 *   - \code
	dac_read_configuration(&OUTPUT_DAC, &conf);
	dac_set_conversion_parameters(&conf, DAC_REF_AVCC, DAC_ADJ_RIGHT);
	dac_set_active_channel(&conf, DAC_CH0 | DAC_CH1, 0);
	#ifdef XMEGA_DAC_VERSION_1
	dac_set_conversion_interval(&conf, 10);
	dac_set_refresh_interval(&conf, 20);
	#endif
	dac_write_configuration(&OUTPUT_DAC, &conf);
	dac_enable(&OUTPUT_DAC);
\endcode
 * -# Enable DAC:
 *   - \code dac_enable(&SPEAKER_DAC); \endcode
 * -# Initialize the clock system, event system, DAC trigger timer, and the DAC:
 *     - \code
	sysclk_init();
	tc_init();
	dac_init();
\endcode
 *
 * \section dac_use_case_1_usage Usage steps
 *
 * \subsection dac_use_case_1_usage_code Example code
 * Add to, e.g., main loop in application C-file:
 * \code
	 while (!(tc_is_overflow(&TCC0))) {};
	 tc_clear_overflow(&TCC0);

	 dac_set_channel_value(&OUTPUT_DAC, DAC_CH0, 410);
	 dac_set_channel_value(&OUTPUT_DAC, DAC_CH1, 3686);

	 while (!(tc_is_overflow(&TCC0))) {};
	 tc_clear_overflow(&TCC0);

	 dac_set_channel_value(&OUTPUT_DAC, DAC_CH0, 3686);
	 dac_set_channel_value(&OUTPUT_DAC, DAC_CH1, 410);
\endcode
 *
 * \subsection dac_use_case_1_usage_flow Workflow
 * -# Wait for channels to get ready for new values, by waiting for the sample
 *    timer to overflow and then clearing the flag:
 *   - \code
	while (!(tc_is_overflow(&TCC0))) {};
	tc_clear_overflow(&TCC0);
\endcode
 * -# Set the value of channel 0 to 10% and the other to 90% of maximum:
 *   - \code
	dac_set_channel_value(&OUTPUT_DAC, DAC_CH0, 410);
	dac_set_channel_value(&OUTPUT_DAC, DAC_CH1, 3686);
\endcode
 * -# Wait for channels to get ready for new values, by waiting for the sample
 *    timer to overflow and then clearing the flag:
 *   - \code
	while (!(tc_is_overflow(&TCC0))) {};
	tc_clear_overflow(&TCC0);
\endcode
 * -# Set the value of channel 0 to 90% and the other to 10% of maximum:
 *   - \code
	dac_set_channel_value(&OUTPUT_DAC, DAC_CH0, 3686);
	dac_set_channel_value(&OUTPUT_DAC, DAC_CH1, 410);
\endcode
 * \note Conversions are triggered by the timer/counter
 */

#ifdef __cplusplus
}
#endif

#endif /* DAC_H */


text:
<?php

class Session_Storage_Elastic implements Session_StorageInterface {
  protected $_storage;

  public function __construct(StorageInterface $storage) {
    $this->_storage = $storage;
  }

  public function load($name, $id) {
    return $this->_storage->get('session:'.$name.':'.$id);
  }

  public function save($name, $id, $data, $timeout) {
    return $this->_storage->set('session:'.$name.':'.$id, $data, $timeout);
  }

  public function destroy($name, $id) {
    return $this->_storage->delete('session:'.$name.':'.$id, $data, $timeout);
  }
}

?>


text:
Specifies how an HTTP request is made.

The HttpOptions type is a table that specifies how an HTTP request is
made. It has the following fields:

Field
Type
Description

URL
string
The URL to make to request to.

Method
string?
The HTTP method. Defaults to GET.

RequestFormat
FormatSelector?
The format used to encode the request body.

ResponseFormat
FormatSelector?
The format used to decode the response body.

Headers
HttpHeaders?
The HTTP headers to include with the request.

Cookies
Cookies?
Cookies to append to the Cookie header.

Body
any?
The body of the request, to be encoded by the specified format.

If RequestFormat is unspecified, then no request body is sent. If
ResponseFormat is unspecified, then no response body is returned.

Use of the Cookies field ensures that cookies sent with the request are
well-formed, and is preferred over setting the Cookie header directly.


text:
import {
  assert, CMapCompressionType, createValidAbsoluteUrl, deprecated,
  removeNullCharacters, stringToBytes, warn
} from '../shared/util';
import globalScope from '../shared/global_scope';

const DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
const SVG_NS = 'http://www.w3.org/2000/svg';

class DOMCanvasFactory {
  create(width, height) {
    if (width <= 0 || height <= 0) {
      throw new Error('invalid canvas size');
    }
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    return {
      canvas,
      context,
    };
  }

  reset(canvasAndContext, width, height) {
    if (!canvasAndContext.canvas) {
      throw new Error('canvas is not specified');
    }
    if (width <= 0 || height <= 0) {
      throw new Error('invalid canvas size');
    }
    canvasAndContext.canvas.width = width;
    canvasAndContext.canvas.height = height;
  }

  destroy(canvasAndContext) {
    if (!canvasAndContext.canvas) {
      throw new Error('canvas is not specified');
    }
    // Zeroing the width and height cause Firefox to release graphics
    // resources immediately, which can greatly reduce memory consumption.
    canvasAndContext.canvas.width = 0;
    canvasAndContext.canvas.height = 0;
    canvasAndContext.canvas = null;
    canvasAndContext.context = null;
  }
}

class DOMCMapReaderFactory {
  constructor({ baseUrl = null, isCompressed = false, }) {
    this.baseUrl = baseUrl;
    this.isCompressed = isCompressed;
  }

  fetch({ name, }) {
    if (!name) {
      return Promise.reject(new Error('CMap name must be specified.'));
    }
    return new Promise((resolve, reject) => {
      let url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');

      let request = new XMLHttpRequest();
      request.open('GET', url, true);

      if (this.isCompressed) {
        request.responseType = 'arraybuffer';
      }
      request.onreadystatechange = () => {
        if (request.readyState !== XMLHttpRequest.DONE) {
          return;
        }
        if (request.status === 200 || request.status === 0) {
          let data;
          if (this.isCompressed && request.response) {
            data = new Uint8Array(request.response);
          } else if (!this.isCompressed && request.responseText) {
            data = stringToBytes(request.responseText);
          }
          if (data) {
            resolve({
              cMapData: data,
              compressionType: this.isCompressed ?
                CMapCompressionType.BINARY : CMapCompressionType.NONE,
            });
            return;
          }
        }
        reject(new Error('Unable to load ' +
                         (this.isCompressed ? 'binary ' : '') +
                         'CMap at: ' + url));
      };

      request.send(null);
    });
  }
}

class DOMSVGFactory {
  create(width, height) {
    assert(width > 0 && height > 0, 'Invalid SVG dimensions');

    let svg = document.createElementNS(SVG_NS, 'svg:svg');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('width', width + 'px');
    svg.setAttribute('height', height + 'px');
    svg.setAttribute('preserveAspectRatio', 'none');
    svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);

    return svg;
  }

  createElement(type) {
    assert(typeof type === 'string', 'Invalid SVG element type');

    return document.createElementNS(SVG_NS, type);
  }
}

class SimpleDOMNode {
  constructor(nodeName, nodeValue) {
    this.nodeName = nodeName;
    this.nodeValue = nodeValue;

    Object.defineProperty(this, 'parentNode', { value: null, writable: true, });
  }

  get firstChild() {
    return this.childNodes[0];
  }

  get nextSibling() {
    let index = this.parentNode.childNodes.indexOf(this);
    return this.parentNode.childNodes[index + 1];
  }

  get textContent() {
    if (!this.childNodes) {
      return this.nodeValue || '';
    }
    return this.childNodes.map(function(child) {
      return child.textContent;
    }).join('');
  }

  hasChildNodes() {
    return this.childNodes && this.childNodes.length > 0;
  }
}

class SimpleXMLParser {
  parseFromString(data) {
    let nodes = [];

    // Remove all comments and processing instructions.
    data = data.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->/g, '').trim();
    data = data.replace(/<!DOCTYPE[^>\[]+(\[[^\]]+)?[^>]+>/g, '').trim();

    // Extract all text nodes and replace them with a numeric index in
    // the nodes.
    data = data.replace(/>([^<][\s\S]*?)</g, (all, text) => {
      let length = nodes.length;
      let node = new SimpleDOMNode('#text', this._decodeXML(text));
      nodes.push(node);
      if (node.textContent.trim().length === 0) {
        return '><'; // Ignore whitespace.
      }
      return '>' + length + ',<';
    });

    // Extract all CDATA nodes.
    data = data.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g,
        function(all, text) {
      let length = nodes.length;
      let node = new SimpleDOMNode('#text', text);
      nodes.push(node);
      return length + ',';
    });

    // Until nodes without '<' and '>' content are present, replace them
    // with a numeric index in the nodes.
    let regex =
      /<([\w\:]+)((?:[\s\w:=]|'[^']*'|"[^"]*")*)(?:\/>|>([\d,]*)<\/[^>]+>)/g;
    let lastLength;
    do {
      lastLength = nodes.length;
      data = data.replace(regex, function(all, name, attrs, data) {
        let length = nodes.length;
        let node = new SimpleDOMNode(name);
        let children = [];
        if (data) {
          data = data.split(',');
          data.pop();
          data.forEach(function(child) {
            let childNode = nodes[+child];
            childNode.parentNode = node;
            children.push(childNode);
          });
        }

        node.childNodes = children;
        nodes.push(node);
        return length + ',';
      });
    } while (lastLength < nodes.length);

    // We should only have one root index left, which will be last in the nodes.
    return {
      documentElement: nodes.pop(),
    };
  }

  _decodeXML(text) {
    if (text.indexOf('&') < 0) {
      return text;
    }

    return text.replace(/&(#(x[0-9a-f]+|\d+)|\w+);/gi,
        function(all, entityName, number) {
      if (number) {
        if (number[0] === 'x') {
          number = parseInt(number.substring(1), 16);
        } else {
          number = +number;
        }
        return String.fromCharCode(number);
      }

      switch (entityName) {
        case 'amp':
          return '&';
        case 'lt':
          return '<';
        case 'gt':
          return '>';
        case 'quot':
          return '\"';
        case 'apos':
          return '\'';
      }
      return '&' + entityName + ';';
    });
  }
}

/**
 * Optimised CSS custom property getter/setter.
 * @class
 */
var CustomStyle = (function CustomStyleClosure() {

  // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  //              animate-css-transforms-firefox-webkit.html
  // in some versions of IE9 it is critical that ms appear in this list
  // before Moz
  var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  var _cache = Object.create(null);

  function CustomStyle() {}

  CustomStyle.getProp = function get(propName, element) {
    // check cache only when no element is given
    if (arguments.length === 1 && typeof _cache[propName] === 'string') {
      return _cache[propName];
    }

    element = element || document.documentElement;
    var style = element.style, prefixed, uPropName;

    // test standard property first
    if (typeof style[propName] === 'string') {
      return (_cache[propName] = propName);
    }

    // capitalize
    uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);

    // test vendor specific properties
    for (var i = 0, l = prefixes.length; i < l; i++) {
      prefixed = prefixes[i] + uPropName;
      if (typeof style[prefixed] === 'string') {
        return (_cache[propName] = prefixed);
      }
    }

    // If all fails then set to undefined.
    return (_cache[propName] = 'undefined');
  };

  CustomStyle.setProp = function set(propName, element, str) {
    var prop = this.getProp(propName);
    if (prop !== 'undefined') {
      element.style[prop] = str;
    }
  };

  return CustomStyle;
})();

var RenderingCancelledException = (function RenderingCancelledException() {
  function RenderingCancelledException(msg, type) {
    this.message = msg;
    this.type = type;
  }

  RenderingCancelledException.prototype = new Error();
  RenderingCancelledException.prototype.name = 'RenderingCancelledException';
  RenderingCancelledException.constructor = RenderingCancelledException;

  return RenderingCancelledException;
})();

var LinkTarget = {
  NONE: 0, // Default value.
  SELF: 1,
  BLANK: 2,
  PARENT: 3,
  TOP: 4,
};

var LinkTargetStringMap = [
  '',
  '_self',
  '_blank',
  '_parent',
  '_top'
];

/**
 * @typedef ExternalLinkParameters
 * @typedef {Object} ExternalLinkParameters
 * @property {string} url - An absolute URL.
 * @property {LinkTarget} target - The link target.
 * @property {string} rel - The link relationship.
 */

/**
 * Adds various attributes (href, title, target, rel) to hyperlinks.
 * @param {HTMLLinkElement} link - The link element.
 * @param {ExternalLinkParameters} params
 */
function addLinkAttributes(link, params) {
  var url = params && params.url;
  link.href = link.title = (url ? removeNullCharacters(url) : '');

  if (url) {
    var target = params.target;
    if (typeof target === 'undefined') {
      target = getDefaultSetting('externalLinkTarget');
    }
    link.target = LinkTargetStringMap[target];

    var rel = params.rel;
    if (typeof rel === 'undefined') {
      rel = getDefaultSetting('externalLinkRel');
    }
    link.rel = rel;
  }
}

// Gets the file name from a given URL.
function getFilenameFromUrl(url) {
  var anchor = url.indexOf('#');
  var query = url.indexOf('?');
  var end = Math.min(
    anchor > 0 ? anchor : url.length,
    query > 0 ? query : url.length);
  return url.substring(url.lastIndexOf('/', end) + 1, end);
}

function getDefaultSetting(id) {
  // The list of the settings and their default is maintained for backward
  // compatibility and shall not be extended or modified. See also global.js.
  var globalSettings = globalScope.PDFJS;
  switch (id) {
    case 'pdfBug':
      return globalSettings ? globalSettings.pdfBug : false;
    case 'disableAutoFetch':
      return globalSettings ? globalSettings.disableAutoFetch : false;
    case 'disableStream':
      return globalSettings ? globalSettings.disableStream : false;
    case 'disableRange':
      return globalSettings ? globalSettings.disableRange : false;
    case 'disableFontFace':
      return globalSettings ? globalSettings.disableFontFace : false;
    case 'disableCreateObjectURL':
      return globalSettings ? globalSettings.disableCreateObjectURL : false;
    case 'disableWebGL':
      return globalSettings ? globalSettings.disableWebGL : true;
    case 'cMapUrl':
      return globalSettings ? globalSettings.cMapUrl : null;
    case 'cMapPacked':
      return globalSettings ? globalSettings.cMapPacked : false;
    case 'postMessageTransfers':
      return globalSettings ? globalSettings.postMessageTransfers : true;
    case 'workerPort':
      return globalSettings ? globalSettings.workerPort : null;
    case 'workerSrc':
      return globalSettings ? globalSettings.workerSrc : null;
    case 'disableWorker':
      return globalSettings ? globalSettings.disableWorker : false;
    case 'maxImageSize':
      return globalSettings ? globalSettings.maxImageSize : -1;
    case 'imageResourcesPath':
      return globalSettings ? globalSettings.imageResourcesPath : '';
    case 'isEvalSupported':
      return globalSettings ? globalSettings.isEvalSupported : true;
    case 'externalLinkTarget':
      if (!globalSettings) {
        return LinkTarget.NONE;
      }
      switch (globalSettings.externalLinkTarget) {
        case LinkTarget.NONE:
        case LinkTarget.SELF:
        case LinkTarget.BLANK:
        case LinkTarget.PARENT:
        case LinkTarget.TOP:
          return globalSettings.externalLinkTarget;
      }
      warn('PDFJS.externalLinkTarget is invalid: ' +
           globalSettings.externalLinkTarget);
      // Reset the external link target, to suppress further warnings.
      globalSettings.externalLinkTarget = LinkTarget.NONE;
      return LinkTarget.NONE;
    case 'externalLinkRel':
      return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL;
    case 'enableStats':
      return !!(globalSettings && globalSettings.enableStats);
    case 'pdfjsNext':
      return !!(globalSettings && globalSettings.pdfjsNext);
    default:
      throw new Error('Unknown default setting: ' + id);
  }
}

function isExternalLinkTargetSet() {
  var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  switch (externalLinkTarget) {
    case LinkTarget.NONE:
      return false;
    case LinkTarget.SELF:
    case LinkTarget.BLANK:
    case LinkTarget.PARENT:
    case LinkTarget.TOP:
      return true;
  }
}

function isValidUrl(url, allowRelative) {
  deprecated('isValidUrl(), please use createValidAbsoluteUrl() instead.');
  var baseUrl = allowRelative ? 'http://example.com' : null;
  return createValidAbsoluteUrl(url, baseUrl) !== null;
}

export {
  CustomStyle,
  RenderingCancelledException,
  addLinkAttributes,
  isExternalLinkTargetSet,
  isValidUrl,
  getFilenameFromUrl,
  LinkTarget,
  getDefaultSetting,
  DEFAULT_LINK_REL,
  DOMCanvasFactory,
  DOMCMapReaderFactory,
  DOMSVGFactory,
  SimpleXMLParser,
};


text:
  Wenn Jenkins Subversion nach Änderungen befragt (um gegebenenfalls einen
  neuen Builds zu starten), werden alle Revisionen ignoriert, deren Commit-Kommentar
  mindestens einen der hier angegebenen regulären Ausdrücke enthält.


text:
{% load cms_tags %}

{% if not instance.hidden %}

{% for plugin in instance.child_plugin_instances %}

    {% render_plugin plugin %}

{% endfor %}

{% endif %}


text:
#pragma once

#include <string>
#include <unordered_map>

#include <folly/Range.h>

namespace facebook { namespace memcache {

class McReply;

namespace mcrouter {

// define stat_name_t
#define STAT(name,...) name##_stat,
#define STUI STAT
#define STUIR STAT
#define STSI STAT
#define STSS STAT
enum stat_name_t {
  #include "stat_list.h"
  num_stats,
};
#undef STAT
#undef STUI
#undef STUIR
#undef STSI
#undef STSS

// Forward declarations
struct proxy_request_t;
struct proxy_t;

/** statistics ftw */

struct stat_s;
typedef std::string(*string_fn_t)(void*);

enum stat_type_t {
  stat_string_fn,
  stat_string,
  stat_uint64,
  stat_int64,
  stat_double,
//  stat_percentile, // TBD
  num_stat_types
};

enum stat_group_t {
  mcproxy_stats     =        0x1,
  detailed_stats    =        0x2,
  cmd_all_stats     =        0x4,
  cmd_in_stats      =        0x8,
  cmd_out_stats     =       0x10,
  cmd_error_stats   =       0x20,
  ods_stats         =       0x40,
  timer_stats       =       0x80,
  rate_stats        =      0x100,
  count_stats       =      0x200,
  all_stats         =     0xffff, // don't want all stats to include server stats?
  server_stats      =    0x10000,
  memory_stats      =    0x20000,
  unknown_stats     = 0x10000000,
};

/** defines a statistic: name, type, and data */
struct stat_t {
  folly::StringPiece name;
  int group;
  stat_type_t type;
  int aggregate;
  union {
    string_fn_t string_fn;
    char* string;
    uint64_t uint64;
    int64_t int64;
    double dbl;
    void* pointer;
  } data;
};

/** prototypes are stupid */
void init_stats(stat_t *stats);
void stat_incr(proxy_t*, stat_name_t, int64_t);
void stat_decr(proxy_t*, stat_name_t, int64_t);
void stat_incr_safe(proxy_t*, stat_name_t);
void stat_decr_safe(proxy_t*, stat_name_t);

/**
 * Current rate of proxy->stats[idx] (which must be a rate stat),
 * units will be per second.
 *
 * Caller must have obtained stats_lock.
 */
double stats_rate_value(proxy_t* proxy, int idx);

void stat_set_uint64(proxy_t*, stat_name_t, uint64_t);
uint64_t stat_get_uint64(proxy_t*, stat_name_t);
uint64_t stat_get_config_age(const proxy_t* proxy, uint64_t now);
McReply stats_reply(proxy_t*, folly::StringPiece);
void prepare_stats(proxy_t *proxy, stat_t *stats);

}}} // facebook::memcache::mcrouter


text:
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class SearchRoute extends Route {
  @service currentUser;
  @service iliosConfig;
  @service session;

  async beforeModel(transition) {
    this.session.requireAuthentication(transition, 'login');
    const searchEnabled = await this.iliosConfig.getSearchEnabled();
    if (!searchEnabled || !this.currentUser.performsNonLearnerFunction) {
      this.transitionTo('dashboard');
    }
  }
}