text:
goog.provide('audioCat.ui.widget.ClipDetectorWidget');

goog.require('audioCat.audio.play.events');
goog.require('audioCat.ui.widget.ClippingBarWidget');
goog.require('audioCat.ui.widget.Widget');
goog.require('goog.async.AnimationDelay');
goog.require('goog.events');

/**
 * A widget that indicates when clipping occurs by having bars turning red.
 * @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions.
 * @param {!audioCat.audio.play.PlayManager} playManager Manages playing.
 * @param {!audioCat.audio.Analyser} audioAnalyser Analyses audio.
 * @param {number} numberOfChannels The number of output channels to check
 *     clipping for.
 * @constructor
 * @extends {audioCat.ui.widget.Widget}
 */
audioCat.ui.widget.ClipDetectorWidget = function(
    domHelper,
    playManager,
    audioAnalyser,
    numberOfChannels) {
  /**
   * The audio analyser.
   * @private {!audioCat.audio.Analyser}
   */
  this.audioAnalyser_ = audioAnalyser;

  /**
   * The base element.
   * @private {!Element}
   */
  this.baseElement_ = domHelper.createDiv(
      goog.getCssName('clipDetectorWidgetContainer'));
  goog.base(this, this.baseElement_);

  // TODO(chizeng): Use 2D canvas instead of these DOM-based clipping bars.
  // OR it could be the script processor just being too slow. Skip more frames.
  var clippingBarWidgets = new Array(numberOfChannels);
  for (var i = 0; i < numberOfChannels; ++i) {
    clippingBarWidgets[i] = new audioCat.ui.widget.ClippingBarWidget(domHelper);
    domHelper.appendChild(this.baseElement_, clippingBarWidgets[i].getDom());
  }
  /**
   * A list of clipping bar widgets. One for each channel.
   * @private {!Array.<!audioCat.ui.widget.ClippingBarWidget>}
   */
  this.clippingBarWidgets_ = clippingBarWidgets;

  /**
   * A count of how many calls to requestAnimation have occurred. Used to only
   * draw on even calls.
   * @private {number}
   */
  this.drawIndex_ = 0;

  /**
   * The animation delay pegged to frame times. Used to update the indicated
   * time. Null when not playing.
   * @private {goog.async.AnimationDelay}
   */
  this.playAnimationDelay_ = null;

  // Respond to changes in play status.
  /**
   * Keys of listeners to remove upon clean up.
   * @private {!Array.<goog.events.Key>}
   */
  this.listenerKeys_ = [
      goog.events.listen(playManager, audioCat.audio.play.events.PLAY_BEGAN,
          this.handlePlayBegan_, false, this),
      goog.events.listen(playManager, audioCat.audio.play.events.PAUSED,
          this.handlePlayPause_, false, this)
    ];

  // Start animation iff we're playing.
  if (playManager.getPlayState()) {
    this.doAnimationLoop_();
  }
};
goog.inherits(audioCat.ui.widget.ClipDetectorWidget, audioCat.ui.widget.Widget);

/**
 * Updates the clipping bars.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.updateClippingBarWidgets_ =
    function() {
  var audioAnalyser = this.audioAnalyser_;
  var clippingBarWidgets = this.clippingBarWidgets_;
  audioAnalyser.computeCurrentSampleMaxesPerChannel();
  for (var i = 0; i < clippingBarWidgets.length; ++i) {
    clippingBarWidgets[i].setSampleValue(
        audioAnalyser.obtainCurrentSampleMax(i));
  }
};

/**
 * Handles what happens when playing of audio begins.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.handlePlayBegan_ = function() {
  this.doAnimationLoop_();
};

/**
 * Begins the animation.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.doAnimationLoop_ = function() {
  var animationDelay = new goog.async.AnimationDelay(
      this.doPerVisualFrame_, undefined, this);
  animationDelay.start();
  this.playAnimationDelay_ = animationDelay;
};

/**
 * Draws, then requests more drawing on the next visual frame.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.doPerVisualFrame_ =
    function() {
  if (this.drawIndex_ & 1) {
    // Render every other frame. We don't need 60 FPS. 30 suffices.
    this.updateClippingBarWidgets_();
  }
  this.drawIndex_ += 1;
  this.doAnimationLoop_();
};

/**
 * Handles what happens when playing of audio pauses.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.handlePlayPause_ =
    function() {
  this.stopAnimation_();
  // 2 more draws to clear the canvas since each draw resets at the end.
  this.clearClippingBarWidgets_();
};

/**
 * Clears the clipping bar widgets.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.clearClippingBarWidgets_ =
    function() {
  var clippingBarWidgets = this.clippingBarWidgets_;
  for (var i = 0; i < clippingBarWidgets.length; ++i) {
    clippingBarWidgets[i].setSampleValue(0);
  }
};

/**
 * Stops the animation if the animation had been playing. Otherwise, does
 * nothing.
 * @private
 */
audioCat.ui.widget.ClipDetectorWidget.prototype.stopAnimation_ =
    function() {
  if (this.playAnimationDelay_) {
    this.playAnimationDelay_.stop();
    this.playAnimationDelay_ = null;
  }
  this.drawIndex_ = 0;
};

/** @override */
audioCat.ui.widget.ClipDetectorWidget.prototype.cleanUp = function() {
  for (var i = 0; i < this.clippingBarWidgets_.length; ++i) {
    this.clippingBarWidgets_[i].cleanUp();
  }
  this.clippingBarWidgets_.length = 0;

  for (var i = 0; i < this.listenerKeys_.length; ++i) {
    goog.events.unlistenByKey(this.listenerKeys_[i]);
  }

  audioCat.ui.widget.ClipDetectorWidget.base(this, 'cleanUp');
};


text:
#ifndef _JSONFX_DOCUMENT_H_
#define _JSONFX_DOCUMENT_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <stdio.h>

#include "JsonFx/Config.h"
#include "JsonFx/Allocator.h"
#include "JsonFx/Value.h"
#include "JsonFx/Reader.h"
#include "JsonFx/Writer.h"

#include "JsonFx/Stream/StringInputStream.h"

#include "jimi/basic/assert.h"

namespace JsonFx {

// Forward declaration.
template <typename EncodingT = JSONFX_DEFAULT_ENCODING,
          typename PoolAllocatorT = DefaultPoolAllocator,
          typename AllocatorT = DefaultAllocator>
class BasicDocument;

// Define default Document class type
typedef BasicDocument<>    Document;

// Save and setting the packing alignment
#pragma pack(push)
#pragma pack(1)

template <typename EncodingT /* = JSONFX_DEFAULT_ENCODING */,
          typename PoolAllocatorT /* = DefaultPoolAllocator */,
          typename AllocatorT /* = DefaultAllocator */>
class BasicDocument : public BasicValue<EncodingT, PoolAllocatorT>
{
public:
    typedef typename EncodingT::CharType            CharType;           //!< Character type derived from Encoding.
    typedef BasicValue<EncodingT, PoolAllocatorT>   ValueType;          //!< Value type of the document.
    typedef EncodingT                               EncodingType;       //!< Character encoding type.
    typedef PoolAllocatorT                          PoolAllocatorType;  //!< Pool allocator type from template parameter.
    typedef AllocatorT                              StackAllocatorType; //!< Stack allocator type from template parameter.
    typedef BasicStringInputStream<CharType>        StringInputStreamType;
    typedef BasicStack<PoolAllocatorT>              StackType;
    typedef BasicParseResult<EncodingT>             ParseResultType;

private:
    PoolAllocatorType *     mPoolAllocator;
    bool                    mPoolAllocatorNeedFree;
    StackAllocatorType *    mStackAllocator;
    bool                    mStackAllocatorNeedFree;
    StackType               mStack;
    ParseResultType         mParseResult;

public:
    BasicDocument(const PoolAllocatorType * poolAllocator = NULL)
        : mPoolAllocator(const_cast<PoolAllocatorType *>(poolAllocator)),
          mPoolAllocatorNeedFree(false),
          mStack(poolAllocator, 100), mParseResult()
    {
        initPoolAllocator(poolAllocator);
    }

    ~BasicDocument() {
        destroy();
    }

private:
    //! Prohibit copying
    BasicDocument(const BasicDocument &);
    //! Prohibit assignment
    BasicDocument & operator =(const BasicDocument &);

public:
    const PoolAllocatorType *  getPoolAllocator() const  { return mPoolAllocator;  }
    const StackAllocatorType * getStackAllocator() const { return mStackAllocator; }
    const PoolAllocatorType *  getAllocator() const      { return getPoolAllocator();  }

    void visit();

    void test() {
        printf("JsonFx::BasicDocument::test()\n\n");
    }

private:
    void destroy() {
        if (this->mPoolAllocatorNeedFree) {
            if (this->mPoolAllocator) {
                delete this->mPoolAllocator;
                this->mPoolAllocator = NULL;
            }
        }
    }

    void initPoolAllocator(const PoolAllocatorType * poolAllocator) {
        if (poolAllocator == NULL) {
            PoolAllocatorType * newPoolAllocator = new PoolAllocatorType();
            jimi_assert(newPoolAllocator != NULL);
            if (newPoolAllocator != NULL) {
                mPoolAllocator = newPoolAllocator;
                mPoolAllocatorNeedFree = true;
            }
        }
    }

public:
    // Implementation of ReaderHandler
    bool saxNull()             { new (mStack.template push<ValueType>()) ValueType();  return true; }
    bool saxBool(bool b)       { new (mStack.template push<ValueType>()) ValueType(b); return true; }
    bool saxInt(int i)         { new (mStack.template push<ValueType>()) ValueType(i); return true; }
    bool saxUint(unsigned i)   { new (mStack.template push<ValueType>()) ValueType(i); return true; }
    bool saxInt64(int64_t i)   { new (mStack.template push<ValueType>()) ValueType(i); return true; }
    bool saxUint64(uint64_t i) { new (mStack.template push<ValueType>()) ValueType(i); return true; }
    bool saxDouble(double d)   { new (mStack.template push<ValueType>()) ValueType(d); return true; }

    bool saxString(const CharType * str, SizeType length, bool copy) {
        if (copy)
            new (mStack.template push<ValueType>()) ValueType(str, length, this->getAllocator());
        else
            new (mStack.template push<ValueType>()) ValueType(str, length);
        return true;
    }

    bool saxStartObject() { new (mStack.template push<ValueType>()) ValueType(kObjectType); return true; }

    bool saxKey(const CharType * str, SizeType length, bool copy) { return saxString(str, length, copy); }

    bool saxEndObject(SizeType memberCount) {
        typename ValueType::MemberType * members = mStack.template pop<typename ValueType::MemberType>(memberCount);
        mStack.template Top<ValueType>()->setObjectRaw(members, (SizeType)memberCount, this->getAllocator());
        return true;
    }

    bool saxStartArray() { new (mStack.template push<ValueType>()) ValueType(kArrayType); return true; }

    bool saxEndArray(SizeType elementCount) {
        ValueType * elements = mStack.template pop<ValueType>(elementCount);
        mStack.template Top<ValueType>()->setArrayRaw(elements, elementCount, this->getAllocator());
        return true;
    }
    // End of implementation of ReaderHandler

    //
    // BasicDocument::parse<parseFlags, SourceEncodingT, InuptStreamT>(is);
    //
    template <size_t parseFlags, typename SourceEncodingT, typename InuptStreamT>
    BasicDocument & parseStream(const InuptStreamT & is) {
        // Remove existing root if exist
        ValueType::setNull();
        BasicReader<parseFlags, SourceEncodingT, EncodingT, PoolAllocatorT, AllocatorT>
            reader(this->getPoolAllocator(), false, this->getPoolAllocator());

        // Parse the stream use SAX mode in Reader class.
        mParseResult = reader.parseStream(const_cast<InuptStreamT &>(is), *this);
        if (mParseResult.hasError()) {
            // Get the error code.
            mParseResult.getError();
        }
        return *this;
    }

    //
    // BasicDocument::parse(InputStreamT & is);
    //
    template <size_t parseFlags, typename InputStreamT>
    BasicDocument & parseStream(const InputStreamT & is) {
        return parseStream<parseFlags, EncodingT, InputStreamT>(is);
    }

    template <typename InputStreamT>
    BasicDocument & parseStream(const InputStreamT & is) {
        return parseStream<kDefaultParseFlags>(is);
    }

    //
    // BasicDocument::parse(StringInputStreamType & is);
    //
    template <size_t parseFlags, typename SourceEncodingT>
    BasicDocument & parseStream(const StringInputStreamType & is) {
        return parseStream<parseFlags, SourceEncodingT, StringInputStreamType>(is);
    }

    template <size_t parseFlags>
    BasicDocument & parseStream(const StringInputStreamType & is) {
        return parseStream<parseFlags, EncodingT>(is);
    }

    BasicDocument & parseStream(const StringInputStreamType & is) {
        return parseStream<kDefaultParseFlags>(is);
    }

    //
    // BasicDocument::parse(const CharType * text);
    //
    template <size_t parseFlags, typename SourceEncodingT, typename InputStreamT>
    BasicDocument & parseStream(const CharType * text) {
        jimi_assert(text != NULL);
        InputStreamT inputStream(text);
        return parseStream<parseFlags, SourceEncodingT, InputStreamT>(inputStream);
    }

    template <size_t parseFlags, typename SourceEncodingT>
    BasicDocument & parseStream(const CharType * text) {
        return parseStream<parseFlags, SourceEncodingT, StringInputStreamType>(text);
    }

    template <typename InputStreamT>
    BasicDocument & parseStream(const typename InputStreamT::CharType * text) {
        return parseStream<kDefaultParseFlags, EncodingT, InputStreamT>(text);
    }

    template <size_t parseFlags>
    BasicDocument & parseStream(const CharType * text) {
        return parseStream<parseFlags, EncodingT>(text);
    }

    BasicDocument & parseStream(const CharType * text) {
        return parseStream<kDefaultParseFlags>(text);
    }

    //
    // BasicDocument::parse<parseFlags, SourceEncodingT, InuptStreamT>(is);
    //
    template <size_t parseFlags, typename SourceEncodingT, typename InuptStreamT>
    BasicDocument & parse(const InuptStreamT & is) {
        // Remove existing root if exist
        ValueType::setNull();
        BasicReader<parseFlags, SourceEncodingT, EncodingT, PoolAllocatorT, AllocatorT>
            reader(this->getPoolAllocator(), false, this->getPoolAllocator());

        // Parse the stream use SAX mode in Reader class.
        mParseResult = reader.parse(const_cast<InuptStreamT &>(is), *this);
        if (mParseResult.hasError()) {
            // Get the error code.
            mParseResult.getError();
        }
        return *this;
    }

    //
    // BasicDocument::parse(InputStreamT & is);
    //
    template <size_t parseFlags, typename InputStreamT>
    BasicDocument & parse(const InputStreamT & is) {
        return parse<parseFlags, EncodingT, InputStreamT>(is);
    }

    template <typename InputStreamT>
    BasicDocument & parse(const InputStreamT & is) {
        return parse<kDefaultParseFlags>(is);
    }

    //
    // BasicDocument::parse(StringInputStreamType & is);
    //
    template <size_t parseFlags, typename SourceEncodingT>
    BasicDocument & parse(const StringInputStreamType & is) {
        return parse<parseFlags, SourceEncodingT, StringInputStreamType>(is);
    }

    template <size_t parseFlags>
    BasicDocument & parse(const StringInputStreamType & is) {
        return parse<parseFlags, EncodingT>(is);
    }

    BasicDocument & parse(const StringInputStreamType & is) {
        return parse<kDefaultParseFlags>(is);
    }

    //
    // BasicDocument::parse(const CharType * text);
    //
    template <size_t parseFlags, typename SourceEncodingT, typename InputStreamT>
    BasicDocument & parse(const CharType * text) {
        jimi_assert(text != NULL);
        InputStreamT inputStream(text);
        return parse<parseFlags, SourceEncodingT, InputStreamT>(inputStream);
    }

    template <size_t parseFlags, typename SourceEncodingT>
    BasicDocument & parse(const CharType * text) {
        return parse<parseFlags, SourceEncodingT, StringInputStreamType>(text);
    }

    template <typename InputStreamT>
    BasicDocument & parse(const typename InputStreamT::CharType * text) {
        return parse<kDefaultParseFlags, EncodingT, InputStreamT>(text);
    }

    template <size_t parseFlags>
    BasicDocument & parse(const CharType * text) {
        return parse<parseFlags, EncodingT>(text);
    }

    BasicDocument & parse(const CharType * text) {
        return parse<kDefaultParseFlags>(text);
    }
};

// Recover the packing alignment
#pragma pack(pop)

template <typename EncodingT, typename PoolAllocatorT, typename AllocatorT>
void BasicDocument<EncodingT, PoolAllocatorT, AllocatorT>::visit()
{
    printf("JsonFx::BasicDocument::visit(). EncodingType = %d\n\n", EncodingType::type);
}

}  // namespace JsonFx

// Define default Document class type
typedef JsonFx::BasicDocument<>     jfxDocument;

#endif  /* !_JSONFX_DOCUMENT_H_ */

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Globalization;

namespace Othello
{
    public sealed class OthelloGameAIConfig
    {
        public int depth { get; set; }
        public float alpha { get; set; }
        public float beta { get;set; }
        public string turnrange { get; set; }
        public int difficulty { get; set; }

        public bool IsInRange(int Turn, GameDifficultyMode difficulty)
        {
            if (this.difficulty != (int)difficulty)
                return false;

            //e.g. input is (0:30), (40:43]
            string[] ranges = turnrange.Split(':');

            if (ranges[0].Contains("("))
            {
                if (Turn <= int.Parse(ranges[0].Remove(0, 1), CultureInfo.InvariantCulture))
                    return false;
            }
            else if (ranges[0].Contains("["))
            {
                if (Turn < int.Parse(ranges[0].Remove(0, 1), CultureInfo.InvariantCulture))
                    return false;
            }
            else
                throw new Exception(string.Format(CultureInfo.CurrentCulture,"invalid config parameter in {0} in row: {1}\t{2}\t{3}\t{4}\t{5}",ranges[0],depth,alpha,beta,turnrange, difficulty));

            if(ranges[1].Contains(")"))
            {
                if (Turn >= int.Parse(ranges[1].TrimEnd(')'), CultureInfo.InvariantCulture))
                    return false;
            }
            else if(ranges[1].Contains("]"))
            {
                if (Turn > int.Parse(ranges[1].TrimEnd(']'), CultureInfo.InvariantCulture))
                    return false;
            }
            else
                throw new Exception(string.Format(CultureInfo.CurrentCulture, "invalid config parameter in {0} in row: {1}\t{2}\t{3}\t{4}\t{5}", ranges[1], depth, alpha, beta, turnrange, difficulty));

            return true;
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('languages_plus', '0003_auto_20150803_1140'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='language',
            name='iso_639_6',
        ),
        migrations.RemoveField(
            model_name='language',
            name='name_other',
        ),
    ]


text:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");

var t = async_test("Multiple scale()s combine");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
    throw reason;
});
t.step(function() {

var canvas = new OffscreenCanvas(100, 50);
var ctx = canvas.getContext('2d');

ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.scale(Math.sqrt(2), Math.sqrt(2));
ctx.scale(Math.sqrt(2), Math.sqrt(2));
ctx.fillStyle = '#0f0';
ctx.fillRect(0, 0, 50, 25);
_assertPixel(canvas, 90,40, 0,255,0,255);
t.done();

});
done();


text:
<?php
//Blantly ripped off from https://github.com/donatj/mjpeg-php/blob/master/mjpeg.php
//And then modified to suit out needs

define('BASE_DIR', dirname(__FILE__));
require_once(BASE_DIR.'/config.php');

if (isset($_GET["pDelay"]))
   {
      $preview_delay = $_GET["pDelay"];
   } else {
      $preview_delay = 10000;
   }

//writeLog("mjpeg stream with $preview_delay delay");

// Used to separate multipart
$boundary = "PIderman";

// We start with the standard headers. PHP allows us this much
header ("Content-type: multipart/x-mixed-replace; boundary=$boundary");
header ("Cache-Control: no-cache");
header ("Pragma: no-cache");
header ("Connection: close");

ob_flush();		//Push out the content we already have (gets the headers to the browser as quickly as possible)

set_time_limit(0); // Set this so PHP doesn't timeout during a long stream

while(true)
{
	ob_start();

	echo "--$boundary\r\n";
	echo "Content-type: image/jpeg\r\n";

	$fileContents = file_get_contents("/dev/shm/mjpeg/cam.jpg");
	$fileLength = strlen($fileContents);

	echo "Content-Length:" . $fileLength . "\r\n";
	echo "\r\n";

	echo $fileContents;

	echo "\r\n";
	ob_end_flush();

	usleep($preview_delay);
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

    <meta name="author" content="Alex Moriarty">
    <meta name="description" content="Alex Moriarty enjoys travelling, photography, cycling, longboarding, skiing and website development">

    <title>hobbies amoriarty</title>
    <link rel="icon" type="image/png" href="./favicon.png"/>
	<link rel="stylesheet" type="text/css" href="./js/shadowbox/shadowbox.css" media="screen" />
	<link rel="stylesheet" type="text/css" href="./css/style.css" media="all"/>

			a. moriarty

About

Experience

Portfolio

Research

Hobbies

			<select>
				<option value="" selected="selected">Navigation</option>
			</select>

				home > hobbies

				Things I like to do

Photography

All the background images on this site are my own work. I have taken over 20,000 photos in the past 5 years. Currently I have 6 Canon camera's and of course the an iPhone camera. My primary camera's are: Canon EOS-7D for digital, Canon EOS-3 for film and Canon Powershot D20 underwater camera for getting wet.

Putting together an album by "hand" and generating thumbnail images without the help of php is a pain. So for this final project I'm going to reuse my YouBot images. These images were taken by me at Automatica 2012 in Munich, Germany. The rights have since been given to The Youbot Store and National Intruments

Outdoor Activities

I could keep some sort of blog here... As long as I could update it via twitter automatically.

github

linkedin

facebook

google+

twitter

				<address>
					Alexander Moriarty

					Dalhousie University

					Halifax, NS, Canada

					moriarty"at"cs.dal.ca
				</address>

				am

				<select>
					<option value="" selected="selected">Navigation</option>
				</select>

				Documentation

				Updated: Nov. 29 2012

				© Alex Moriarty


text:
package com.xivvic.args.schema.item;

import java.util.Objects;

public class ItemPredicateHasEnvironmentVariable<T>
implements ItemPredicate<T>
{

	@Override
	public boolean test(Item<T> item)
	{
		Objects.requireNonNull(item);
		String s = item.getEv();
		return s != null;
	}
}


text:
<!DOCTYPE html>

    <meta name="robots" content="noindex,nofollow" />
    <meta property="og:title" content="My First Campaign" />

            <?php echo $w_title; ?>

              Site web : <?php echo $w_url_rw; ?>

              Langages site web : <?php echo $l_title; ?>

              Accès Administrateur

              Utilisateur  : <?php echo $w_admin_login; ?>

              Mot de passe : <?php echo $w_admin_password; ?>

              Accès FTP

              Serveur : <?php echo $w_adresseip; ?>

              Utilisateur : <?php echo $w_login_ftp; ?>

              Mot de passe : <?php echo $w_password_ftp; ?>

            <button type="button" style="display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: 700; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; color: #fff; background-color: #FF6B57; border-color: #FF6B57;">
              Contacter le webmaster
            </button>

          2015 © Company. ALL Rights Reserved.


text:
import { isDevMode } from '@angular/core';

export function ɵcacheInstance<T>(cacheKey: any, moduleName: string, appName: string, fn: () => T, deps: any): T {
  const [, instance, cachedDeps] = globalThis.ɵAngularfireInstanceCache.find((it: any) => it[0] === cacheKey) || [];
  if (instance) {
    if (!matchDep(deps, cachedDeps)) {
      log('error', `${moduleName} was already initialized on the ${appName} Firebase App with different settings.${IS_HMR ? ' You may need to reload as Firebase is not HMR aware.' : ''}`);
      log('warn', {is: deps, was: cachedDeps});
    }
    return instance;
  } else {
    const newInstance = fn();
    globalThis.ɵAngularfireInstanceCache.push([cacheKey, newInstance, deps]);
    return newInstance;
  }
}

function matchDep(a: any, b: any) {
  try {
    return a.toString() === b.toString();
  } catch (_) {
    return a === b;
  }
}

const IS_HMR = !!(module as any).hot;

const log = (level: 'log'|'error'|'info'|'warn', ...args: any) => {
  if (isDevMode() && typeof console !== 'undefined') {
    console[level](...args);
  }
};

globalThis.ɵAngularfireInstanceCache ||= [];


text:
#ifndef VV_PROGRESS_DIALOG_H
#define VV_PROGRESS_DIALOG_H

#include "precompiled.h"
#include "vvDialog.h"
#include "vvNullable.h"
#include "vvSgLogHandler.h"
#include "vvCommand.h"
#include "vvProgressExecutor.h"

/**
 * An sglib log handler that displays progress in a dialog box.
 * This dialog is explicitly thread-safe, so it can display progress occurring in another thread.
 */
class vvProgressDialog : public wxDialog, public vvSgGeneralLogHandler
{
// types
public:
	// These would be private, but WX needs it to be accessible from global scope.
	class OperationEvent; //< A type of event used to marshal operation calls across threads.
	class MessageEvent;   //< A type of event used to marshal message reports across threads.
	class ErrorCaughtEvent;   //< A type of event used to request a login dialog.

// constants
public:
	static const char* DefaultTitle; //< Default title for progress dialogs.
	static const long  DefaultStyle; //< Default style for progress dialogs.

// construction
public:
	/**
	 * Default constructor.
	 */
	vvProgressDialog();

	/**
	 * Create constructor.
	 */
	vvProgressDialog(
		wxWindow*       wParent,                       //< [in] The new dialog's parent window, or NULL if it won't have one.
		vvProgressExecutor* pExecutor,				   //< [in] The executor that launched the progress dialog.
		wxWindowID      cId       = wxID_ANY,          //< [in] ID to use for the dialog.
		const wxString& sTitle    = DefaultTitle,      //< [in] Title to use for the dialog.
		const wxPoint&  cPosition = wxDefaultPosition, //< [in] Initial position for the dialog.
		const wxSize&   cSize     = wxDefaultSize,     //< [in] Initial size for the dialog.
		long            iStyle    = DefaultStyle,      //< [in] Style flags to use for the dialog.
		const wxString& sName     = wxDialogNameStr    //< [in] Window class name for the dialog.
		);

	/**
	 * Destructor.
	 */
	~vvProgressDialog();

// functionality
public:
	/**
	 * Creates the actual dialog window.
	 */
	virtual bool Create(
		wxWindow*       wParent,                       //< [in] The new dialog's parent window, or NULL if it won't have one.
		wxWindowID      cId       = wxID_ANY,          //< [in] ID to use for the dialog.
		const wxString& sTitle    = DefaultTitle,      //< [in] Title to use for the dialog.
		const wxPoint&  cPosition = wxDefaultPosition, //< [in] Initial position for the dialog.
		const wxSize&   cSize     = wxDefaultSize,     //< [in] Initial size for the dialog.
		long            iStyle    = DefaultStyle,      //< [in] Style flags to use for the dialog.
		const wxString& sName     = wxDialogNameStr    //< [in] Window class name for the dialog.
		);

	/**
	 * Updates the dialog's display based on its data.
	 */
	void UpdateDisplay();

	/**
	 * Checks if the user has pushed the Cancel button.
	 */
	bool CancelRequested();

	void ExecutionStarted();
	void ExecutionStopped();

// event handlers
protected:
	void OnUpdateTimer(wxTimerEvent& cEvent);
	void OnOperationPush(OperationEvent& cEvent);
	void OnOperationPop(OperationEvent& cEvent);
	void OnOperationReplace(OperationEvent& cEvent);
	void OnMessage(MessageEvent& cEvent);
	void OnClose(wxCommandEvent& cEvent);
	void OnCancel(wxCommandEvent& cEvent);
	void OnErrorCaught(ErrorCaughtEvent& cEvent);
	void EnableTheCloseButton();
	void OnShown(wxShowEvent& cEvent);
	void OnUpdateEvent(wxListEvent& cEvent);

// private types
private:
	// forward declarations
	class OperationControl;
	class MessageListCtrl;

	/**
	 * A stack of progress operation data.
	 */
	typedef std::stack<struct _OperationData*> stlOperationStack;

// private constants
private:
	static const char* CloseButtonText;     //< Text used for the dialog's OK/close button.
	static const char* CancelButtonText;    //< Text used for the dialog's cancel button.
	static const char* CancelingButtonText; //< Text used for the cancel button after it's clicked/disabled.
	static const int   UpdateTime;          //< Milliseconds in between display updates.
	static const char* CompletedTitle;		//< The title used when the operation is completed without error.
	static const char* ErrorTitle;			//< The title used when the operation is completed with an error.

// private helpers
private:
	void RemoveOperation();
	void vvProgressDialog::SetTheTitle(wxString sTheTitle);
// private data
private:
	// data
	vvProgressExecutor* mpExecutor;
	stlOperationStack mcOperations;  //< Stack of currently running operations.
	wxTimer           mcUpdateTimer; //< Timer that pings us to update our controls.
	vvNullable<bool>  mnbFinished;   //< Whether or not our last operation has completed.
	                                 //< If NULL, no operations have been started yet.
	vvNullable<bool>  mnbCanceling;  //< Whether or not the user is attempting to cancel the running operations.
	                                 //< If NULL, the current top-level operation is not cancelable.

	int mnExecutionCount;

	// sizers
	wxBoxSizer*       mpOperationSizer;
	wxStaticBoxSizer* mpMessageSizer;

	// widgets
	wxTextCtrl*      mwMessageText;
	MessageListCtrl* mwMessageList;
	wxButton*        mwCloseButton;
	wxButton*        mwCancelButton;
	bool bEnableCloseButton;
	wxString		 msTitle;
// macro declarations
private:
	DECLARE_DYNAMIC_CLASS(vvProgressDialog);
	DECLARE_EVENT_TABLE();
};

/**
 * An event for requesting login credentials.
 */
class vvProgressDialog::ErrorCaughtEvent : public wxEvent
{
// construction
public:
	/**
	 * Constructor.
	 */
	ErrorCaughtEvent(
		int             iWinId,  //< [in] ID of the window to receive the event.
		vvProgressExecutor* pExecutor,
		vvCommand* pCurrentCommand,
		wxUint64 sgErrorCode
		);

public:
	vvCommand* GetCurrentCommand() const
	{
		return mpCurrentCommand;
	}
	vvProgressExecutor* GetExecutor() const
	{
		return mpExecutor;
	}
	wxUint64 GetErrorCode() const
	{
		return m_sgErrorCode;
	}
// implementation
public:
	virtual wxEvent* Clone() const;

private:
	class vvProgressExecutor* mpExecutor;
	class vvCommand* mpCurrentCommand;
	wxUint64 m_sgErrorCode;
};

#endif


text:
require 'xenon/routing/route_directives'

module Xenon
  module Routing
    module ParamDirectives
      include RouteDirectives

      def param_hash
        extract_request do |request|
          yield request.param_hash
        end
      end

      def params(*param_defs)
        param_hash do |hash|
          values = Array(param_defs).map do |param_def|
            if param_def.respond_to?(:has_key?)
              name, settings = param_def.each_pair.first
              value = hash.fetch(name, settings[:default])
              value = convert_param_type(value, settings[:type]) if settings.has_key?(:type)
            else
              value = hash[param_def]
            end
          end
          yield *values
        end
      end

      private

      def convert_param_type(value, type)
        if type == String then value
        elsif type == Symbol then value.to_sym
        elsif type == Bignum || type == Fixnum || type == Integer then Integer(value)
        elsif type == Float then Float(value)
        elsif type == BigDecimal then BigDecimal(v)
        else
          begin
            send(type.to_s, value)
          rescue NoMethodError
            raise "No type constructor found for #{type}"
          end
        end
      end
    end
  end
end


text:
package yuku.alkitab.base.util;

import android.os.Environment;

import java.io.File;

public class AddonManager {
	public static final String TAG = AddonManager.class.getSimpleName();

	public static String getYesPath() {
		return new File(Environment.getExternalStorageDirectory(), "bible/yes").getAbsolutePath(); //$NON-NLS-1$
	}

	/**
	 * @param yesName an added yes filename without the path.
	 */
	public static String getVersionPath(String yesName) {
		String yesPath = getYesPath();
		File yes = new File(yesPath, yesName);
		return yes.getAbsolutePath();
	}

	public static boolean hasVersion(String yesName) {
		File f = new File(getVersionPath(yesName));
		return f.exists() && f.canRead();
	}

	public static boolean mkYesDir() {
		File dir = new File(getYesPath());
		if (!dir.exists()) {
			return new File(getYesPath()).mkdirs();
		} else {
			return true;
		}
	}

}


text:
NSString *serverAddr = @"http://copapi.easyar.cn";
NSString *appKey = @"cd48a9265b666690c072cefb187dc1c3";
NSString *appSecret = @"ccdb6314b418829ef65fbfb3b14c8e30eee13f1f6a5370c5cc43955116c0001d";

@interface EasyarARViewController ()

@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *shotButton;
@property (nonatomic, strong) UIButton *cameraButton;
@property (nonatomic, strong) UIButton *centerButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) PLSLoadAnimationView *downLoadAniView;

@property (nonatomic, strong) UIButton *recordButton;
@property (nonatomic, assign) BOOL started;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, strong) easyar_PlayerRecorder *easyarRecorder;

@end

@implementation EasyarARViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    EasyARScene *easyARSceneview = [[EasyARScene alloc] initWithFrame:self.view.bounds];
    [easyARSceneview setFPS:60];
    self.view = easyARSceneview;

    self.downLoadAniView = [[PLSLoadAnimationView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    self.downLoadAniView.center = self.view.center;
    [self.view addSubview:_downLoadAniView];
    self.downLoadAniView.hidden = YES;

    [self loadScene:@"scene"];
    __weak EasyarARViewController *myself = self;
    [ARScene setMessageReceiver:^(NSString *name, NSArray<NSString *> *params) {
        [myself messageReceiverWith:name parms:params];
    }];
}

-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];

    self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 24, kButtenWidth, kButtenHeigh)];
    self.backButton.layer.cornerRadius = kButtenHeigh/2;
    self.backButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.backButton setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.backButton.hidden = YES;
    [self.view addSubview:_backButton];

    self.centerButton = [[UIButton alloc]initWithFrame:CGRectMake(kButtenWidth + 25 , 24, kButtenWidth * 2, kButtenHeigh)];
    self.centerButton.layer.cornerRadius = kButtenHeigh/2;
    self.centerButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.centerButton.titleLabel.textColor = [UIColor whiteColor];
    [self.centerButton setTitle:@"居中" forState:UIControlStateNormal];
    [self.centerButton addTarget:self action:@selector(centerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.centerButton.hidden = YES;
    [self.view addSubview:_centerButton];

    self.cameraButton = [[UIButton alloc]initWithFrame:CGRectMake(kButtenWidth * 3 + 35, 24, kButtenWidth, kButtenHeigh)];
    self.cameraButton.layer.cornerRadius = kButtenHeigh/2;
    self.cameraButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.cameraButton setImage:[UIImage imageNamed:@"toggle_camera"] forState:UIControlStateNormal];
    [self.cameraButton addTarget:self action:@selector(cameraButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.cameraButton.hidden = YES;
    [self.view addSubview:_cameraButton];

    self.shotButton = [[UIButton alloc]initWithFrame:CGRectMake(kButtenWidth * 4 + 50, 24, kButtenWidth * 2, kButtenHeigh)];
    self.shotButton.layer.cornerRadius = kButtenHeigh/2;
    self.shotButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.shotButton.titleLabel.textColor = [UIColor whiteColor];
    [self.shotButton setTitle:@"截图" forState:UIControlStateNormal];
    [self.shotButton addTarget:self action:@selector(shotButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.shotButton.hidden = YES;
    [self.view addSubview:_shotButton];

    self.nextButton = [[UIButton alloc]initWithFrame:CGRectMake(PLS_SCREEN_WIDTH - kButtenWidth * 2 - 10, 24, kButtenWidth * 2, kButtenHeigh)];
    self.nextButton.layer.cornerRadius = kButtenHeigh/2;
    self.nextButton.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    self.nextButton.titleLabel.textColor = [UIColor whiteColor];
    [self.nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.nextButton.hidden = YES;
    [self.view addSubview:_nextButton];

    self.started = NO;

    self.recordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.recordButton .frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-50, 70, 50);
    [self.recordButton setTitle:@"Record" forState:UIControlStateNormal];
    [self.recordButton setTitle:@"Stop" forState:UIControlStateSelected];
    self.recordButton .backgroundColor = [UIColor yellowColor];
    self.recordButton .hidden = YES;
    [self.recordButton  addTarget:self action:@selector(recordButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_recordButton];
}

- (void)loadScene:(NSString*)path{
    NSString * fName = [[NSBundle mainBundle] pathForResource:path ofType:@"js"];
    EasyARScene* scene = (EasyARScene*)self.view;
    if (scene != NULL) {
        [scene setMessageReceiver:^(NSString * name, NSArray<NSString *> * params) {
            (void)name;
            (void)params;
        }];
        [scene loadJavaScript:path content:[NSString stringWithContentsOfFile: fName usedEncoding:nil error:nil]];
    }
}

- (void)messageReceiverWith:(NSString *)name parms:(NSArray *)array {
    if ([name isEqualToString:@"request:JsNativeBinding.openWebView"]) {
        NSLog(@"response:JsNativeBinding.openWebView %@",array);
        [self JSMeaasgeOpenWebView:array[0]];
    } else if ([name isEqualToString:@"response:JsNativeBinding.getCameraDeviceType"]) {
        NSLog(@"response:JsNativeBinding.getCameraDeviceType %@",array);
    } else if ([name isEqualToString:@"request:JsNativeBinding.targetLost"]) {
        NSLog(@"response:JsNativeBinding.targetLost %@",array);
    } else if ([name isEqualToString:@"request:JsNativeBinding.targetFound"]) {
        NSLog(@"response:JsNativeBinding.targetFound %@",array);
        [self showFinding];
    } else if ([name isEqualToString:@"request:JsNativeBinding.showNativeButton"]) {
        NSLog(@"request:JsNativeBinding.showNativeButton %@",array);
    } else if ([name isEqualToString:@"request:JsNativeBinding.closeNativeButton"]) {
        NSLog(@"request:JsNativeBinding.closeNativeButton %@",array);
        [self showLoast];
    } else if ([name isEqualToString:@"request:JsNativeBinding.openView"]) {
        NSLog(@"request:JsNativeBinding.openView %@",array);
    }else if ([name isEqualToString:@"request:JsNativeBinding.getMetaData"]) {
        //        NSLog(@"request:JsNativeBinding.getMetaData %@",array);
    }else if ([name isEqualToString:@"request:JsNativeBinding.FinishLoading"]) {
        [self showUntracking];
        [ARScene sendMessage:@"request:NativeJsBinding.showARWithTrack" params:@[]];
    }else {
        NSLog(@"name error %@",name);
    }
}

#pragma mark - JS Message Use
- (void)JSMeaasgeOpenWebView:(NSString *)url {
    ARWebViewController *arwebVC = [ARWebViewController new];
    arwebVC.url = url;
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:arwebVC];
    [self presentViewController:navi animated:YES completion:nil];
}

#pragma mark - showUI type
- (void)showUntracking {
    NSLog(@"AR View type showUntracking");
    [self hideButtonsWithHidden:NO];
}

- (void)showFinding {
    NSLog(@"AR View type showFinding");
    [self hideButtonsWithHidden:NO];
}
- (void)showLoast {
    NSLog(@"AR View type showLoast");
    [self hideButtonsWithHidden:YES];
}

- (void)hideButtonsWithHidden:(BOOL)hidden {
    self.shotButton.hidden = hidden;
    self.backButton.hidden = hidden;
    self.recordButton.hidden = hidden;
    self.centerButton.hidden = hidden;
    self.cameraButton.hidden = hidden;
}

- (void)loadARID:(NSString*)arid{
    SPARManager *sparMan = [SPARManager sharedManager];
    [sparMan setServerAddress:serverAddr];
    [sparMan setServerAccessTokens:appKey secret:appSecret];

    __weak EasyarARViewController * weak_self = self;
    [sparMan loadApp:arid completionHandler:^(SPARApp *app, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"Error: ----%@", error);
            } else {
                NSString* manifestURL = [app.package getManifestURL];
                NSLog(@"%@", manifestURL);
                [(EasyARScene*)weak_self.view loadManifest:manifestURL];
            }
        });
    } progressHandler:^(NSString *taskName, float progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"<<<<%@: %.2f%%", taskName, progress * 100);
            if ([taskName isEqualToString:@"Download"]) {
                [weak_self showFinding];
                weak_self.downLoadAniView.hidden = NO;
                weak_self.downLoadAniView.centerLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
            }
            if (progress == 1) {
                weak_self.downLoadAniView.hidden = YES;
            }
        });
    }];
}

- (void)loadManifest:(NSString*)targetDesc{
    if (targetDesc == nil) {
        return;
    }

    __weak EasyarARViewController * weak_self = self;
    SPARManager *sparMan = [SPARManager sharedManager];
    SPARApp *app = [sparMan getAppByTargetDesc:targetDesc];
    [app deployPackage:NO completionHandler:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"Error: %@", error);
                return;
            }
            [(EasyARScene*)weak_self.view loadManifest:[app.package getManifestURL]];
        });
    } progressHandler:^(NSString *taskName, float progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@: %.2f%%", taskName, progress * 100);
            if ([taskName isEqualToString:@"Download"]) {
                [weak_self showFinding];
                weak_self.downLoadAniView.hidden = NO;
                weak_self.downLoadAniView.centerLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
            }
            if (progress == 1) {
                weak_self.downLoadAniView.hidden = YES;
            }
        });
    }];
}

#pragma mark - ButtonActive
- (void)scanLineViewBackButton:(UIButton *)button {
    NSLog(@"scanLineViewBackButton");
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)backButtonClick:(UIButton *)button {
    if (!_easyarRecorder) {
        [_easyarRecorder close];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)shotButtonClick:(UIButton *)button {
    [self snapShot];
}

- (void)snapShot{
    [(EasyARScene*)self.view snapshot:^(UIImage *image) {
         UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    } failed:^(NSString *msg) {
        NSLog(@"Error: %@", msg);
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"保存图片到相册 image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)centerButtonClick:(UIButton *)button {
    [ARScene sendMessage:@"request:NativeJsBinding.resetContent" params:@[]];
}

- (void)cameraButtonClick:(UIButton *)button {
    [ARScene sendMessage:@"request:NativeJsBinding.changeCameraDeviceType" params:@[]];
}

- (void)fail {
    [_recordButton setTitle:@"Record" forState:UIControlStateNormal];
    _started = NO;
    _url = nil;
    if (_easyarRecorder != nil) {
        _easyarRecorder = nil;
    }
}

#pragma mark -- 下一步
- (void)nextButtonClick {
    // 设置音视频、水印等编辑信息
    NSMutableDictionary *outputSettings = [[NSMutableDictionary alloc] init];
    // 待编辑的原始视频素材
    NSMutableDictionary *plsMovieSettings = [[NSMutableDictionary alloc] init];
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", _url]];

    AVAsset *asset = [AVAsset assetWithURL:URL];
    CMTime cmtime = asset.duration;
    CGFloat totalSeconds = CMTimeGetSeconds(cmtime);

    plsMovieSettings[PLSURLKey] = URL;
    plsMovieSettings[PLSAssetKey] = asset;
    plsMovieSettings[PLSStartTimeKey] = [NSNumber numberWithFloat:0.f];
    plsMovieSettings[PLSDurationKey] = [NSNumber numberWithFloat:totalSeconds];
    plsMovieSettings[PLSVolumeKey] = [NSNumber numberWithFloat:1.0f];
    outputSettings[PLSMovieSettingsKey] = plsMovieSettings;

    EditViewController *editViewController = [[EditViewController alloc] init];
    editViewController.settings = outputSettings;
    [self presentViewController:editViewController animated:NO completion:nil];
}

- (void)recordButtonClick:(UIButton *)recordButton {
    if (_started) {
        [_recordButton setTitle:@"Record" forState:UIControlStateNormal];
        _started = NO;
        if (_easyarRecorder != nil) {
            [EasyarARViewController displayToastWithMessage:[@"Recorded at " stringByAppendingString:_url]];
            [_easyarRecorder stop];
             _nextButton.hidden = NO;
        } else{
             _nextButton.hidden = YES;
        }
    } else {
        _nextButton.hidden = YES;
        if (![easyar_PlayerRecorder isAvailable]) {
            [EasyarARViewController displayToastWithMessage:@"Recorder Module Not Available"];
        }
        [_recordButton setTitle:@"Stop" forState:UIControlStateNormal];
        _started = YES;
        easyar_PlayerRecorderConfiguration *configuration = [[easyar_PlayerRecorderConfiguration alloc] init];
        configuration.Identifier = @"04_RecordPass";
        _url = [EasyarARViewController prepareURL];
        configuration.OutputFilePath = _url;
        configuration.VideoOrientation = easyar_RecordVideoOrientation_Portrait;
        configuration.ZoomMode = easyar_RecordZoomMode_ZoomInWithAllContent;
        if (!_easyarRecorder) {
            [_easyarRecorder close];
        }

        _easyarRecorder = [(EasyARScene *)(self.view) createRecorder:configuration];
        __weak EasyarARViewController * weak_self = self;
        [_easyarRecorder requestPermissions:^(easyar_PermissionStatus status, NSString *value) {
            switch (status) {
                case easyar_PermissionStatus_Denied:
                    _started = NO;
                    [EasyarARViewController displayToastWithMessage:@"Permission Denied"];
                    [weak_self fail];
                    break;
                case easyar_PermissionStatus_Error:
                    _started = NO;
                    [EasyarARViewController displayToastWithMessage:@"Permission Error"];
                    [weak_self fail];
                    break;
                case easyar_PermissionStatus_Granted:
                {
                    EasyarARViewController * strong_self = weak_self;
                    if (strong_self == nil) { return; }
                    [strong_self->_easyarRecorder open:^(easyar_RecordStatus status, NSString *value) {
                        if (status == easyar_RecordStatus_FileFailed) {
                            EasyarARViewController * strong_self = weak_self;
                            if (strong_self == nil) { return; }
                            [strong_self fail];
                        }
                        NSLog(@"Recorder Callback status: %d, MSG: %@", (int)(status), value);
                    }];
                    [strong_self->_easyarRecorder start];
                    [EasyarARViewController displayToastWithMessage:@"Recording..."];
                }
                    break;
                default:
                    break;
            }
        }];
    }
}

+ (NSString*)prepareURL
{
    static long size = 0;
    size ++ ;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *album = [docDir stringByAppendingPathComponent:@"album"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:album]) {
        NSLog(@"first run");
        [[NSFileManager defaultManager] createDirectoryAtPath:album withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",album);
    }
    double timenumber = [NSDate date].timeIntervalSince1970;
    NSLog(@"timenumber %lf",timenumber);
    NSString *time = [NSString stringWithFormat:@"%lf",timenumber];
    time = [time stringByReplacingOccurrencesOfString:@"." withString:@"mm"];
    NSLog(@"%@",time);
    NSString *videoString = [NSString stringWithFormat:@"%@number%08ld.mp4",time,size];
    NSString *path = [NSString stringWithFormat:@"%@/%@",album,videoString];
    NSLog(@"path %@",path);
    return path;
}

+ (void)displayToastWithMessage:(NSString *)toastMessage
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
        UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
        UILabel * toastView = [[UILabel alloc] init];
        toastView.text = toastMessage;
        toastView.textAlignment = NSTextAlignmentCenter;
        toastView.lineBreakMode = NSLineBreakByWordWrapping;
        toastView.numberOfLines = 0;
        toastView.frame = CGRectMake(0.0, 0.0, keyWindow.frame.size.width/2.0, 200.0);
        toastView.layer.cornerRadius = 10;
        toastView.layer.masksToBounds = YES;
        toastView.center = keyWindow.center;

        [keyWindow addSubview:toastView];

        [UIView animateWithDuration: 3.0f
                              delay: 0.0
                            options: UIViewAnimationOptionCurveEaseOut
                         animations: ^{
                             toastView.alpha = 0.0;
                         }
                         completion: ^(BOOL finished) {
                             [toastView removeFromSuperview];
                         }
         ];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)dealloc {
    NSLog(@"dealloc: %@", [[self class] description]);
}

@end


text:
<?php namespace Comodojo\Daemon\Socket;

use \Comodojo\Exception\SocketException;

class Connection {

    protected $socket;

    protected $index;

    public function __construct($socket, $i) {

        $this->index = $i;
        $this->socket = @socket_accept($socket);

        if ( $this->socket === false ) {
            $error = self::checkConnectionError($socket);
            if ( $error !== true ) {
                throw new SocketException("Cannot put socket in listening mode: $error");
            }
        }

    }

    public function getIndex() {
        return $this->index;
    }

    public function getSocket() {
        return $this->socket;
    }

    public function destroy() {
        socket_close($this->socket);
    }

    protected static function checkConnectionError($socket) {

        $err_code = socket_last_error($socket);
        $err_string = socket_strerror($err_code);

        if ( $err_code === 11 || strtolower($err_string) == 'success' ) return true;

        return $err_string;

    }

}


text:
<template name="tag">

    Tags
    <input type="text" value="{{tags}}" name="tag" id="tag" placeholder="Enter Tags" />

</template>


text:
using Microsoft.AspNet.Identity.EntityFramework;
using NetBots.WebServer.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetBots.WebServer.Data.MsSql
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<PlayerBot> PlayerBots { get; set; }
        public DbSet<GameSummary> GameSummaries { get; set; }

        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}


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

namespace Amido.NAuto.Compare
{
    public class CompareResult : List<CompareItem>
    {
        public CompareResult(IEnumerable<CompareItem> compareItems)
        {
            AddRange(compareItems);
        }

        public bool AreEqual
        {
            get
            {
                return this.All(x => x.IsEqual);
            }
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
CaptureType (Objectify-AppEngine Javadoc)
</TITLE>

<META NAME="date" CONTENT="2012-01-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.googlecode.objectify.repackaged.gentyref

Interface CaptureType

All Superinterfaces:
java.lang.reflect.Type

public interface CaptureType
extends java.lang.reflect.Type

CaptureType represents a wildcard that has gone through capture conversion.
 It is a custom subinterface of Type, not part of the java builtin Type hierarchy.

Author:

Wouter Coekaerts <wouter@coekaerts.be>

Method Summary

 java.lang.reflect.Type[]
getLowerBounds()

          Returns an array of <tt>Type</tt> objects representing the
 lower bound(s) of this type variable.

 java.lang.reflect.Type[]
getUpperBounds()

          Returns an array of <tt>Type</tt> objects representing the upper
 bound(s) of this capture.

Method Detail

getUpperBounds

java.lang.reflect.Type[] getUpperBounds()

Returns an array of <tt>Type</tt> objects representing the upper
 bound(s) of this capture. This includes both the upper bound of a <tt>? extends</tt> wildcard,
 and the bounds declared with the type variable.
 References to other (or the same) type variables in bounds coming from the type variable are
 replaced by their matching capture.

getLowerBounds

java.lang.reflect.Type[] getLowerBounds()

Returns an array of <tt>Type</tt> objects representing the
 lower bound(s) of this type variable. This is the bound of a <tt>? super</tt> wildcard.
 This normally contains only one or no types; it is an array for consistency with WildcardType.getLowerBounds().

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2012 Jeff Schnitzer and a gang of pirates. All Rights Reserved. Build version: 4.0a3


text:
class UnixWindow : public QWidget
{
    Q_OBJECT

public:
    UnixWindow();

    void minimize();
    void maximize();
    void closeWindow();

private:
    UnixPanel* mainPanel;
    QPoint oldWindowPos;
    bool dragging;
    bool customTB;

    void mousePressEvent(QMouseEvent* evt);
    void mouseDoubleClickEvent(QMouseEvent* evt);
    void mouseReleaseEvent(QMouseEvent* evt);
    void mouseMoveEvent(QMouseEvent* evt);
};

#endif


text:
require 'spec_helper'

describe RubyCA::Certificate do
  before do
    @cert = RubyCA::Certificate.new({
      :serial => "02",
      :dn => "/C=DE/ST=Berlin/L=Berlin/O=Examplicon Ltd./OU=Stuffers/CN=clerk_desktop.example.com/name=Johnny Clerk/emailAddress=clerk@example.com",
    })
  end

  describe 'Status' do
    it "should have the default status 'Valid'" do
      @cert.status.should eql(RubyCA::Certificate::STATUS[:valid])
      @cert.valid?.should be_true
    end

    it "should expire when expire date is in the past" do
      @cert.valid?.should be_true
      @cert.expire_date = DateTime.now - 2

      @cert.status.should eql(RubyCA::Certificate::STATUS[:expired])
      @cert.expired?.should be_true

      @cert.expire_date = nil
      @cert.expired?.should be_false
      @cert.valid?.should be_true
    end

    it "should not expire when expire date is in the future" do
      @cert.valid?.should be_true

      @cert.expire_date = DateTime.now + 2
      @cert.expired?.should be_false
      @cert.valid?.should be_true
    end

    it "should be revoked when revoke date is in the past" do
      @cert.valid?.should be_true
      @cert.revoke_date = DateTime.now - 2

      @cert.status.should eql(RubyCA::Certificate::STATUS[:revoked])
      @cert.revoked?.should be_true

      @cert.revoke_date = nil
      @cert.revoked?.should be_false
      @cert.valid?.should be_true
    end

    it "should not be revoked when revoke_date is in the future" do
      @cert.valid?.should be_true

      @cert.revoke_date = DateTime.now + 2
      @cert.revoked?.should be_false
      @cert.valid?.should be_true
    end

    it "should handle revoked status at higer priority than expired" do
      @cert.valid?.should be_true

      @cert.expire_date = DateTime.now - 2
      @cert.expired?.should be_true

      @cert.revoke_date = DateTime.now - 2
      @cert.revoked?.should be_true

      @cert.expire_date = nil
      @cert.revoked?.should be_true

      @cert.revoke_date = nil
      @cert.valid?.should be_true

      @cert.revoke_date = DateTime.now - 1
      @cert.expire_date = DateTime.now - 2
      @cert.revoked?.should be_true
      @cert.revoke_date = nil
      @cert.expired?.should be_true
    end
  end

  describe 'DN' do
    it "should parse the DN" do
      @cert.dn.is_a?(Hash).should be_true

      @cert.dn['CN'].should == "clerk_desktop.example.com"
      @cert.dn['CN'].should eql(@cert.cn)

      @cert.country.should == "DE"
      @cert.email.should == "clerk@example.com"
      @cert.location.should == "Berlin"
      @cert.name.should == "Johnny Clerk"
      @cert.state.should == "Berlin"
      @cert.organization.should == "Examplicon Ltd."
      @cert.ou.should == "Stuffers"
    end
  end
end


text:
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/AudioResource.hpp>
#include <SFML/Audio/AudioDevice.hpp>

namespace sf
{
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
AudioResource::AudioResource()
{
    priv::AudioDevice::AddReference();
}

////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
AudioResource::AudioResource(const AudioResource&)
{
    priv::AudioDevice::AddReference();
}

////////////////////////////////////////////////////////////
/// Destructor
////////////////////////////////////////////////////////////
AudioResource::~AudioResource()
{
    priv::AudioDevice::RemoveReference();
}

} // namespace sf


text:
<?php

class A
{
    const trait = 'trait';
    const callable = 'callable';
    const insteadof = 'insteadof';
}


text:
package org.apache.shindig.gadgets.http;

import com.google.common.base.Strings;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.common.cache.Cache;
import org.apache.shindig.common.cache.CacheProvider;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.gadgets.AuthType;

import com.google.inject.Inject;

import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Default implementation of the invalidation service. No security checks are applied when
 * invalidating Urls. Invalidation marks are added to HttpResponse objects which are then cached.
 * We do an exact equality check on the invalidation marks rather than trying to do something
 * timestamp based.
 *
 * This implementation uses an invalidate-on-read technique. HttpResponses are 'marked' with a
 * globally unique sequence value assigned to the users in who's context the signed/oauth request
 * was made. When that same request is repeated later we ensure that the mark on the cached response
 * is consistent with the current mark for the request.
 *
 * When the content for a user is invalidated a new unique sequence value is assigned to them and
 * all the marks on cached content associated with that user will become invalid.
 *
 * This technique is reliable if the lifetime of the HttpCache is tied to the invalidation cache
 * and when the invalidation cache is canonical. A non-canonical invalidation cache can be used
 * but cached responses must become invalid if an invalidation entry is missing.
 */
public class DefaultInvalidationService implements InvalidationService {

  public static final String CACHE_NAME = "invalidatedUsers";

  private final HttpCache httpCache;
  protected final Cache<String,Long> invalidationEntries;
  private final AtomicLong marker;

  private static final String TOKEN_PREFIX = "INV_TOK:";

  @Inject
  public DefaultInvalidationService(HttpCache httpCache, CacheProvider cacheProvider) {
    // Initialize to current time to mimimize conflict with persistent caches
    this(httpCache, cacheProvider, new AtomicLong(System.currentTimeMillis()));
  }

  DefaultInvalidationService(HttpCache httpCache, CacheProvider cacheProvider, AtomicLong marker) {
    this.httpCache = httpCache;
    invalidationEntries = cacheProvider.createCache(CACHE_NAME);
    this.marker = marker;
  }

  public void invalidateApplicationResources(Set<Uri> uris, SecurityToken token) {
    // TODO Add checks on content
    for (Uri uri : uris) {
      httpCache.removeResponse(new HttpRequest(uri));
    }
  }

  /**
   * Invalidate all fetched content that was signed on behalf of the specified set of users.
   *
   * @param opensocialIds
   * @param token
   */
  public void invalidateUserResources(Set<String> opensocialIds, SecurityToken token) {
    for (String userId : opensocialIds) {
      // Allocate a new mark for each user
      invalidationEntries.addElement(getKey(userId, token), marker.incrementAndGet());
    }
  }

  public boolean isValid(HttpRequest request, HttpResponse response) {
    if (request.getAuthType() == AuthType.NONE) {
      // Always valid for unauthenticated requests
      return true;
    }
    String invalidationHeader = response.getHeader(INVALIDATION_HEADER);
    if (invalidationHeader == null) {
      invalidationHeader = "";
    }
    return invalidationHeader.equals(getInvalidationMark(request));
  }

  public HttpResponse markResponse(HttpRequest request, HttpResponse response) {
    if (request.getAuthType() == AuthType.NONE) {
      return response;
    }
    String mark = getInvalidationMark(request);
    if (mark.length() > 0) {
      return new HttpResponseBuilder(response).setHeader(INVALIDATION_HEADER, mark).create();
    }
    return response;
  }

  /**
   * Get the invalidation entry key for a user in the scope of a given
   * application
   */
  private String getKey(String userId, SecurityToken token) {
    // Convert the id to the container relative form
    int colonIndex = userId.lastIndexOf(':');
    if (colonIndex != -1) {
      userId = userId.substring(colonIndex + 1);
    }

    // Assume the container is consistent in its use of either appId or appUrl.
    // Use appId
    if (!Strings.isNullOrEmpty(token.getAppId())) {
      return TOKEN_PREFIX + token.getAppId() + ':' + userId;
    }
    return TOKEN_PREFIX + token.getAppUrl() + ':' + userId;
  }

  /**
   * Calculate the invalidation mark for a request
   */
  private String getInvalidationMark(HttpRequest request) {
    StringBuilder currentInvalidation = new StringBuilder();

    Long ownerStamp = null;
    if (request.getOAuthArguments() != null && request.getOAuthArguments().getSignOwner()) {
      String ownerKey = getKey(request.getSecurityToken().getOwnerId(), request.getSecurityToken());
      ownerStamp = invalidationEntries.getElement(ownerKey);
    }
    Long viewerStamp = null;
    if (request.getOAuthArguments() != null && request.getOAuthArguments().getSignViewer()) {
      if (ownerStamp != null &&
          request.getSecurityToken().getOwnerId().equals(
              request.getSecurityToken().getViewerId())) {
        viewerStamp = ownerStamp;
      } else {
        String viewerKey = getKey(request.getSecurityToken().getViewerId(),
            request.getSecurityToken());
        viewerStamp = invalidationEntries.getElement(viewerKey);
      }
    }
    if (ownerStamp != null) {
      currentInvalidation.append("o=").append(ownerStamp).append(';');
    }
    if (viewerStamp != null) {
      currentInvalidation.append("v=").append(viewerStamp).append(';');
    }
    return currentInvalidation.toString();
  }

}


text:
sievelib
========

|travis| |codecov| |latest-version|

Client-side Sieve and Managesieve library written in Python.

* Sieve : An Email Filtering Language
  (`RFC 5228 <http://tools.ietf.org/html/rfc5228>`_)
* ManageSieve : A Protocol for Remotely Managing Sieve Scripts
  (`RFC 5804 <http://tools.ietf.org/html/rfc5804>`_)

Installation
------------

To install ``sievelib`` from PyPI::

  pip install sievelib

To install sievelib from git::

  git clone git@github.com:tonioo/sievelib.git
  cd sievelib
  python ./setup.py install

Sieve tools
-----------

What is supported
^^^^^^^^^^^^^^^^^

Currently, the provided parser supports most of the functionalities
described in the RFC. The only exception concerns section
*2.4.2.4. Encoding Characters Using "encoded-character"* which is not
supported.

The following extensions are also supported:

* Copying Without Side Effects (`RFC 3894 <https://tools.ietf.org/html/rfc3894>`_)
* Body (`RFC 5173 <https://tools.ietf.org/html/rfc5173>`_)
* Vacation (`RFC 5230 <http://tools.ietf.org/html/rfc5230>`_)
* Relational (`RFC 5231 <https://tools.ietf.org/html/rfc5231>`_)
* Imap4flags (`RFC 5232 <https://tools.ietf.org/html/rfc5232>`_)

The following extensions are partially supported:

* Date and Index (`RFC 5260 <https://tools.ietf.org/html/rfc5260>`_)
* Checking Mailbox Status and Accessing Mailbox Metadata (`RFC 5490 <https://tools.ietf.org/html/rfc5490>`_)

Extending the parser
^^^^^^^^^^^^^^^^^^^^

It is possible to extend the parser by adding new supported
commands. For example::

  import sievelib

  class MyCommand(sievelib.commands.ActionCommand):
      args_definition = [
          {"name": "testtag",
              "type": ["tag"],
              "write_tag": True,
              "values": [":testtag"],
              "extra_arg": {"type": "number",
                            "required": False},
              "required": False},
          {"name": "recipients",
              "type": ["string", "stringlist"],
              "required": True}
      ]

  sievelib.commands.add_commands(MyCommand)

Basic usage
^^^^^^^^^^^

The parser can either be used from the command-line::

  $ cd sievelib
  $ python parser.py test.sieve
  Syntax OK
  $

Or can be used from a python environment (or script/module)::

  >>> from sievelib.parser import Parser
  >>> p = Parser()
  >>> p.parse('require ["fileinto"];')
  True
  >>> p.dump()
  require (type: control)
      ["fileinto"]
  >>>
  >>> p.parse('require ["fileinto"]')
  False
  >>> p.error
  'line 1: parsing error: end of script reached while semicolon expected'
  >>>

Simple filters creation
^^^^^^^^^^^^^^^^^^^^^^^

Some high-level classes are provided with the ``factory`` module, they
make the generation of Sieve rules easier::

  >>> from sievelib.factory import FiltersSet
  >>> fs = FiltersSet("test")
  >>> fs.addfilter("rule1",
  ...              [("Sender", ":is", "toto@toto.com"),],
  ...              [("fileinto", "Toto"),])
  >>> fs.tosieve()
  require ["fileinto"];

  # Filter: rule1
  if anyof (header :is "Sender" "toto@toto.com") {
      fileinto "Toto";
  }
  >>>

Additional documentation is available within source code.

ManageSieve tools
-----------------

What is supported
^^^^^^^^^^^^^^^^^

All mandatory commands are supported. The ``RENAME`` extension is
supported, with a simulated behaviour for server that do not support
it.

For the ``AUTHENTICATE`` command, supported mechanisms are ``DIGEST-MD5``,
``PLAIN`` and ``LOGIN``.

Basic usage
^^^^^^^^^^^

The ManageSieve client is intended to be used from another python
application (there isn't any shell provided)::

  >>> from sievelib.managesieve import Client
  >>> c = Client("server.example.com")
  >>> c.connect("user", "password", starttls=False, authmech="DIGEST-MD5")
  True
  >>> c.listscripts()
  ("active_script", ["script1", "script2"])
  >>> c.setactive("script1")
  True
  >>> c.havespace("script3", 45)
  True
  >>>

Additional documentation is available with source code.

.. |latest-version| image:: https://badge.fury.io/py/sievelib.svg
   :target: https://badge.fury.io/py/sievelib
.. |travis| image:: https://travis-ci.org/tonioo/sievelib.png?branch=master
   :target: https://travis-ci.org/tonioo/sievelib
.. |codecov| image:: http://codecov.io/github/tonioo/sievelib/coverage.svg?branch=master
   :target: http://codecov.io/github/tonioo/sievelib?branch=master


text:
package com.akexorcist.roundcornerprogressbar.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.akexorcist.roundcornerprogressbar.R;

/**
 * Created by Akexorcist on 5/16/15 AD.
 */
public abstract class BaseRoundCornerProgressBar extends LinearLayout {
    protected final static int DEFAULT_PROGRESS_BAR_HEIGHT = 30;
    protected final static int DEFAULT_BACKGROUND_WIDTH = 0;
    protected final static int DEFAULT_MAX_PROGRESS = 100;
    protected final static int DEFAULT_CURRENT_PROGRESS = 0;
    protected final static int DEFAULT_SECONDARY_PROGRESS = 0;
    protected final static int DEFAULT_PROGRESS_RADIUS = 10;
    protected final static int DEFAULT_PROGRESS_PADDING = 5;
    protected final static int DEFAULT_PROGRESS_COLOR = Color.parseColor("#ff7f7f7f");
    protected final static int DEFAULT_SECONDARY_PROGRESS_COLOR = Color.parseColor("#7f7f7f7f");
    protected final static int DEFAULT_BACKGROUND_COLOR = Color.parseColor("#ff5f5f5f");

    protected LinearLayout layoutBackground;
    protected LinearLayout layoutProgress;
    protected LinearLayout layoutSecondaryProgress;

    protected float max;
    protected float progress;
    protected float secondaryProgress;

    private int backgroundWidth;
    private int backgroundHeight;
    private int radius;
    private int padding;
    private int progressColor;
    private int secondaryProgressColor;
    private int backgroundColor;

    private boolean isProgressBarCreated;
    private boolean isProgressSetBeforeDraw;
    private boolean isMaxProgressSetBeforeDraw;
    private boolean isBackgroundColorSetBeforeDraw;
    private boolean isProgressColorSetBeforeDraw;

    private boolean isScreenMeasure;
    private boolean isBackgroundLayourSet;

    @SuppressLint("NewApi")
    public BaseRoundCornerProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        if (!isInEditMode()) {
            isProgressBarCreated = false;
            isProgressSetBeforeDraw = false;
            isMaxProgressSetBeforeDraw = false;
            isBackgroundColorSetBeforeDraw = false;
            isProgressColorSetBeforeDraw = false;
            isScreenMeasure = false;
            isBackgroundLayourSet = false;

            backgroundColor = DEFAULT_BACKGROUND_COLOR;
            backgroundWidth = DEFAULT_BACKGROUND_WIDTH;
            backgroundHeight = (int) dp2px(DEFAULT_PROGRESS_BAR_HEIGHT);
            max = DEFAULT_MAX_PROGRESS;
            progress = DEFAULT_CURRENT_PROGRESS;
            secondaryProgress = DEFAULT_SECONDARY_PROGRESS;
            radius = DEFAULT_PROGRESS_RADIUS;
            padding = DEFAULT_PROGRESS_PADDING;

            progressColor = DEFAULT_PROGRESS_COLOR;
            secondaryProgressColor = DEFAULT_SECONDARY_PROGRESS_COLOR;
            backgroundColor = DEFAULT_BACKGROUND_COLOR;

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(initProgressBarLayout(), this);
            setup(context, attrs);
        } else {
            setBackgroundColor(DEFAULT_BACKGROUND_COLOR);
            setGravity(Gravity.CENTER);
            int padding = (int) dp2px(10);
            setPadding(padding, padding, padding, padding);
            TextView tv = new TextView(context);
            tv.setText(getClass().getSimpleName());
            addView(tv);
        }
    }

    protected void setup(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerProgress);

        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
        radius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, radius, metrics);
        radius = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcBackgroundRadius, DEFAULT_PROGRESS_RADIUS);

        padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, padding, metrics);
        padding = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcBackgroundPadding, DEFAULT_PROGRESS_PADDING);

        layoutBackground = (LinearLayout) findViewById(R.id.round_corner_progress_background);
        layoutBackground.setPadding(padding, padding, padding, padding);
        if (!isBackgroundColorSetBeforeDraw) {
            setBackgroundLayoutColor(typedArray.getColor(R.styleable.RoundCornerProgress_rcBackgroundColor, DEFAULT_BACKGROUND_COLOR));
        }

        layoutProgress = (LinearLayout) findViewById(R.id.round_corner_progress_progress);
        layoutSecondaryProgress = (LinearLayout) findViewById(R.id.round_corner_progress_secondary_progress);
        if (!isProgressColorSetBeforeDraw) {
            setProgressColor(
                    typedArray.getColor(R.styleable.RoundCornerProgress_rcProgressColor, DEFAULT_PROGRESS_COLOR),
                    typedArray.getColor(R.styleable.RoundCornerProgress_rcSecondaryProgressColor, DEFAULT_SECONDARY_PROGRESS_COLOR)
            );
        }

        if (!isMaxProgressSetBeforeDraw) {
            max = typedArray.getFloat(R.styleable.RoundCornerProgress_rcMax, DEFAULT_MAX_PROGRESS);
        }

        if (!isProgressSetBeforeDraw) {
            progress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcProgress, DEFAULT_CURRENT_PROGRESS);
            secondaryProgress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcSecondaryProgress, DEFAULT_SECONDARY_PROGRESS);
        }

        setup(typedArray, metrics);
        typedArray.recycle();
    }

    protected abstract void setBackgroundLayoutSize(LinearLayout layoutBackground);
    protected abstract void setup(TypedArray typedArray, DisplayMetrics metrics);
    protected abstract int initProgressBarLayout();

    @SuppressWarnings("deprecation")
    private void setProgressColor(ViewGroup layout, int color) {
        GradientDrawable gradient = new GradientDrawable();
        gradient.setShape(GradientDrawable.RECTANGLE);
        gradient.setColor(color);
        setGradientRadius(gradient);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            layout.setBackground(gradient);
        } else {
            layout.setBackgroundDrawable(gradient);
        }
    }

    protected abstract void setGradientRadius(GradientDrawable gradient);

    public void setProgressColor(int color) {
        progressColor = color;

        setProgressColor(layoutProgress, color);

        if (!isProgressBarCreated) {
            isProgressColorSetBeforeDraw = true;
        }
    }

    public void setProgressColor(int color, int secondaryColor) {
        progressColor = color;
        secondaryProgressColor = secondaryColor;

        setProgressColor(layoutProgress, color);
        setProgressColor(layoutSecondaryProgress, secondaryColor);

        if (!isProgressBarCreated) {
            isProgressColorSetBeforeDraw = true;
        }
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void setBackgroundLayoutColor(int color) {
        backgroundColor = color;
        GradientDrawable gradient = new GradientDrawable();
        gradient.setShape(GradientDrawable.RECTANGLE);
        gradient.setColor(backgroundColor);
        gradient.setCornerRadius(radius);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            layoutBackground.setBackground(gradient);
        } else {
            layoutBackground.setBackgroundDrawable(gradient);
        }

        if (!isProgressBarCreated) {
            isBackgroundColorSetBeforeDraw = true;
        }
    }

    public int getBackgroundLayoutColor() {
        return backgroundColor;
    }

    public int getProgressColor() {
        return progressColor;
    }

    public int getSecondaryProgressColor( ) {
        return secondaryProgressColor;
    }

    protected void setProgress() {
        setProgress(progress);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setBackgroundLayoutSize(layoutBackground);
        onLayoutMeasured();
        isScreenMeasure = true;
        isProgressBarCreated = true;
        setProgress();
        setSecondaryProgress();
    }

    protected abstract void onLayoutMeasured();

    public void setProgress(float progress) {
        progress = (progress > max) ? max : progress;
        progress = (progress < 0) ? 0 : progress;
        this.progress = progress;

        if(isScreenMeasure) {
            if(!isBackgroundLayourSet) {
                ViewGroup.LayoutParams backgroundParams = layoutBackground.getLayoutParams();
                backgroundParams.width = backgroundWidth;
                backgroundParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutBackground.setLayoutParams(backgroundParams);
                isBackgroundLayourSet = true;
            }
            float ratio = (progress > 0) ? max / progress : 0;
            int progressWidth = (int) setLayoutProgressWidth(ratio);
            ViewGroup.LayoutParams progressParams = layoutProgress.getLayoutParams();
            progressParams.width = progressWidth;
            progressParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutProgress.setLayoutParams(progressParams);
        }

        if (!isProgressBarCreated) {
            isProgressSetBeforeDraw = true;
        }
    }

    protected abstract float setLayoutProgressWidth(float ratio);

    public void setSecondaryProgress(float secondaryProgress) {
        secondaryProgress = (secondaryProgress > max) ? max : secondaryProgress;
        secondaryProgress = (secondaryProgress < 0) ? 0 : secondaryProgress;
        this.secondaryProgress = secondaryProgress;
        if(isScreenMeasure) {
            if(!isBackgroundLayourSet) {
                ViewGroup.LayoutParams backgroundParams = layoutBackground.getLayoutParams();
                backgroundParams.width = backgroundWidth;
                backgroundParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutBackground.setLayoutParams(backgroundParams);
                isBackgroundLayourSet = true;
            }

            float ratio = (secondaryProgress > 0) ? max / secondaryProgress : 0;
            int progressWidth = (int) setSecondaryLayoutProgressWidth(ratio);
            ViewGroup.LayoutParams progressParams = layoutSecondaryProgress.getLayoutParams();
            progressParams.width = progressWidth;
            progressParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutSecondaryProgress.setLayoutParams(progressParams);
        }

        if (!isProgressBarCreated) {
            isProgressSetBeforeDraw = true;
        }
    }

    protected abstract float setSecondaryLayoutProgressWidth(float ratio);

    protected void setSecondaryProgress() {
        setSecondaryProgress(secondaryProgress);
    }

    public float getMax() {
        return max;
    }

    public void setMax(float max) {
        if (!isProgressBarCreated) {
            isMaxProgressSetBeforeDraw = true;
        }
        this.max = max;
        setProgress(progress);
    }

    public float getProgress() {
        return progress;
    }

    public float getSecondaryProgress() {
        return secondaryProgress;
    }

    public int getBackgroundWidth() {
        return backgroundWidth;
    }

    public void setBackgroundWidth(int backgroundWidth) {
        this.backgroundWidth = backgroundWidth;
    }

    public int getBackgroundHeight() {
        return backgroundHeight;
    }

    public void setBackgroundHeight(int backgroundHeight) {
        this.backgroundHeight = backgroundHeight;
    }

    public int getRadius() {
        return radius;
    }

    public void setRadius(int radius) {
        this.radius = radius;
    }

    public int getPadding() {
        return padding;
    }

    public void setPadding(int padding) {
        this.padding = padding;
    }

    public void setSecondaryProgressColor(int secondaryProgressColor) {
        this.secondaryProgressColor = secondaryProgressColor;
    }

    public boolean isProgressBarCreated() {
        return isProgressBarCreated;
    }

    @SuppressLint("NewApi")
    protected float dp2px(float dp) {
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        return Math.round(dp * (displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    @Override
    public void invalidate() {
        super.invalidate();
        invalidateProgressLayout();
    }

    private void invalidateProgressLayout() {
        if(this.getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT
                || this.getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            ViewTreeObserver vto = layoutBackground.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        layoutBackground.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        layoutBackground.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                    setProgress();
                    setSecondaryProgress();
                }
            });
            ViewGroup.LayoutParams backgroudParam = layoutBackground.getLayoutParams();
            backgroudParam.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutBackground.setLayoutParams(backgroudParam);
        }
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.backgroundWidth = this.backgroundWidth;
        ss.backgroundHeight = this.backgroundHeight;
        ss.radius = this.radius;
        ss.padding = this.padding;
        ss.progressColor = this.progressColor;
        ss.secondaryProgressColor = this.secondaryProgressColor;
        ss.backgroundColor = this.backgroundColor;

        ss.max = this.max;
        ss.progress = this.progress;
        ss.secondaryProgress = this.secondaryProgress;

        ss.isProgressBarCreated = this.isProgressBarCreated;
        ss.isProgressSetBeforeDraw = this.isProgressSetBeforeDraw;
        ss.isMaxProgressSetBeforeDraw = this.isMaxProgressSetBeforeDraw;
        ss.isBackgroundColorSetBeforeDraw = this.isBackgroundColorSetBeforeDraw;
        ss.isProgressColorSetBeforeDraw = this.isProgressColorSetBeforeDraw;
        ss.isScreenMeasure = this.isScreenMeasure;
        ss.isBackgroundLayourSet = this.isBackgroundLayourSet;
        return ss;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if(!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState ss = (SavedState)state;
        super.onRestoreInstanceState(ss.getSuperState());

        this.backgroundWidth = ss.backgroundWidth;
        this.backgroundHeight = ss.backgroundHeight;
        this.radius = ss.radius;
        this.padding = ss.padding;
        this.progressColor = ss.progressColor;
        this.secondaryProgressColor = ss.secondaryProgressColor;
        this.backgroundColor = ss.backgroundColor;

        setProgressColor(progressColor, secondaryProgressColor);

        this.max = ss.max;
        this.progress = ss.progress;
        this.secondaryProgress = ss.secondaryProgress;

        this.isProgressBarCreated = ss.isProgressBarCreated;
        this.isProgressSetBeforeDraw = ss.isProgressSetBeforeDraw;
        this.isMaxProgressSetBeforeDraw = ss.isMaxProgressSetBeforeDraw;
        this.isBackgroundColorSetBeforeDraw = ss.isBackgroundColorSetBeforeDraw;
        this.isProgressColorSetBeforeDraw = ss.isProgressColorSetBeforeDraw;
        this.isScreenMeasure = ss.isScreenMeasure;
        this.isBackgroundLayourSet = ss.isBackgroundLayourSet;
    }

    private static class SavedState extends BaseSavedState {
        float max;
        float progress;
        float secondaryProgress;

        int backgroundWidth;
        int backgroundHeight;
        int radius;
        int padding;
        int progressColor;
        int secondaryProgressColor;
        int backgroundColor;

        int layoutBackgroundColor;
        int layoutProgress;
        int layoutSecondaryProgress;

        boolean isProgressBarCreated;
        boolean isProgressSetBeforeDraw;
        boolean isMaxProgressSetBeforeDraw;
        boolean isBackgroundColorSetBeforeDraw;
        boolean isProgressColorSetBeforeDraw;

        boolean isScreenMeasure;
        boolean isBackgroundLayourSet;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.max = in.readFloat();
            this.progress = in.readFloat();
            this.secondaryProgress = in.readFloat();

            this.backgroundWidth = in.readInt();
            this.backgroundHeight = in.readInt();
            this.radius = in.readInt();
            this.padding = in.readInt();
            this.progressColor = in.readInt();
            this.secondaryProgressColor = in.readInt();
            this.backgroundColor = in.readInt();

            this.layoutBackgroundColor = in.readInt();
            this.layoutProgress = in.readInt();
            this.layoutSecondaryProgress = in.readInt();

            this.isProgressBarCreated = in.readByte() != 0;
            this.isProgressSetBeforeDraw = in.readByte() != 0;
            this.isMaxProgressSetBeforeDraw = in.readByte() != 0;
            this.isBackgroundColorSetBeforeDraw = in.readByte() != 0;
            this.isProgressColorSetBeforeDraw = in.readByte() != 0;
            this.isScreenMeasure = in.readByte() != 0;
            this.isBackgroundLayourSet = in.readByte() != 0;
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeFloat(this.max);
            out.writeFloat(this.progress);
            out.writeFloat(this.secondaryProgress);

            out.writeInt(this.backgroundWidth);
            out.writeInt(this.backgroundHeight);
            out.writeInt(this.radius);
            out.writeInt(this.padding);
            out.writeInt(this.progressColor);
            out.writeInt(this.secondaryProgressColor);
            out.writeInt(this.backgroundColor);

            out.writeInt(this.layoutBackgroundColor);
            out.writeInt(this.layoutProgress);
            out.writeInt(this.layoutSecondaryProgress);

            out.writeByte((byte) (this.isProgressBarCreated ? 1 : 0));
            out.writeByte((byte) (this.isProgressSetBeforeDraw ? 1 : 0));
            out.writeByte((byte) (this.isMaxProgressSetBeforeDraw ? 1 : 0));
            out.writeByte((byte) (this.isBackgroundColorSetBeforeDraw ? 1 : 0));
            out.writeByte((byte) (this.isProgressColorSetBeforeDraw ? 1 : 0));
            out.writeByte((byte) (this.isScreenMeasure ? 1 : 0));
            out.writeByte((byte) (this.isBackgroundLayourSet ? 1 : 0));
        }

        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}