text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ComboboxMultiInternal = exports.ComboboxMulti = void 0;

var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteral"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _every = _interopRequireDefault(require("lodash/every"));

var _isMatch = _interopRequireDefault(require("lodash/isMatch"));

var _react = _interopRequireWildcard(require("react"));

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _utils = require("../../../utils");

var _useFocusManagement = require("./utils/useFocusManagement");

var _state = require("./utils/state");

var _ComboboxContext = require("./ComboboxContext");

var _Combobox = require("./Combobox");

var _useComboboxRefs2 = require("./utils/useComboboxRefs");

var _useComboboxToggle = require("./utils/useComboboxToggle");

var _useScrollState = require("./utils/useScrollState");

var _templateObject;

var _excluded = ["openOnFocus", "openOnClick", "onChange", "values", "defaultValues", "onClose", "onOpen", "id"],
    _excluded2 = ["ref"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function compareOptions(optionsA, optionsB) {
  return (0, _every["default"])(optionsA, function (optionA) {
    return optionsB.find(function (optionB) {
      return (0, _isMatch["default"])(optionA, optionB);
    });
  });
}

var ComboboxMultiInternal = (0, _react.forwardRef)(function (_ref, forwardedRef) {
  var _ref$openOnFocus = _ref.openOnFocus,
      openOnFocus = _ref$openOnFocus === void 0 ? false : _ref$openOnFocus,
      _ref$openOnClick = _ref.openOnClick,
      openOnClick = _ref$openOnClick === void 0 ? true : _ref$openOnClick,
      onChange = _ref.onChange,
      values = _ref.values,
      defaultValues = _ref.defaultValues,
      onClose = _ref.onClose,
      onOpen = _ref.onOpen,
      propsID = _ref.id,
      rest = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
  var initialValues = values || defaultValues;
  var initialData = {
    options: initialValues || []
  };

  var _useReducerMachine = (0, _state.useReducerMachine)(_state.reducerMulti, _objectSpread(_objectSpread({}, _ComboboxContext.defaultMultiData), initialData), {
    inputValues: [],
    options: []
  }),
      _useReducerMachine2 = (0, _slicedToArray2["default"])(_useReducerMachine, 3),
      state = _useReducerMachine2[0],
      data = _useReducerMachine2[1],
      transition = _useReducerMachine2[2];

  var lastActionType = data.lastActionType,
      options = data.options;

  if (values !== undefined && (options.length !== values.length || !compareOptions(options, values))) {
    transition && transition(_state.ComboboxActionType.SELECT_SILENT, {
      options: values
    });
  }

  var focusManagement = (0, _useFocusManagement.useFocusManagement)(lastActionType);
  var id = (0, _utils.useID)(propsID);
  var isVisible = (0, _useComboboxToggle.useComboboxToggle)(state, options, onOpen, onClose);

  var _useComboboxRefs = (0, _useComboboxRefs2.useComboboxRefs)(forwardedRef),
      ref = _useComboboxRefs.ref,
      commonRefs = (0, _objectWithoutProperties2["default"])(_useComboboxRefs, _excluded2);

  var scrollState = (0, _useScrollState.useScrollState)();

  var context = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, commonRefs), focusManagement), scrollState), {}, {
    data: data,
    id: id,
    isVisible: isVisible,
    onChange: onChange,
    openOnClick: openOnClick,
    openOnFocus: openOnFocus,
    state: state,
    transition: transition
  });

  return _react["default"].createElement(_ComboboxContext.ComboboxMultiContext.Provider, {
    value: context
  }, _react["default"].createElement(_Combobox.ComboboxWrapper, (0, _extends2["default"])({
    id: id
  }, rest, {
    isVisible: isVisible,
    ref: ref
  })));
});
exports.ComboboxMultiInternal = ComboboxMultiInternal;
ComboboxMultiInternal.displayName = 'ComboboxMultiInternal';
var ComboboxMulti = (0, _styledComponents["default"])(ComboboxMultiInternal).attrs(function (_ref2) {
  var _ref2$display = _ref2.display,
      display = _ref2$display === void 0 ? 'flex' : _ref2$display;
  return {
    display: display
  };
}).withConfig({
  displayName: "ComboboxMulti",
  componentId: "sc-1okouq3-0"
})(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])([""])));
exports.ComboboxMulti = ComboboxMulti;
//# sourceMappingURL=ComboboxMulti.js.map


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['backbone', 'underscore', 'socket.io', 'jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    var _ = require('underscore'),
      Backbone = require('backbone'),
      io = require('socket.io-client'),
      $ = require('jquery');
    module.exports = factory(Backbone, _, io, $);
  } else {
    // Browser globals (root is window)
    factory(root.Backbone, root._, root.io, (root.jQuery || root.Zepto || root.ender || root.$));
  }
}(this, function (Backbone, _, io, $){

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Seahinet\Sales\Model\Api\Rest;

use Seahinet\Api\Model\Api\Rest\AbstractHandler;
use Seahinet\Customer\Model\Customer;
use Seahinet\Lib\Session\Segment;
use Seahinet\Oauth\Model\Token;
use Seahinet\Sales\Model\Cart as Model;
use Seahinet\Sales\Model\Collection\Cart as Collection;

class Cart extends AbstractHandler
{

    public function getCart()
    {
        $data = $this->getRequest()->getQuery();
        $columns = $this->getAttributes('cart');
        if (count($columns)) {
            if ($this->authOptions['validation'] > 0) {
                if (isset($data['openId']) && $data['openId'] === $this->authOptions['open_id']) {
                    $token = new Token;
                    $token->load($data['openId'], 'open_id');
                    unset($data['openId']);
                    $data['customer_id'] = $token['customer_id'];
                    $data['status'] = 1;
                    $data['limit'] = 1;
                    $data['desc'] = 'id';
                } else {
                    return $this->getResponse()->withStatus(400);
                }
            }
            $collection = new Collection;
            $collection->columns($columns);
            $this->filter($collection, $data);
            $result = [];
            $itemColumns = $this->getAttributes('cart_items');
            $collection->walk(function ($item) use (&$result, $itemColumns) {
                if (count($itemColumns)) {
                    $items = $item->getItems(true);
                    $items->columns($itemColumns);
                    $items->load(true, true);
                }
                $result[] = $item->toArray() + ['items' => isset($item) ? $items->toArray() : []];
            });
            return $result;
        }
        return $this->getResponse()->withStatus(403);
    }

    public function putCartItem()
    {
        if ($this->authOptions['validation'] > 0) {
            $data = $this->getRequest()->getPost();
            if ((!empty($data['id']) || !empty($data['product_id']) && !empty($data['warehouse_id'])) && !empty($data['qty']) &&
                    isset($data['openId']) && $data['openId'] === $this->authOptions['open_id']) {
                $token = new Token;
                $token->load($data['openId'], 'open_id');
                unset($data['openId']);
                $segment = new Segment('customer');
                $segment->set('hasLoggedIn', true)
                        ->set('customer', (new Customer)->setId($token['customer_id']));
                $cart = Model::instance();
                if (!empty($data['id'])) {
                    $cart->changeQty($data['id'], $data['qty']);
                } else {
                    $cart->addItem($data['product_id'], $data['qty'], $data['warehouse_id'], $data['options'] ?? [], $data['sku'] ?? '');
                }
                return $this->getResponse()->withStatus(202);
            } else {
                return $this->getResponse()->withStatus(400);
            }
        }
        return $this->getResponse()->withStatus(403);
    }

    public function deleteCartItem()
    {
        if ($this->authOptions['validation'] > 0) {
            $data = $this->getRequest()->getPost();
            if (!empty($data['id']) && isset($data['openId']) && $data['openId'] === $this->authOptions['open_id']) {
                $token = new Token;
                $token->load($data['openId'], 'open_id');
                unset($data['openId']);
                $segment = new Segment('customer');
                $segment->set('hasLoggedIn', true)
                        ->set('customer', (new Customer)->setId($token['customer_id']));
                $cart = Model::instance();
                $cart->removeItem($data['id']);
                return $this->getResponse()->withStatus(202);
            } else {
                return $this->getResponse()->withStatus(400);
            }
        }
        return $this->getResponse()->withStatus(403);
    }

}


text:
#include "audio_stream.h"
#include "file_output.h"
#include "stream_configuration.h"
#include "http_stream.h"
#include "file_stream.h"
#include "caching_stream.h"

#include <CommonCrypto/CommonDigest.h>

/*
 * Some servers may send an incorrect MIME type for the audio stream.
 * By uncommenting the following line, relaxed checks will be
 * performed for the MIME type. This allows playing more
 * streams:
 */
//#define AS_RELAX_CONTENT_TYPE_CHECK 1

//#define AS_DEBUG 1

#if !defined (AS_DEBUG)
#define AS_TRACE(...) do {} while (0)
#else
#define AS_TRACE(...) printf(__VA_ARGS__)
#endif

namespace astreamer {

/* Create HTTP stream as Audio_Stream (this) as the delegate */
Audio_Stream::Audio_Stream() :
    m_delegate(0),
    m_inputStreamRunning(false),
    m_audioStreamParserRunning(false),
    m_contentLength(0),
    m_state(STOPPED),
    m_inputStream(0),
    m_audioQueue(0),
    m_watchdogTimer(0),
    m_audioFileStream(0),
    m_audioConverter(0),
    m_initializationError(noErr),
    m_outputBufferSize(Stream_Configuration::configuration()->bufferSize),
    m_outputBuffer(new UInt8[m_outputBufferSize]),
    m_dataOffset(0),
    m_seekPosition(0),
    m_bounceCount(0),
    m_firstBufferingTime(0),
#if defined (AS_RELAX_CONTENT_TYPE_CHECK)
    m_strictContentTypeChecking(false),
#else
    m_strictContentTypeChecking(true),
#endif
    m_defaultContentType(CFSTR("audio/mpeg")),
    m_contentType(NULL),

    m_fileOutput(0),
    m_outputFile(NULL),
    m_queuedHead(0),
    m_queuedTail(0),
    m_cachedDataSize(0),
    m_processedPacketsCount(0),
    m_audioDataByteCount(0),
    m_packetDuration(0),
    m_bitrateBufferIndex(0),
    m_outputVolume(1.0),
    m_queueCanAcceptPackets(true),
    m_converterRunOutOfData(false)
{
    memset(&m_srcFormat, 0, sizeof m_srcFormat);

    memset(&m_dstFormat, 0, sizeof m_dstFormat);

    Stream_Configuration *config = Stream_Configuration::configuration();

    m_dstFormat.mSampleRate = config->outputSampleRate;
    m_dstFormat.mFormatID = kAudioFormatLinearPCM;
    m_dstFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
    m_dstFormat.mBytesPerPacket = 4;
    m_dstFormat.mFramesPerPacket = 1;
    m_dstFormat.mBytesPerFrame = 4;
    m_dstFormat.mChannelsPerFrame = 2;
    m_dstFormat.mBitsPerChannel = 16;
}

Audio_Stream::~Audio_Stream()
{
    if (m_defaultContentType) {
        CFRelease(m_defaultContentType), m_defaultContentType = NULL;
    }

    if (m_contentType) {
        CFRelease(m_contentType), m_contentType = NULL;
    }

    close();

    delete [] m_outputBuffer, m_outputBuffer = 0;

    if (m_inputStream) {
        m_inputStream->m_delegate = 0;
        delete m_inputStream, m_inputStream = 0;
    }

    if (m_audioConverter) {
        AudioConverterDispose(m_audioConverter), m_audioConverter = 0;
    }

    if (m_fileOutput) {
        delete m_fileOutput, m_fileOutput = 0;
    }
}

void Audio_Stream::open()
{
    open(0);
}

void Audio_Stream::open(Input_Stream_Position *position)
{
    if (m_inputStreamRunning || m_audioStreamParserRunning) {
        AS_TRACE("%s: already running: return\n", __PRETTY_FUNCTION__);
        return;
    }

    m_contentLength = 0;
    m_seekPosition = 0;
    m_bounceCount = 0;
    m_firstBufferingTime = 0;
    m_processedPacketsCount = 0;
    m_bitrateBufferIndex = 0;
    m_initializationError = noErr;
    m_converterRunOutOfData = false;

    if (m_watchdogTimer) {
        CFRunLoopTimerInvalidate(m_watchdogTimer);
        CFRelease(m_watchdogTimer), m_watchdogTimer = 0;
    }

    Stream_Configuration *config = Stream_Configuration::configuration();

    if (m_contentType) {
        CFRelease(m_contentType), m_contentType = NULL;
    }

    bool success = false;

    if (position) {
        if (m_inputStream) {
            success = m_inputStream->open(*position);
        }
    } else {
        if (m_inputStream) {
            success = m_inputStream->open();
        }
    }

    if (success) {
        AS_TRACE("%s: HTTP stream opened, buffering...\n", __PRETTY_FUNCTION__);
        m_inputStreamRunning = true;
        setState(BUFFERING);

        if (config->startupWatchdogPeriod > 0) {
            /*
             * Start the WD if we have one requested. In this way we can track
             * that the stream doesn't stuck forever on the buffering state
             * (for instance some network error condition)
             */

            CFRunLoopTimerContext ctx = {0, this, NULL, NULL, NULL};

            m_watchdogTimer = CFRunLoopTimerCreate(NULL,
                                                   CFAbsoluteTimeGetCurrent() + config->startupWatchdogPeriod,
                                                   0,
                                                   0,
                                                   0,
                                                   watchdogTimerCallback,
                                                   &ctx);

            AS_TRACE("Starting the startup watchdog, period %i seconds\n", config->startupWatchdogPeriod);

            CFRunLoopAddTimer(CFRunLoopGetCurrent(), m_watchdogTimer, kCFRunLoopCommonModes);
        }
    } else {
        AS_TRACE("%s: failed to open the HTTP stream\n", __PRETTY_FUNCTION__);
        closeAndSignalError(AS_ERR_OPEN);
    }
}

void Audio_Stream::close()
{
    AS_TRACE("%s: enter\n", __PRETTY_FUNCTION__);

    if (m_watchdogTimer) {
        CFRunLoopTimerInvalidate(m_watchdogTimer);
        CFRelease(m_watchdogTimer), m_watchdogTimer = 0;
    }

    /* Close the HTTP stream first so that the audio stream parser
       isn't fed with more data to parse */
    if (m_inputStreamRunning) {
        if (m_inputStream) {
            m_inputStream->close();
        }
        m_inputStreamRunning = false;
    }

    if (m_audioStreamParserRunning) {
        if (m_audioFileStream) {
            if (AudioFileStreamClose(m_audioFileStream) != 0) {
                AS_TRACE("%s: AudioFileStreamClose failed\n", __PRETTY_FUNCTION__);
            }
            m_audioFileStream = 0;
        }
        m_audioStreamParserRunning = false;
    }

    closeAudioQueue();

    if (FAILED != state()) {
        /*
         * Set the stream state to stopped if the stream was stopped successfully.
         * We don't want to cause a spurious stopped state as the fail state should
         * be the final state in case the stream failed.
         */
        setState(STOPPED);
    }

    /*
     * Free any remaining queud packets for encoding.
     */
    queued_packet_t *cur = m_queuedHead;
    while (cur) {
        queued_packet_t *tmp = cur->next;
        free(cur);
        cur = tmp;
    }
    m_queuedHead = m_queuedTail = 0;
    m_cachedDataSize = 0;

    AS_TRACE("%s: leave\n", __PRETTY_FUNCTION__);
}

void Audio_Stream::pause()
{
    audioQueue()->pause();
}

unsigned Audio_Stream::timePlayedInSeconds()
{
    if (m_audioStreamParserRunning) {
        return m_seekPosition + audioQueue()->timePlayedInSeconds();
    }
    return 0;
}

unsigned Audio_Stream::durationInSeconds()
{
    unsigned duration = 0;
    unsigned bitrate = this->bitrate();

    if (bitrate == 0) {
        goto out;
    }

    double d;

    if (m_audioDataByteCount > 0) {
        d = m_audioDataByteCount;
    } else {
        d = contentLength();
    }

    duration = d / (bitrate * 0.125);

out:
    return duration;
}

void Audio_Stream::seekToTime(unsigned newSeekTime)
{
    if (state() == SEEKING) {
        return;
    } else {
        setState(SEEKING);
    }

    Input_Stream_Position position = streamPositionForTime(newSeekTime);

    if (position.start == 0 && position.end == 0) {
        return;
    }

    UInt64 originalContentLength = m_contentLength;

    close();

    AS_TRACE("Seeking position %llu\n", position.start);

    open(&position);

    setSeekPosition(newSeekTime);
    setContentLength(originalContentLength);
}

Input_Stream_Position Audio_Stream::streamPositionForTime(unsigned newSeekTime)
{
    Input_Stream_Position position;
    position.start = 0;
    position.end   = 0;

    unsigned duration = durationInSeconds();
    if (!(duration > 0)) {
        return position;
    }

    double offset = (double)newSeekTime / (double)duration;
    UInt64 seekByteOffset = m_dataOffset + offset * (contentLength() - m_dataOffset);

    position.start = seekByteOffset;
    position.end = contentLength();

    double packetDuration = m_srcFormat.mFramesPerPacket / m_srcFormat.mSampleRate;

    if (packetDuration > 0 && bitrate() > 0) {
        UInt32 ioFlags = 0;
        SInt64 packetAlignedByteOffset;
        SInt64 seekPacket = floor((double)newSeekTime / packetDuration);

        OSStatus err = AudioFileStreamSeek(m_audioFileStream, seekPacket, &packetAlignedByteOffset, &ioFlags);
        if (!err) {
            position.start = packetAlignedByteOffset + m_dataOffset;
        }
    }

    return position;
}

void Audio_Stream::setVolume(float volume)
{
    if (volume < 0) {
        volume = 0;
    }
    if (volume > 1.0) {
        volume = 1.0;
    }
    // Store the volume so it will be used consequently when the queue plays
    m_outputVolume = volume;

    if (m_audioQueue) {
        m_audioQueue->setVolume(volume);
    }
}

void Audio_Stream::setPlayRate(float playRate)
{
    if (m_audioQueue) {
        m_audioQueue->setPlayRate(playRate);
    }
}

void Audio_Stream::setUrl(CFURLRef url)
{
    if (m_inputStream) {
        delete m_inputStream, m_inputStream = 0;
    }

    if (HTTP_Stream::canHandleUrl(url)) {
        Stream_Configuration *config = Stream_Configuration::configuration();

        if (config->cacheEnabled) {
            Caching_Stream *cache = new Caching_Stream(new HTTP_Stream());

            CFStringRef cacheIdentifier = createCacheIdentifierForURL(url);

            cache->setCacheIdentifier(cacheIdentifier);

            CFRelease(cacheIdentifier);

            m_inputStream = cache;
        } else {
            m_inputStream = new HTTP_Stream();
        }

        m_inputStream->m_delegate = this;
    } else if (File_Stream::canHandleUrl(url)) {
        m_inputStream = new File_Stream();
        m_inputStream->m_delegate = this;
    }

    if (m_inputStream) {
        m_inputStream->setUrl(url);
    }
}

void Audio_Stream::setStrictContentTypeChecking(bool strictChecking)
{
    m_strictContentTypeChecking = strictChecking;
}

void Audio_Stream::setDefaultContentType(CFStringRef defaultContentType)
{
    if (m_defaultContentType) {
        CFRelease(m_defaultContentType), m_defaultContentType = 0;
    }
    if (defaultContentType) {
        m_defaultContentType = CFStringCreateCopy(kCFAllocatorDefault, defaultContentType);
    }
}

void Audio_Stream::setSeekPosition(unsigned seekPosition)
{
    m_seekPosition = seekPosition;
}

void Audio_Stream::setContentLength(UInt64 contentLength)
{
    m_contentLength = contentLength;
}

void Audio_Stream::setOutputFile(CFURLRef url)
{
    if (m_fileOutput) {
        delete m_fileOutput, m_fileOutput = 0;
    }
    if (url) {
        m_fileOutput = new File_Output(url);
    }
    m_outputFile = url;
}

CFURLRef Audio_Stream::outputFile()
{
    return m_outputFile;
}

Audio_Stream::State Audio_Stream::state()
{
    return m_state;
}

CFStringRef Audio_Stream::sourceFormatDescription()
{
    unsigned char formatID[5];
    *(UInt32 *)formatID = OSSwapHostToBigInt32(m_srcFormat.mFormatID);

    formatID[4] = '\0';

    CFStringRef formatDescription = CFStringCreateWithFormat(NULL,
                                                            NULL,
                                                            CFSTR("formatID: %s, sample rate: %f"),
                                                            formatID,
                                                            m_srcFormat.mSampleRate);

    return formatDescription;
}

CFStringRef Audio_Stream::contentType()
{
    return m_contentType;
}

CFStringRef Audio_Stream::createCacheIdentifierForURL(CFURLRef url)
{
    CFStringRef urlString = CFURLGetString(url);
    CFStringRef urlHash = createHashForString(urlString);

    CFStringRef cacheIdentifier = CFStringCreateWithFormat(NULL, NULL, CFSTR("FSCache-%@"), urlHash);

    CFRelease(urlHash);

    return cacheIdentifier;
}

size_t Audio_Stream::cachedDataSize()
{
    return m_cachedDataSize;
}

AudioFileTypeID Audio_Stream::audioStreamTypeFromContentType(CFStringRef contentType)
{
    AudioFileTypeID fileTypeHint = kAudioFileMP3Type;

    if (!contentType) {
        AS_TRACE("***** Unable to detect the audio stream type: missing content-type! *****\n");
        goto out;
    }

    if (CFStringCompare(contentType, CFSTR("audio/mpeg"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileMP3Type;
        AS_TRACE("kAudioFileMP3Type detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/x-wav"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileWAVEType;
        AS_TRACE("kAudioFileWAVEType detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/x-aifc"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileAIFCType;
        AS_TRACE("kAudioFileAIFCType detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/x-aiff"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileAIFFType;
        AS_TRACE("kAudioFileAIFFType detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/x-m4a"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileM4AType;
        AS_TRACE("kAudioFileM4AType detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/mp4"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileMPEG4Type;
        AS_TRACE("kAudioFileMPEG4Type detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/x-caf"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileCAFType;
        AS_TRACE("kAudioFileCAFType detected\n");
    } else if (CFStringCompare(contentType, CFSTR("audio/aac"), 0) == kCFCompareEqualTo ||
               CFStringCompare(contentType, CFSTR("audio/aacp"), 0) == kCFCompareEqualTo) {
        fileTypeHint = kAudioFileAAC_ADTSType;
        AS_TRACE("kAudioFileAAC_ADTSType detected\n");
    } else {
        AS_TRACE("***** Unable to detect the audio stream type *****\n");
    }

out:
    return fileTypeHint;
}

void Audio_Stream::audioQueueStateChanged(Audio_Queue::State state)
{
    if (state == Audio_Queue::RUNNING) {
        setState(PLAYING);

        float currentVolume = m_audioQueue->volume();

        if (currentVolume != m_outputVolume) {
            m_audioQueue->setVolume(m_outputVolume);
        }
    } else if (state == Audio_Queue::IDLE) {
        setState(STOPPED);
    } else if (state == Audio_Queue::PAUSED) {
        setState(PAUSED);
    }
}

void Audio_Stream::audioQueueBuffersEmpty()
{
    AS_TRACE("%s: enter\n", __PRETTY_FUNCTION__);

    Stream_Configuration *config = Stream_Configuration::configuration();

    if (m_inputStreamRunning && FAILED != state()) {
        /* Still feeding the audio queue with data,
           don't stop yet */
        setState(BUFFERING);

        if (m_firstBufferingTime == 0) {
            // Never buffered, just increase the counter
            m_firstBufferingTime = CFAbsoluteTimeGetCurrent();
            m_bounceCount++;

            AS_TRACE("stream buffered, increasing bounce count %zu, interval %i\n", m_bounceCount, config->bounceInterval);
        } else {
            // Buffered before, calculate the difference
            CFAbsoluteTime cur = CFAbsoluteTimeGetCurrent();

            int diff = cur - m_firstBufferingTime;

            if (diff >= config->bounceInterval) {
                // More than bounceInterval seconds passed from the last
                // buffering. So not a continuous bouncing. Reset the
                // counters.
                m_bounceCount = 0;
                m_firstBufferingTime = 0;

                AS_TRACE("%i seconds passed from last buffering, resetting counters, interval %i\n", diff, config->bounceInterval);
            } else {
                m_bounceCount++;

                AS_TRACE("%i seconds passed from last buffering, increasing bounce count to %zu, interval %i\n", diff, m_bounceCount, config->bounceInterval);
            }
        }

        // Check if we have reached the bounce state
        if (m_bounceCount >= config->maxBounceCount) {
            closeAndSignalError(AS_ERR_BOUNCING);
        }

        return;
    }

    // Keep enqueuing the packets in the queue until we have them

    int count = cachedDataCount();

    AS_TRACE("%i cached packets, enqueuing\n", count);

    if (count > 0) {
        enqueueCachedData(0);
    } else {
        AS_TRACE("%s: closing the audio queue\n", __PRETTY_FUNCTION__);

        close();
    }
}

void Audio_Stream::audioQueueOverflow()
{
    m_queueCanAcceptPackets = false;
}

void Audio_Stream::audioQueueUnderflow()
{
    m_queueCanAcceptPackets = true;
}

void Audio_Stream::audioQueueInitializationFailed()
{
    if (m_inputStreamRunning) {
        if (m_inputStream) {
            m_inputStream->close();
        }
        m_inputStreamRunning = false;
    }

    setState(FAILED);

    if (m_delegate) {
        if (audioQueue()->m_lastError == kAudioFormatUnsupportedDataFormatError) {
            m_delegate->audioStreamErrorOccurred(AS_ERR_UNSUPPORTED_FORMAT);
        } else {
            m_delegate->audioStreamErrorOccurred(AS_ERR_STREAM_PARSE);
        }
    }
}

void Audio_Stream::audioQueueFinishedPlayingPacket()
{
    int count = cachedDataCount();

    if (count > 0) {
        enqueueCachedData(0);
    }
}

void Audio_Stream::streamIsReadyRead()
{
    if (m_audioStreamParserRunning) {
        AS_TRACE("%s: parser already running!\n", __PRETTY_FUNCTION__);
        return;
    }

    CFStringRef audioContentType = CFSTR("audio/");
    const CFIndex audioContentTypeLength = CFStringGetLength(audioContentType);
    bool matchesAudioContentType = false;

    CFStringRef contentType = 0;

    if (m_inputStream) {
        contentType = m_inputStream->contentType();
    }

    if (m_contentType) {
        CFRelease(m_contentType), m_contentType = 0;
    }
    if (contentType) {
        m_contentType = CFStringCreateCopy(kCFAllocatorDefault, contentType);

        /* Check if the stream's MIME type begins with audio/ */
        matchesAudioContentType = (kCFCompareEqualTo ==
                                    CFStringCompareWithOptions(contentType, CFSTR("audio/"),
                                                               CFRangeMake(0, audioContentTypeLength),
                                                               0));
    }

    if (m_strictContentTypeChecking && !matchesAudioContentType) {
        closeAndSignalError(AS_ERR_OPEN);
        return;
    }

    m_audioDataByteCount = 0;

    /* OK, it should be an audio stream, let's try to open it */
    OSStatus result = AudioFileStreamOpen(this,
                                          propertyValueCallback,
                                          streamDataCallback,
                                          audioStreamTypeFromContentType(contentType),
                                          &m_audioFileStream);

    if (result == 0) {
        AS_TRACE("%s: audio file stream opened.\n", __PRETTY_FUNCTION__);
        m_audioStreamParserRunning = true;
    } else {
        closeAndSignalError(AS_ERR_OPEN);
    }
}

void Audio_Stream::streamHasBytesAvailable(UInt8 *data, UInt32 numBytes)
{
    AS_TRACE("%s: %u bytes\n", __FUNCTION__, (unsigned int)numBytes);

    if (!m_inputStreamRunning) {
        AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
        return;
    }

    if (m_fileOutput) {
        m_fileOutput->write(data, numBytes);
    }

    if (m_audioStreamParserRunning) {
        OSStatus result = AudioFileStreamParseBytes(m_audioFileStream, numBytes, data, 0);

        if (result != 0) {
            AS_TRACE("%s: AudioFileStreamParseBytes error %d\n", __PRETTY_FUNCTION__, (int)result);
            closeAndSignalError(AS_ERR_STREAM_PARSE);
        } else if (m_initializationError == kAudioConverterErr_FormatNotSupported) {
            AS_TRACE("Audio stream initialization failed due to unsupported format\n");
            closeAndSignalError(AS_ERR_UNSUPPORTED_FORMAT);
        } else if (m_initializationError != noErr) {
            AS_TRACE("Audio stream initialization failed due to unknown error\n");
            closeAndSignalError(AS_ERR_OPEN);
        }
    }
}

void Audio_Stream::streamEndEncountered()
{
    AS_TRACE("%s\n", __PRETTY_FUNCTION__);

    if (!m_inputStreamRunning) {
        AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
        return;
    }

    setState(END_OF_FILE);

    if (m_inputStream) {
        m_inputStream->close();
    }
    m_inputStreamRunning = false;
}

void Audio_Stream::streamErrorOccurred()
{
    AS_TRACE("%s\n", __PRETTY_FUNCTION__);

    if (!m_inputStreamRunning) {
        AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
        return;
    }

    closeAndSignalError(AS_ERR_NETWORK);
}

void Audio_Stream::streamMetaDataAvailable(std::map<CFStringRef,CFStringRef> metaData)
{
    if (m_delegate) {
        m_delegate->audioStreamMetaDataAvailable(metaData);
    }
}

/* private */

CFStringRef Audio_Stream::createHashForString(CFStringRef str)
{
    UInt8 buf[4096];
    CFIndex usedBytes = 0;

    CFStringGetBytes(str,
                     CFRangeMake(0, CFStringGetLength(str)),
                     kCFStringEncodingUTF8,
                     '?',
                     false,
                     buf,
                     4096,
                     &usedBytes);

    CC_SHA1_CTX hashObject;
    CC_SHA1_Init(&hashObject);

    CC_SHA1_Update(&hashObject,
                   (const void *)buf,
                   (CC_LONG)usedBytes);

    unsigned char digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1_Final(digest, &hashObject);

    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }

    return CFStringCreateWithCString(kCFAllocatorDefault,
                                       (const char *)hash,
                                       kCFStringEncodingUTF8);
}

Audio_Queue* Audio_Stream::audioQueue()
{
    if (!m_audioQueue) {
        AS_TRACE("No audio queue, creating\n");

        m_audioQueue = new Audio_Queue();

        m_audioQueue->m_delegate = this;
        m_audioQueue->m_streamDesc = m_dstFormat;

        m_audioQueue->m_initialOutputVolume = m_outputVolume;

        m_queueCanAcceptPackets = true;
    }
    return m_audioQueue;
}

void Audio_Stream::closeAudioQueue()
{
    if (!m_audioQueue) {
        return;
    }

    AS_TRACE("Releasing audio queue\n");

    m_audioQueue->m_delegate = 0;
    delete m_audioQueue, m_audioQueue = 0;
}

UInt64 Audio_Stream::contentLength()
{
    if (m_contentLength == 0) {
        if (m_inputStream) {
            m_contentLength = m_inputStream->contentLength();
        }
    }
    return m_contentLength;
}

void Audio_Stream::closeAndSignalError(int errorCode)
{
    AS_TRACE("%s: error %i\n", __PRETTY_FUNCTION__, errorCode);

    setState(FAILED);
    close();

    if (m_delegate) {
        m_delegate->audioStreamErrorOccurred(errorCode);
    }
}

void Audio_Stream::setState(State state)
{
    if (m_state == state) {
        return;
    }

    m_state = state;

    if (m_delegate) {
        m_delegate->audioStreamStateChanged(m_state);
    }
}

void Audio_Stream::setCookiesForStream(AudioFileStreamID inAudioFileStream)
{
    OSStatus err;

    // get the cookie size
    UInt32 cookieSize;
    Boolean writable;

    err = AudioFileStreamGetPropertyInfo(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, &writable);
    if (err) {
        return;
    }

    // get the cookie data
    void* cookieData = calloc(1, cookieSize);
    err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, cookieData);
    if (err) {
        free(cookieData);
        return;
    }

    // set the cookie on the queue.
    if (m_audioConverter) {
        AudioConverterSetProperty(m_audioConverter, kAudioConverterDecompressionMagicCookie, cookieSize, cookieData);
    }

    free(cookieData);
}

unsigned Audio_Stream::bitrate()
{
    if (m_processedPacketsCount < kAudioStreamBitrateBufferSize) {
        return 0;
    }
    double sum = 0;

    for (size_t i=0; i < kAudioStreamBitrateBufferSize; i++) {
        sum += m_bitrateBuffer[i];
    }

    return sum / kAudioStreamBitrateBufferSize;
}

void Audio_Stream::watchdogTimerCallback(CFRunLoopTimerRef timer, void *info)
{
    Audio_Stream *THIS = (Audio_Stream *)info;

    if (PLAYING != THIS->state()) {
        AS_TRACE("The stream startup watchdog activated: stream didn't start to play soon enough\n");

        THIS->closeAndSignalError(AS_ERR_OPEN);
    }
}

int Audio_Stream::cachedDataCount()
{
    int count = 0;
    queued_packet_t *cur = m_queuedHead;
    while (cur) {
        cur = cur->next;
        count++;
    }
    return count;
}

void Audio_Stream::enqueueCachedData(int minPacketsRequired)
{
    if (!m_queueCanAcceptPackets) {
        AS_TRACE("Queue cannot accept packets, return\n");
        return;
    }

    if (m_converterRunOutOfData) {
        AS_TRACE("Converted run out of data\n");

        if (m_audioConverter) {
            AudioConverterDispose(m_audioConverter);
        }

        OSStatus err = AudioConverterNew(&(m_srcFormat),
                                         &(m_dstFormat),
                                         &(m_audioConverter));

        if (err) {
            AS_TRACE("Error in creating an audio converter, error %i\n", err);

           m_initializationError = err;
        }

        m_converterRunOutOfData = false;
    }

    if (state() == PAUSED) {
        return;
    }

    int count = cachedDataCount();

    if (count > minPacketsRequired) {
        AudioBufferList outputBufferList;
        outputBufferList.mNumberBuffers = 1;
        outputBufferList.mBuffers[0].mNumberChannels = m_dstFormat.mChannelsPerFrame;
        outputBufferList.mBuffers[0].mDataByteSize = m_outputBufferSize;
        outputBufferList.mBuffers[0].mData = m_outputBuffer;

        AudioStreamPacketDescription description;
        description.mStartOffset = 0;
        description.mDataByteSize = m_outputBufferSize;
        description.mVariableFramesInPacket = 0;

        UInt32 ioOutputDataPackets = m_outputBufferSize / m_dstFormat.mBytesPerPacket;

        AS_TRACE("calling AudioConverterFillComplexBuffer\n");

        Stream_Configuration *config = Stream_Configuration::configuration();

        OSStatus err = AudioConverterFillComplexBuffer(m_audioConverter,
                                                       &encoderDataCallback,
                                                       this,
                                                       &ioOutputDataPackets,
                                                       &outputBufferList,
                                                       NULL);
        if (err == noErr) {
            AS_TRACE("%i output bytes available for the audio queue\n", (unsigned int)ioOutputDataPackets);

            if (m_watchdogTimer) {
                AS_TRACE("The stream started to play, canceling the watchdog\n");

                CFRunLoopTimerInvalidate(m_watchdogTimer);
                CFRelease(m_watchdogTimer), m_watchdogTimer = 0;
            }

            setState(PLAYING);

            audioQueue()->handleAudioPackets(outputBufferList.mBuffers[0].mDataByteSize,
                                                   outputBufferList.mNumberBuffers,
                                                   outputBufferList.mBuffers[0].mData,
                                                   &description);

            if (m_delegate) {
                m_delegate->samplesAvailable(outputBufferList, description);
            }

            for(std::list<queued_packet_t*>::iterator iter = m_processedPackets.begin();
                iter != m_processedPackets.end(); iter++) {
                queued_packet_t *cur = *iter;

                m_cachedDataSize -= cur->desc.mDataByteSize;

                if (m_cachedDataSize < config->maxPrebufferedByteCount) {
                    AS_TRACE("Cache underflow, enabling the HTTP stream\n");

                    if (m_inputStream) {
                        m_inputStream->setScheduledInRunLoop(true);
                    }
                }

                free(cur);
            }
            m_processedPackets.clear();
        } else {
            AS_TRACE("AudioConverterFillComplexBuffer failed, error %i\n", err);
        }
    } else {
        AS_TRACE("Less than %i packets queued, returning...\n", minPacketsRequired);
    }
}

OSStatus Audio_Stream::encoderDataCallback(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData, AudioStreamPacketDescription **outDataPacketDescription, void *inUserData)
{
    Audio_Stream *THIS = (Audio_Stream *)inUserData;

    AS_TRACE("encoderDataCallback called\n");

    // Dequeue one packet per time for the decoder
    queued_packet_t *front = THIS->m_queuedHead;

    if (!front) {
        /*
         * End of stream - Inside your input procedure, you must set the total amount of packets read and the sizes of the data in the AudioBufferList to zero. The input procedure should also return noErr. This will signal the AudioConverter that you are out of data. More specifically, set ioNumberDataPackets and ioBufferList->mDataByteSize to zero in your input proc and return noErr. Where ioNumberDataPackets is the amount of data converted and ioBufferList->mDataByteSize is the size of the amount of data converted in each AudioBuffer within your input procedure callback. Your input procedure may be called a few more times; you should just keep returning zero and noErr.
         */

        AS_TRACE("run out of data to provide for encoding\n");

        THIS->m_converterRunOutOfData = true;

        *ioNumberDataPackets = 0;

        ioData->mBuffers[0].mDataByteSize = 0;

        return noErr;
    } else {
        THIS->m_converterRunOutOfData = false;
    }

    *ioNumberDataPackets = 1;

    ioData->mBuffers[0].mData = front->data;
	ioData->mBuffers[0].mDataByteSize = front->desc.mDataByteSize;
	ioData->mBuffers[0].mNumberChannels = THIS->m_srcFormat.mChannelsPerFrame;

    if (outDataPacketDescription) {
        *outDataPacketDescription = &front->desc;
    }

    THIS->m_queuedHead = front->next;

    front->next = NULL;
    THIS->m_processedPackets.push_front(front);

    THIS->m_processedPacketsCount++;

    return noErr;
}

/* This is called by audio file stream parser when it finds property values */
void Audio_Stream::propertyValueCallback(void *inClientData, AudioFileStreamID inAudioFileStream, AudioFileStreamPropertyID inPropertyID, UInt32 *ioFlags)
{
    AS_TRACE("%s\n", __PRETTY_FUNCTION__);
    Audio_Stream *THIS = static_cast<Audio_Stream*>(inClientData);

    if (!THIS->m_audioStreamParserRunning) {
        AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
        return;
    }

    switch (inPropertyID) {
        case kAudioFileStreamProperty_DataOffset: {
            SInt64 offset;
            UInt32 offsetSize = sizeof(offset);
            OSStatus result = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataOffset, &offsetSize, &offset);
            if (result == 0) {
                THIS->m_dataOffset = offset;
            } else {
                AS_TRACE("%s: reading kAudioFileStreamProperty_DataOffset property failed\n", __PRETTY_FUNCTION__);
            }

            break;
        }
        case kAudioFileStreamProperty_AudioDataByteCount: {
            UInt32 byteCountSize = sizeof(UInt64);
            OSStatus err = AudioFileStreamGetProperty(inAudioFileStream,
                                                      kAudioFileStreamProperty_AudioDataByteCount,
                                                      &byteCountSize, &THIS->m_audioDataByteCount);
            if (err) {
                THIS->m_audioDataByteCount = 0;
            }
            break;
        }
        case kAudioFileStreamProperty_ReadyToProducePackets: {
            memset(&(THIS->m_srcFormat), 0, sizeof THIS->m_srcFormat);
            UInt32 asbdSize = sizeof(THIS->m_srcFormat);
            UInt32 formatListSize = 0;
            Boolean writable;
            OSStatus err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataFormat, &asbdSize, &(THIS->m_srcFormat));
            if (err) {
                AS_TRACE("Unable to set the src format\n");
                break;
            }

            if (!AudioFileStreamGetPropertyInfo(inAudioFileStream, kAudioFileStreamProperty_FormatList, &formatListSize, &writable)) {
                void *formatListData = calloc(1, formatListSize);
                if (!AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_FormatList, &formatListSize, formatListData)) {
                    for (int i=0; i < formatListSize; i += sizeof(AudioFormatListItem)) {
                        AudioStreamBasicDescription *pasbd = (AudioStreamBasicDescription *)formatListData + i;

                        if (pasbd->mFormatID == kAudioFormatMPEG4AAC_HE ||
                            pasbd->mFormatID == kAudioFormatMPEG4AAC_HE_V2) {
                            THIS->m_srcFormat = *pasbd;
                            break;
                        }
                    }
                }

                free(formatListData);
            }

            THIS->m_packetDuration = THIS->m_srcFormat.mFramesPerPacket / THIS->m_srcFormat.mSampleRate;

            AS_TRACE("srcFormat, bytes per packet %i\n", (unsigned int)THIS->m_srcFormat.mBytesPerPacket);

            if (THIS->m_audioConverter) {
                AudioConverterDispose(THIS->m_audioConverter);
            }

            err = AudioConverterNew(&(THIS->m_srcFormat),
                                    &(THIS->m_dstFormat),
                                    &(THIS->m_audioConverter));

            if (err) {
                AS_TRACE("Error in creating an audio converter, error %i\n", err);

                THIS->m_initializationError = err;
            }

            THIS->setCookiesForStream(inAudioFileStream);

            THIS->audioQueue()->handlePropertyChange(inAudioFileStream, inPropertyID, ioFlags);
            break;
        }
        default: {
            THIS->audioQueue()->handlePropertyChange(inAudioFileStream, inPropertyID, ioFlags);
            break;
        }
    }
}

/* This is called by audio file stream parser when it finds packets of audio */
void Audio_Stream::streamDataCallback(void *inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void *inInputData, AudioStreamPacketDescription *inPacketDescriptions)
{
    AS_TRACE("%s: inNumberBytes %u, inNumberPackets %u\n", __FUNCTION__, inNumberBytes, inNumberPackets);

    Stream_Configuration *config = Stream_Configuration::configuration();
    Audio_Stream *THIS = static_cast<Audio_Stream*>(inClientData);

    if (!THIS->m_audioStreamParserRunning) {
        AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
        return;
    }

    for (int i = 0; i < inNumberPackets; i++) {
        /* Allocate the packet */
        UInt32 size = inPacketDescriptions[i].mDataByteSize;
        queued_packet_t *packet = (queued_packet_t *)malloc(sizeof(queued_packet_t) + size);

        if (THIS->m_bitrateBufferIndex < kAudioStreamBitrateBufferSize) {
            // Only keep sampling for one buffer cycle; this is to keep the counters (for instance) duration
            // stable.

            THIS->m_bitrateBuffer[THIS->m_bitrateBufferIndex++] = 8 * inPacketDescriptions[i].mDataByteSize / THIS->m_packetDuration;
        }

        /* Prepare the packet */
        packet->next = NULL;
        packet->desc = inPacketDescriptions[i];
        packet->desc.mStartOffset = 0;
        memcpy(packet->data, (const char *)inInputData + inPacketDescriptions[i].mStartOffset,
               size);

        if (THIS->m_queuedHead == NULL) {
            THIS->m_queuedHead = THIS->m_queuedTail = packet;
        } else {
            THIS->m_queuedTail->next = packet;
            THIS->m_queuedTail = packet;
        }

        THIS->m_cachedDataSize += size;

        if (THIS->m_cachedDataSize >= config->maxPrebufferedByteCount) {
            AS_TRACE("Cache overflow, disabling the HTTP stream\n");

            if (THIS->m_inputStream) {
                THIS->m_inputStream->setScheduledInRunLoop(false);
            }
        }
    }

    THIS->enqueueCachedData(config->decodeQueueSize);
}

} // namespace astreamer


text:
//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.IO;
//using System.Threading.Tasks;
//using WebOptimizationProject.Helpers.Git;

//namespace WebOptimizationProject.Helpers
//{
//    public static class WopProcessRunner
//    {
//        public static async Task<int> RunProcessAsync(string fileName, string arguments, List<EnvironmentVariable> environmentVariables = null)
//        {
//            Console.WriteLine();
//            Console.WriteLine($"> {Path.GetFileName(fileName)} {arguments}");

//            var psi = new ProcessStartInfo(fileName, arguments);

//            if (environmentVariables != null)
//            {
//                foreach (var envVariable in environmentVariables)
//                {
//                    psi.EnvironmentVariables.Add(envVariable.Key, envVariable.Value);
//                }
//            }

//            using (var process = new Process
//            {
//                StartInfo = psi
//            })
//            {

//                process.Start();

//                await Task.Run(() => process.WaitForExit());

//                return process.ExitCode;
//            }
//        }

//        public static async Task<int> RunProcessAsyncWithResults(string fileName, string arguments, List<ProcessOutputLine> output, List<EnvironmentVariable> environmentVariables = null)
//        {
//            Console.WriteLine();
//            Console.WriteLine($"> {Path.GetFileName(fileName)} {arguments}");

//            var psi = new ProcessStartInfo(fileName, arguments);
//            psi.UseShellExecute = false;
//            psi.RedirectStandardError = true;
//            psi.RedirectStandardOutput = true;

//            if (environmentVariables != null)
//            {
//                foreach (var envVariable in environmentVariables)
//                {
//                    psi.EnvironmentVariables.Add(envVariable.Key, envVariable.Value);
//                }
//            }

//            using (var process = new Process
//            {
//                StartInfo = psi,
//                EnableRaisingEvents = true
//            })
//            {

//                process.OutputDataReceived += (s, e) =>
//                {
//                    lock (output)
//                    {
//                        if (e.Data != null)
//                        {
//                            output.Add(new ProcessOutputLine(ProcessOutputLineType.Log, e.Data));
//                            Console.WriteLine(e.Data);
//                        }
//                    }
//                };

//                process.ErrorDataReceived += (s, e) =>
//                {
//                    lock (output)
//                    {
//                        if (e.Data != null)
//                        {
//                            output.Add(new ProcessOutputLine(ProcessOutputLineType.Error, e.Data));
//                            Console.Error.WriteLine(e.Data);
//                        }
//                    }
//                };

//                process.Start();

//                process.BeginOutputReadLine();
//                process.BeginErrorReadLine();

//                await Task.Run(() => process.WaitForExit());

//                return process.ExitCode;
//            }
//        }
//    }
//}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<JServer name="Receiver">

    <property name="logLevel" value="Debug"/>
    <SnsClientManager>
        <property name="remoteAddresses" value="localhost:12121">
         <!--<value>localhost:12121</value>
         <value>localhost:12122</value>--></property>
        <property name="logLevel" value="Debug"/>

        <!--<property name="socketFactoryClass" value="com.teletalk.jserver.tcp.SSLSocketFactory"/>

        <Component name="SSLSocketFactory">
            <property name="logLevel" value="Debug"/>

            <property name="securityProtocol" value="TLS"/>
            <property name="useNaiveTrustManager" value="true"/>
            <property name="useNaiveHostnameVerifier" value="true"/>

            <property name="wrappedSocketFactoryClass" value="com.teletalk.jserver.tcp.HttpProxySocketFactory"/>

            <Component name="HttpProxySocketFactory">
	            <property name="proxyHost" value="10.6.1.67"/>
	            <property name="proxyPort" value="8080"/>
		    <property name="logLevel" value="Debug"/>
         </Component>

        </Component>-->

        <Component name="EndpointPool">
            <property name="logLevel" value="Debug"/>
        </Component>

    </SnsClientManager>

    <Component name="MessagingManager">

    <property name="localAddresses" value="localhost:13132"/>

<!--<property name="localServiceNames" value="Receiver"/>-->
<!--<property name="localServiceNames">
      <value>Receiver</value>
<value>t1</value>
<value>t2</value>
</property>-->
        <property name="logLevel" value="Debug"/>

        <Component name="EndpointPool">
            <property name="logLevel" value="Debug"/>
        </Component>
    </Component>

   <LogManager name="LogManager">

      <DefaultCriticalErrorLogger name="CriticalErrorAppender">
         <property name="logLevel" value="Debug"/>
         <property name="remoteLoggingServiceNames" value="CELMa"/>
      </DefaultCriticalErrorLogger>
   </LogManager>
</JServer>


text:
@interface DLWMLinearMenuViewController ()

@property (readwrite, assign, nonatomic) BOOL layered;

@property (readwrite, assign, nonatomic) NSUInteger items;
@property (readwrite, assign, nonatomic) CGFloat itemSpacing;
@property (readwrite, assign, nonatomic) CGFloat centerSpacing;
@property (readwrite, assign, nonatomic) CGFloat angle;

@property (weak, nonatomic) IBOutlet UISlider *itemsSlider;
@property (weak, nonatomic) IBOutlet UILabel *itemsLabel;

@property (weak, nonatomic) IBOutlet UISlider *itemSpacingSlider;
@property (weak, nonatomic) IBOutlet UILabel *itemSpacingLabel;

@property (weak, nonatomic) IBOutlet UISlider *centerSpacingSlider;
@property (weak, nonatomic) IBOutlet UILabel *centerSpacingLabel;

@property (weak, nonatomic) IBOutlet UISlider *angleSlider;
@property (weak, nonatomic) IBOutlet UILabel *angleLabel;

@end

@implementation DLWMLinearMenuViewController

#pragma mark - DLWMMenuLayout

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.items = 3;
	self.itemSpacing = 45.0; // in pixels
	self.centerSpacing = 50.0; // in pixels
	self.angle = M_PI_2 * 3; // in radians
}

+ (id<DLWMMenuLayout>)layout {
	return [[DLWMLinearLayout alloc] initWithAngle:0.0 itemSpacing:45.0 centerSpacing:50.0];
}

#pragma mark - DLWMMenuDataSource Protocol

- (NSUInteger)numberOfObjectsInMenu:(DLWMMenu *)menu {
	return self.items;
}

#pragma mark - IBActions

- (IBAction)changeItems:(UISlider *)sender {
	self.items = sender.value;
}

- (IBAction)changeItemSpacing:(UISlider *)sender {
	self.itemSpacing = sender.value;
}

- (IBAction)changeCenterSpacing:(UISlider *)sender {
	self.centerSpacing = sender.value;
}

- (IBAction)changeAngle:(UISlider *)sender {
	self.angle = sender.value;
}

#pragma mark - Accessors

- (void)setItems:(NSUInteger)items {
	_items = items;
	[self.menu reloadData];
	self.itemsSlider.value = items;
	self.itemsLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)items];
}

- (void)setItemSpacing:(CGFloat)itemSpacing {
	_itemSpacing = itemSpacing;
	((DLWMLinearLayout *)self.menu.layout).itemSpacing = itemSpacing;
	self.itemSpacingSlider.value = itemSpacing;
	self.itemSpacingLabel.text = [NSString stringWithFormat:@"%.0fpx", itemSpacing];
}

- (void)setCenterSpacing:(CGFloat)centerSpacing {
	_centerSpacing = centerSpacing;
	((DLWMLinearLayout *)self.menu.layout).centerSpacing = centerSpacing;
	self.centerSpacingSlider.value = centerSpacing;
	self.centerSpacingLabel.text = [NSString stringWithFormat:@"%.0fpx", centerSpacing];
}

- (void)setAngle:(CGFloat)angle {
	_angle = angle;
	((DLWMLinearLayout *)self.menu.layout).angle = angle;
	self.angleSlider.value = angle;
	self.angleLabel.text = [NSString stringWithFormat:@"%.0fº", (angle / M_PI) * 180];
}

@end


text:
class SimulationConfiguration {
public:
    SimulationConfiguration(const std::string& config_file_name);
    SimulationConfiguration(std::istream& input);
    ~SimulationConfiguration();

    // These functions raise a std::runtime_error if the given key isn't
    // present or the value can't be converted into the required type.
    std::string as_string(std::initializer_list<std::string> list);
    int as_int(std::initializer_list<std::string> list);
    std::int64_t as_int64(std::initializer_list<std::string> list);
    bool as_bool(std::initializer_list<std::string> list);
    double as_double(std::initializer_list<std::string> list);

    // These versions return the given default instead of throwing an error
    std::string get_string(std::initializer_list<std::string> list,
                           const std::string& default_value) noexcept;
    int get_int(std::initializer_list<std::string> list, int default_value) noexcept;
    std::int64_t get_int64(std::initializer_list<std::string> list, int64_t default_value);
    bool get_bool(std::initializer_list<std::string> list, bool default_value) noexcept;
    double get_double(std::initializer_list<std::string> list, double default_value) noexcept;

private:
    void init(std::istream& input);

    class impl;
    std::unique_ptr<impl> pimpl;
};

#endif


text:
package org.springframework.web.method.annotation;

import java.lang.reflect.Method;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.springframework.core.MethodParameter;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;

import static org.junit.Assert.*;

/**
 * Test fixture with {@link org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver}.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 */
public class RequestHeaderMethodArgumentResolverTests {

	private RequestHeaderMethodArgumentResolver resolver;

	private MethodParameter paramNamedDefaultValueStringHeader;
	private MethodParameter paramNamedValueStringArray;
	private MethodParameter paramSystemProperty;
	private MethodParameter paramContextPath;
	private MethodParameter paramNamedValueMap;

	private MockHttpServletRequest servletRequest;

	private NativeWebRequest webRequest;

	@Before
	public void setUp() throws Exception {
		GenericWebApplicationContext context = new GenericWebApplicationContext();
		context.refresh();
		resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory());

		Method method = getClass().getMethod("params", String.class, String[].class, String.class, String.class, Map.class);
		paramNamedDefaultValueStringHeader = new MethodParameter(method, 0);
		paramNamedValueStringArray = new MethodParameter(method, 1);
		paramSystemProperty = new MethodParameter(method, 2);
		paramContextPath = new MethodParameter(method, 3);
		paramNamedValueMap = new MethodParameter(method, 4);

		servletRequest = new MockHttpServletRequest();
		webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());

		// Expose request to the current thread (for SpEL expressions)
		RequestContextHolder.setRequestAttributes(webRequest);
	}

	@After
	public void teardown() {
		RequestContextHolder.resetRequestAttributes();
	}

	@Test
	public void supportsParameter() {
		assertTrue("String parameter not supported", resolver.supportsParameter(paramNamedDefaultValueStringHeader));
		assertTrue("String array parameter not supported", resolver.supportsParameter(paramNamedValueStringArray));
		assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(paramNamedValueMap));
	}

	@Test
	public void resolveStringArgument() throws Exception {
		String expected = "foo";
		servletRequest.addHeader("name", expected);

		Object result = resolver.resolveArgument(paramNamedDefaultValueStringHeader, null, webRequest, null);

		assertTrue(result instanceof String);
		assertEquals("Invalid result", expected, result);
	}

	@Test
	public void resolveStringArrayArgument() throws Exception {
		String[] expected = new String[]{"foo", "bar"};
		servletRequest.addHeader("name", expected);

		Object result = resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null);

		assertTrue(result instanceof String[]);
		assertArrayEquals("Invalid result", expected, (String[]) result);
	}

	@Test
	public void resolveDefaultValue() throws Exception {
		Object result = resolver.resolveArgument(paramNamedDefaultValueStringHeader, null, webRequest, null);

		assertTrue(result instanceof String);
		assertEquals("Invalid result", "bar", result);
	}

	@Test
	public void resolveDefaultValueFromSystemProperty() throws Exception {
		System.setProperty("systemProperty", "bar");
		Object result = resolver.resolveArgument(paramSystemProperty, null, webRequest, null);
		System.clearProperty("systemProperty");

		assertTrue(result instanceof String);
		assertEquals("bar", result);
	}

	@Test
	public void resolveDefaultValueFromRequest() throws Exception {
		servletRequest.setContextPath("/bar");
		Object result = resolver.resolveArgument(paramContextPath, null, webRequest, null);

		assertTrue(result instanceof String);
		assertEquals("/bar", result);
	}

	@Test(expected = ServletRequestBindingException.class)
	public void notFound() throws Exception {
		resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null);
	}

	public void params(@RequestHeader(value = "name", defaultValue = "bar") String param1,
					   @RequestHeader("name") String[] param2,
					   @RequestHeader(value = "name", defaultValue="#{systemProperties.systemProperty}") String param3,
					   @RequestHeader(value = "name", defaultValue="#{request.contextPath}") String param4,
					   @RequestHeader("name") Map<?, ?> unsupported) {
	}

}


text:
package de.fu_berlin.imp.apiua.diff.editors;

import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.CompareEditorInput;
import org.eclipse.compare.CompareUI;
import org.eclipse.compare.structuremergeviewer.DiffNode;
import org.eclipse.compare.structuremergeviewer.Differencer;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.PlatformUI;

import de.fu_berlin.imp.apiua.diff.model.IDiffRecord;

public class DiffFileRecordCompareInput extends CompareEditorInput {
	private IDiffRecord diffRecord;
	private Image titleImage;

	public DiffFileRecordCompareInput(IDiffRecord diffRecord) {
		super(new CompareConfiguration());
		this.diffRecord = diffRecord;
	}

	public IDiffRecord getDiffFileRecord() {
		return this.diffRecord;
	}

	@Override
	public String getName() {
		return this.diffRecord != null ? this.diffRecord.getFilename()
				: "NO_CODES";
	}

	@Override
	public String getTitle() {
		return this.diffRecord != null ? this.diffRecord.getDiffFile()
				.getIdentifier() + ": " + this.diffRecord.getFilename()
				: "NO_CODES";
	}

	@Override
	public String getToolTipText() {
		if (this.diffRecord == null) {
			return "";
		}
		String predRevision = this.diffRecord.getPredecessor() != null ? this.diffRecord
				.getPredecessor().getDiffFile().getRevision()
				: "-";
		String revision = this.diffRecord.getDiffFile().getRevision();
		return "ID: " + this.diffRecord.getDiffFile().getIdentifier()
				+ "\nFile:" + this.diffRecord.getFilename() + "\nRevisions: "
				+ predRevision + " and " + revision;
	}

	@Override
	public Image getTitleImage() {
		if (this.titleImage == null) {
			this.titleImage = PlatformUI.getWorkbench().getEditorRegistry()
					.getImageDescriptor(this.diffRecord.getFilename())
					.createImage();
			CompareUI.disposeOnShutdown(this.titleImage);
		}
		return this.titleImage;
	}

	@Override
	protected Object prepareInput(IProgressMonitor pm) {
		DiffFileRecordCompareItem left = new DiffFileRecordCompareItem(
				this.diffRecord.getPredecessor(), this.getTitleImage());
		DiffFileRecordCompareItem right = new DiffFileRecordCompareItem(
				this.diffRecord, this.getTitleImage());

		return new DiffNode(null, Differencer.ADDITION | Differencer.CHANGE
				| Differencer.DELETION, null, left, right);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((this.diffRecord == null) ? 0 : this.diffRecord.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (this.getClass() != obj.getClass()) {
			return false;
		}
		DiffFileRecordCompareInput other = (DiffFileRecordCompareInput) obj;
		if (this.diffRecord == null) {
			if (other.diffRecord != null) {
				return false;
			}
		} else if (!this.diffRecord.equals(other.diffRecord)) {
			return false;
		}
		return true;
	}
}


text:
package ncu.bahuang.chan;

import android.app.Application;

import net.hockeyapp.android.FeedbackManager;
import net.hockeyapp.android.metrics.MetricsManager;

/**
 * Author: BaHuang
 * Date: 2017/3/18 23:15
 * GitHub: https://github.com/bahuangcn
 * Website: http://linyuange.site
 */

public class BHApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        initHockeyAppSDK();
    }

    private void initHockeyAppSDK() {
        MetricsManager.register(this);
        FeedbackManager.register(this);
    }
}


text:
//
//  CQCacheKit.h
//  CQFramework
//
//  Created by runo on 17/2/24.
//  Copyright © 2017年 com.runo. All rights reserved.
//

#ifndef CQCacheKit_h
#define CQCacheKit_h

#import "CQDBOperator.h"
#import "CQDBOperatorSettingInterface.h"

#endif /* CQCacheKit_h */


text:
package javaee.samples.frameworks.injection.resource;

import javaee.samples.frameworks.injection.InjectionRunner;
import javaee.samples.frameworks.injection.WithManagedTransactions;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.annotation.Resource;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.jms.Session;

import static org.mockito.Mockito.mock;
import static org.assertj.core.api.Assertions.assertThat;

@RunWith(InjectionRunner.class)
@WithManagedTransactions
public class ResourceTest {
    @Produces
    Session session = mock(Session.class);

    @Inject
    Session in;

    @Resource
    static Session staticResource;

    @Resource
    static Session thisResource;

    @Inject
    SessionService service;

    @Test
    public void shouldInjectResource() {
        assertThat(in)
                .isNotNull();

        assertThat(staticResource)
                .isNotNull();

        assertThat(thisResource)
                .isNotNull();

        assertThat(service)
                .isNotNull();

        assertThat(service)
                .extracting(SessionService::getSession)
                .doesNotContainNull();

        assertThat(service)
                .extracting(SessionService::getStaticResource)
                .doesNotContainNull();

        assertThat(service)
                .extracting(SessionService::getThisResource)
                .doesNotContainNull();
    }
}


text:
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Platron.Client.Http.Plain;
using Platron.Client.Utils;

namespace Platron.Client.Http
{
    /// <summary>
    /// Implements all xml serialization/deserialization operations.
    /// </summary>
    public sealed class XmlPipeline : IXmlPipeline
    {
        private static readonly string RequestRoot = "request";
        private static readonly string ResponseRoot = "response";

        public string Serialize(object value, string root)
        {
            Ensure.ArgumentNotNull(value, nameof(value));
            Ensure.ArgumentNotNull(root, nameof(root));

            // Need to exclude namespaces from result xml.
            var emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(string.Empty, string.Empty);

            var serializer = new XmlSerializer(value.GetType(), new XmlRootAttribute(root));
            using (TextWriter writer = new EncodingStringWriter(Encoding.UTF8))
            {
                serializer.Serialize(writer, value, emptyNamespace);
                return writer.ToString();
            }
        }

        public IApiResponse<TPlainResponse> Deserialize<TPlainResponse>(IHttpResponse response)
            where TPlainResponse : PlainResponse
        {
            Ensure.ArgumentNotNull(response, nameof(response));

            try
            {
                var serializer = new XmlSerializer(typeof (TPlainResponse), new XmlRootAttribute(ResponseRoot));
                using (var reader = new StringReader(response.Body))
                {
                    var plain = (TPlainResponse) serializer.Deserialize(reader);
                    return new ApiResponse<TPlainResponse>(response, plain);
                }
            }
            catch (Exception e)
            {
                throw new InvalidResponseApiException("Xml content in response cann't be decoded", response, e);
            }
        }

        public string Serialize(ApiRequest request)
        {
            Ensure.ArgumentNotNull(request, nameof(request));
            return Serialize(request.Plain, RequestRoot);
        }

        public string Serialize(ApiCallbackResponse request)
        {
            Ensure.ArgumentNotNull(request, nameof(request));
            return Serialize(request.Plain, ResponseRoot);
        }

        /// <summary>
        ///     Need to subclass StringWriter in order to override Encoding.
        /// </summary>
        private sealed class EncodingStringWriter : StringWriter
        {
            public EncodingStringWriter(Encoding encoding)
            {
                Encoding = encoding;
            }

            public override Encoding Encoding { get; }
        }
    }
}


text:
import { passwordHash } from '../../helper/helper';

export default {
  validAdmin: {
    fullName: 'seun adekunle',
    username: 'seunadex',
    password: passwordHash('seunadex'),
    email: 'seunadex@gmail.com',
    roleId: 1
  },

  incompleteData: {
    fullName: '',
    username: '',
    password: '',
    email: 'seun@gmail.com'
  },

  validUser: {
    fullName: 'lionel messi',
    username: 'lionelmessi',
    password: passwordHash('lionelmessi'),
    email: 'lionelmessi@gmail.com',
    id: 2
  },

  userOne: {
    fullName: 'cristiano ronaldo',
    username: 'cr7',
    password: passwordHash('ronaldo'),
    email: 'cr7@gmail.com',
    roleId: 1
  },

  userTwo: {
    fullName: 'kun aguero',
    username: 'sergioaguero',
    password: passwordHash('aguero'),
    email: 'kunaguero@gmail.com',
    roleId: 2
  },

  userThree: {
    fullName: 'jesse lingard',
    username: 'jesse14',
    password: passwordHash('jesselingard'),
    email: 'jesse14@gmail.com',
    roleId: 2
  }

};


text:
import { AnnotationEvent } from 'src/packages/datav-core/src';
import { getBackendSrv } from 'src/packages/datav-core/src';
import { AnnotationTagsResponse } from './types';

export function saveAnnotation(annotation: AnnotationEvent) {
  return getBackendSrv().post('/api/annotations', annotation);
}

export function updateAnnotation(annotation: AnnotationEvent) {
  return getBackendSrv().put(`/api/annotations/${annotation.id}`, annotation);
}

export function deleteAnnotation(annotation: AnnotationEvent) {
  return getBackendSrv().delete(`/api/annotations/${annotation.id}`);
}

export async function getAnnotationTags() {
  const response: AnnotationTagsResponse = await getBackendSrv().get('/api/annotations/tags');
  return response.result.tags.map(({ tag, count }) => ({
    term: tag,
    count,
  }));
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\search\GeneralHasTipoSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'General_id') ?>

    <?= $form->field($model, 'Tipo_id') ?>

        <?= Html::submitButton(Yii::t('models', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('models', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php

namespace Magento\Setup\Test\Unit\Fixtures;

use \Magento\Setup\Fixtures\FixtureModel;

class FixtureModelTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var \Magento\Setup\Fixtures\FixtureModel
     */
    private $model;

    public function setUp()
    {
        $reindexCommandMock = $this->getMock(
            '\Magento\Indexer\Console\Command\IndexerReindexCommand',
            [],
            [],
            '',
            false
        );
        $fileParserMock = $this->getMock('\Magento\Framework\Xml\Parser', [], [], '', false);

        $this->model = new FixtureModel($reindexCommandMock, $fileParserMock);
    }

    public function testReindex()
    {
        $outputMock = $this->getMock('\Symfony\Component\Console\Output\OutputInterface', [], [], '', false);
        $this->model->reindex($outputMock);
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage Profile configuration file `exception.file` is not readable or does not exists.
     */
    public function testLoadConfigException()
    {
        $this->model->loadConfig('exception.file');
    }

    public function testLoadConfig()
    {
        $reindexCommandMock = $this->getMock(
            '\Magento\Indexer\Console\Command\IndexerReindexCommand',
            [],
            [],
            '',
            false
        );

        $fileParserMock = $this->getMock('\Magento\Framework\Xml\Parser', ['load', 'xmlToArray'], [], '', false);
        $fileParserMock->expects($this->once())->method('xmlToArray')->willReturn(
            ['config' => [ 'profile' => ['some_key' => 'some_value']]]
        );
        $fileParserMock->expects($this->once())->method('load')->with('config.file')->willReturn($fileParserMock);
        $this->model = new FixtureModel($reindexCommandMock, $fileParserMock);
        $this->model->loadConfig('config.file');
        $this->assertSame('some_value', $this->model->getValue('some_key'));
    }

    public function testGetValue()
    {
        $this->assertSame(null, $this->model->getValue('null_key'));
    }
}

namespace Magento\Setup\Fixtures;

/**
 * Overriding the built-in PHP function since it cannot be mocked->
 *
 * The method is used in FixtureModel. loadConfig in an if statement. By overriding this method we are able to test
 * both of the possible cases based on the return value of is_readable.
 *
 * @param string $filename
 * @return bool
 */
function is_readable($filename)
{
    if (strpos($filename, 'exception') !== false) {
        return false;
    }
    return true;
}


text:
require 'odenos/remoteobject'
require 'odenos/core/util/logger'

module Odenos
  module Component
    class SystemManagerInterface
      include Odenos::Core
      include Odenos::Util::Logger

      COMP_MNGS_PATH = 'component_managers'
      COMP_MNG_PATH = 'component_managers/%s'
      EVENT_MNG_PATH = 'event_manager'
      COMP_TYPES_PATH = 'component_types'
      COMP_TYPE_PATH = 'component_types/%s'
      COMPS_PATH = 'components'
      COMP_PATH = 'components/%s'
      CONNECTIONS_PATH = 'connections'
      CONNECTION_PATH = 'connections/%s'
      OBJECT_PATH = 'objects/%s'

      def initialize(dispatcher)
        @dispatcher = dispatcher
        @sysmgr_id = dispatcher.system_manager_id
        logger_ident_initialize('SystemManagerInterface')
      end

      ####################
      # request method
      ####################

      # GET Component Managers.
      def get_component_managers
        debug 'GET Component Managers.'
        path = COMP_MNGS_PATH
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          comp_mgrs = {}
          resp.body.each do |prop|
            objp = ObjectProperty.new(prop)
            comp_mgrs[objp.remote_object_id] = objp
          end
          return comp_mgrs
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Event Manager.
      def get_event_manager
        debug 'GET Event Manager.'
        path = EVENT_MNG_PATH
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          return ObjectProperty.new(resp.body)
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET ComponentTypes.
      def get_component_types
        debug 'GET ComponentTypes.'
        path = COMP_TYPES_PATH
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          comp_types = {}
          resp.body.each do |type, list|
            obj_list = []
            list.each do |prop|
              obj_list.push(ObjectProperty.new(prop))
            end
            comp_types[type] = obj_list
          end
          return comp_types
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Components.
      def get_components
        debug 'GET Components.'
        path = COMPS_PATH
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          comps = {}
          resp.body.each do |id, prop|
            objp = ObjectProperty.new(prop)
            comps[id] = objp
          end
          return comps
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Connections.
      def get_connections
        debug 'GET Connections.'
        path = CONNECTIONS_PATH
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          conns = {}
          resp.body.each do |id, conn|
            conn_prop = nil
            if conn[:type] == 'LogicAndNetwork'
              conn_prop = LogicAndNetwork.new(conn)
            else
              conn_prop = ComponentConnection.new(conn)
            end
            conns[id] = conn_prop
          end
          return conns
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Component Manager.
      def get_component_manager(comp_mgr_id)
        debug 'GET Component Manager.'
        path = COMP_MNG_PATH % comp_mgr_id
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          return ObjectProperty.new(resp.body)
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET ComponentType.
      def get_component_type(comp_type)
        debug 'GET ComponentType.'
        path = COMP_TYPE_PATH % comp_type
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          obj_list = []
          resp.body.each do |prop|
            obj_list.push(ObjectProperty.new(prop))
          end
          return obj_list
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Component.
      def get_component(comp_id)
        debug 'GET Component.'
        path = COMP_PATH % comp_id
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          return ObjectProperty.new(resp.body)
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Connection.
      def get_connection(conn_id)
        debug 'GET Connection.'
        path = CONNECTION_PATH % conn_id
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          conn_prop = nil
          if resp.body[:type] == 'LogicAndNetwork'
            conn_prop = LogicAndNetwork.new(resp.body)
          else
            conn_prop = ComponentConnection.new(resp.body)
          end
          return conn_prop
        rescue => ex
          return dump_error(ex)
        end
      end

      # GET Object.
      def get_object(object_id)
        debug 'GET Object.'
        path = OBJECT_PATH % object_id
        resp = get_object_to_sysmgr(path)
        unless resp.status_code == Response::OK
          return nil
        end
        begin
          return ObjectProperty.new(resp.body)
        rescue => ex
          return dump_error(ex)
        end
      end

      # PUT Connection.
      def put_connection(connection)
        debug 'PUT Connection.'
        path = CONNECTION_PATH % connection.component_connection_id
        put_object_to_sysmgr(path, connection)
      end

      # PUT ComponentManagers.
      def put_component_managers(property)
        debug 'PUT ComponentManagers.'
        path = COMP_MNG_PATH % property.remote_object_id
        put_object_to_sysmgr(path, property)
      end

      # PUT Components.
      def put_components(property)
        debug 'PUT Components.'
        path = COMP_PATH % property.remote_object_id
        put_object_to_sysmgr(path, property)
      end

      # POST Components.
      def post_components(property)
        debug 'POST Components.'
        path = COMPS_PATH
        post_object_to_sysmgr(path, property)
      end

      # POST Connections.
      def post_connections(connection)
        debug 'POST Components.'
        path = CONNECTIONS_PATH
        post_object_to_sysmgr(path, connection)
      end

      # DELETE ComponentManagers.
      def del_component_managers(comp_mgr_id)
        debug 'DELETE ComponentManagers.'
        path = COMP_MNG_PATH % comp_mgr_id
        del_object_to_sysmgr(path)
      end

      # DELETE Components.
      def del_components(comp_id)
        debug 'DELETE Components.'
        path = COMP_PATH % comp_id
        del_object_to_sysmgr(path)
      end

      # DELETE Connections.
      def del_connections(conn_id)
        debug 'DELETE Connections.'
        path = CONNECTION_PATH % conn_id
        del_object_to_sysmgr(path)
      end

      ####################
      # common method
      ####################

      def post_object_to_sysmgr(path, body)
        debug ">> sysmgr_id: #{@sysmgr_id} path: #{path}"
        send_request(@sysmgr_id, :POST, path, body)
      end

      def put_object_to_sysmgr(path, body)
        debug ">> sysmgr_id: #{@sysmgr_id} path: #{path}"
        send_request(@sysmgr_id, :PUT, path, body)
      end

      def del_object_to_sysmgr(path)
        debug ">> sysmgr_id: #{@sysmgr_id} path: #{path}"
        send_request(@sysmgr_id, :DELETE, path, nil)
      end

      def get_object_to_sysmgr(path)
        debug ">> sysmgr_id: #{@sysmgr_id} path: #{path}"
        send_request(@sysmgr_id, :GET, path, nil)
      end

      ####################
      # private method
      ####################

      private

      def dump_error(ex)
        error 'Exception: Get Invalid Message'
        error " #{ex.message} #{ex.backtrace}"
        nil
      end

      def send_request(obj_id, method, path, body)
        resp = Response.new(Response::INTERNAL_SERVER_ERROR, nil)
        req = Request.new(obj_id, method, path, "*", body)
        begin
          resp = @dispatcher.request_sync(req)
        rescue => ex
          error "Exception: Request to #{obj_id} Method:#{method} Path:#{path}"
          error " #{ex.message} #{ex.backtrace}"
        end
        resp
      end
    end
  end
end


text:
comments: true
date: 2010-11-30 17:51:30
layout: post
slug: contact-linker-and-manger-in-firefox
title: Contact Linker and Manger in Firefox
wordpress_id: 448
categories:
- Code
tags:
- contacts
- facebook
- Firefox
- linkedin
- sync
- twitter
---

> Contacts is an experimental addon from Mozilla Labs, which enhances Firefox by making it aware of your online contacts and friend lists. You can then search and browse your contacts in the browser, and a website can ask for permission to access them through an API.

via [Mozilla Labs: Contacts :: Add-ons for Firefox](https://addons.mozilla.org/en-US/firefox/addon/243985/).

This add-on was pretty easy to install and link my Facebook, Twitter, Gmail, and LinkedIn accounts.  It looks nice and has a good user experience, so far.  What's particularly interesting, and I haven't explored this too much, is how it tracks the source of information in contacts as they are merged and split (which is also very easy).

It's supposed to also [sync with OSX AddressBook.app](https://mozillalabs.com/contacts/2010/10/22/contacts-in-the-browser-0-4-released/) in the new [Firefox Beta](http://www.mozilla.com/firefox/beta/) but that didn't work on Leopard for me.

Much easier than [raindrop](https://mozillalabs.com/raindrop/) which apparently doesn't like Python 2.7 and [pip](http://pypi.python.org/pypi/pip) as installed by [homebrew](https://github.com/mxcl/homebrew). The idea of streaming my twitter, skype, and gmail updates is interesting, but have yet to see it working.


text:
Visit the [Samples gallery](https://www.dotvvm.com/samples) on our main website. You'll find instructions how to run the samples locally.

## Videos

We post all of our videos on our [YouTube](https://www.youtube.com/c/DotVVM) channel.

## Articles

You can also find blog posts and tutorials on the following sites:

* [Medium.com DotVVM community](https://medium.com/dotvvm)
* [Dev.to DotVVM community](https://dev.to/dotvvm)
* [C# Corner](https://www.c-sharpcorner.com/search.aspx?q=dotvvm)

## See also

* [The first page](~/pages/quick-starts/build/first-page)
* [Build a To-do list app](~/pages/quick-starts/build/build-to-do-list-app)


text:
package io.aos.guice.spl1;

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

public class RealBillingService {

    @Inject
    public RealBillingService(@Named("Mock") CreditCardProcessor processor,
        TransactionLog transactionLog) {
    }

}


text:
.class public final Landroid/media/MediaDrm$KeyRequest;
.super Ljava/lang/Object;
.source "MediaDrm.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/MediaDrm;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "KeyRequest"
.end annotation

# instance fields
.field private mData:[B

.field private mDefaultUrl:Ljava/lang/String;

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 307
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public getData()[B
    .locals 1

    .prologue
    .line 312
    iget-object v0, p0, Landroid/media/MediaDrm$KeyRequest;->mData:[B

    return-object v0
.end method

.method public getDefaultUrl()Ljava/lang/String;
    .locals 1

    .prologue
    .line 319
    iget-object v0, p0, Landroid/media/MediaDrm$KeyRequest;->mDefaultUrl:Ljava/lang/String;

    return-object v0
.end method


text:
package org.apache.gora.maven.plugin;

import java.io.File;

import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

/**
 * Goal which compiles Gora schemas.
 *
 */
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class GenerateMojo extends AbstractGoraMojo {
  /**
   * The source directory of Apache Avro files. This directory is added to the
   * classpath at schema compiling time. All files can therefore be referenced
   * as classpath resources following the directory structure under the source
   * directory.
   *
   */
  @Parameter(defaultValue = "${basedir}/src/main/avro")
  private File sourceDirectory;

  @Parameter(defaultValue = "${basedir}/src/main/java")
  private File outputDirectory;

  @Override
  protected File getSourcesDirectory() {
    return sourceDirectory;
  }

  @Override
  protected File getOutputDirectory() {
    return outputDirectory;
  }

  @Override
  protected void registerSourceDirectory(MavenProject project, String path) {
    project.addCompileSourceRoot(path);
  }
}


text:
using NotaFiscalNet.Core.Validacao;

namespace NotaFiscalNet.Core
{
    /// <summary>
    /// Representa um erro de validação que ocorre quando se tenta modificar o valor da Nota Fiscal
    /// Eletrônica em modo Somente-Leitura.
    /// </summary>

    public sealed class NFeReadOnlyException : ErroValidacaoNFeException
    {
        /// <summary>
        /// Inicializa uma nova instância da classe <see cref="NFeReadOnlyException"/>.
        /// </summary>
        internal NFeReadOnlyException():base(ChaveErroValidacao.ReadOnlyClass)
        {
        }
    }
}


text:
#region S# License

#endregion S# License
namespace StockSharp.Oanda.Native.DataTypes
{
	using Newtonsoft.Json;

	class Position
	{
		[JsonProperty("side")]
		public string Side { get; set; }

		[JsonProperty("instrument")]
		public string Instrument { get; set; }

		[JsonProperty("units")]
		public int Units { get; set; }

		[JsonProperty("avgPrice")]
		public double AveragePrice { get; set; }
	}
}