text:
// Copyright (C) 2007  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_SHARED_PTr_ABSTRACT_
#ifdef DLIB_SHARED_PTr_ABSTRACT_

#include "weak_ptr_abstract.h"
#include <exception>

namespace dlib
{

// ----------------------------------------------------------------------------------------

    class bad_weak_ptr: public std::exception {}

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    class shared_ptr
    {
        /*!
            INITIAL VALUE
                defined by constructors

            WHAT THIS OBJECT REPRESENTS
                This object represents a reference counted smart pointer.  Each shared_ptr
                contains a pointer to some object and when the last shared_ptr that points
                to the object is destructed or reset() then the object is guaranteed to be
                deleted.

                This is an implementation of the std::tr1::shared_ptr template from the
                document ISO/IEC PDTR 19768, Proposed Draft Technical Report on C++
                Library Extensions.  The only deviation from that document is that this
                shared_ptr is declared inside the dlib namespace rather than std::tr1.

            THREAD SAFETY
                This object is not thread safe.  Especially so since it is
                reference counted.  So you should take care to not have two shared_ptr
                objects in different threads that point to the same object.

                If you want a thread safe version of this object you should use the
                dlib::shared_ptr_thread_safe object instead.
        !*/

    public:

        typedef T element_type;

        shared_ptr(
        );
        /*!
            ensures
                - #get() == 0
                - #use_count() == 0
        !*/

        template<typename Y>
        explicit shared_ptr(
            Y* p
        );
        /*!
            requires
                - p is convertible to a T* type pointer
                - p can be deleted by calling "delete p;" and doing so will not throw exceptions
                - p != 0
            ensures
                - #get() == p
                - #use_count() == 1
                - #*this object owns the pointer p
            throws
                - std::bad_alloc
                  if this exception is thrown then "delete p;" is called
        !*/

        template<typename Y, typename D>
        shared_ptr(
            Y* p,
            const D& d
        );
        /*!
            requires
                - p is convertible to a T* type pointer
                - D is copy constructable (and the copy constructor of D doesn't throw)
                - p can be deleted by calling "d(p);" and doing so will not throw exceptions
                - p != 0
            ensures
                - #get() == p
                - #use_count() == 1
                - #*this object owns the pointer p
            throws
                - std::bad_alloc
                  if this exception is thrown then "d(p);" is called
        !*/

        shared_ptr(
            const shared_ptr& r
        );
        /*!
            ensures
                - #get() == #r.get()
                - #use_count() == #r.use_count()
                - If r is empty, constructs an empty shared_ptr object; otherwise, constructs
                  a shared_ptr object that shares ownership with r.
        !*/

        template<typename Y>
        shared_ptr(
            const shared_ptr<Y>& r
        );
        /*!
            requires
                - Y* is convertible to T*
            ensures
                - #get() == #r.get()
                - #use_count() == #r.use_count()
                - If r is empty, constructs an empty shared_ptr object; otherwise, constructs
                  a shared_ptr object that shares ownership with r.
        !*/

        template<typename Y>
        explicit shared_ptr(
            const weak_ptr<Y>& r
        );
        /*!
            requires
                - Y* is convertible to T*
            ensures
                - #get() == #r.get()
                - #use_count() == #r.use_count()
                - If r is empty, constructs an empty shared_ptr object; otherwise, constructs
                  a shared_ptr object that shares ownership with r.
            throws
                - bad_weak_ptr
                  this exception is thrown if r.expired() == true
        !*/

        template<typename Y>
        explicit shared_ptr(
            std::auto_ptr<Y>& r
        );
        /*!
            requires
                - p.get() != 0
                - p.release() is convertible to a T* type pointer
                - p.release() can be deleted by calling "delete p.release();" and doing so will not throw exceptions
            ensures
                - #get() == p.release()
                - #use_count() == 1
                - #r.get() == 0
                - #*this object owns the pointer p.release()
            throws
                - std::bad_alloc
        !*/

        ~shared_ptr(
        );
        /*!
            ensures
                - if (use_count() > 1)
                    - this object destroys itself but otherwise has no effect (i.e.
                      the pointer get() is still valid and shared between the remaining
                      shared_ptr objects)
                - else if (use_count() == 1)
                    - deletes the pointer get() by calling delete (or using the deleter passed
                      to the constructor if one was passed in)
                - else
                    - in this case get() == 0 so there is nothing to do so nothing occurs
        !*/

        shared_ptr& operator= (
            const shared_ptr& r
        );
        /*!
            ensures
                - equivalent to shared_ptr(r).swap(*this).
                - returns #*this
        !*/

        template<typename Y>
        shared_ptr& operator= (
            const shared_ptr<Y>& r
        );
        /*!
            requires
                - Y* is convertible to T*
            ensures
                - equivalent to shared_ptr(r).swap(*this).
                - returns #*this
        !*/

        template<typename Y>
        shared_ptr& operator= (
            std::auto_ptr<Y>& r
        );
        /*!
            requires
                - p.get() != 0
                - p.release() is convertible to a T* type pointer
                - p.release() can be deleted by calling "delete p.release();" and doing so will not throw exceptions
            ensures
                - equivalent to shared_ptr(r).swap(*this).
                - returns #*this
        !*/

        void reset(
        );
        /*!
            ensures
                - equivalent to shared_ptr().swap(*this)
        !*/

        template<typename Y>
        void reset(
            Y* p
        );
        /*!
            requires
                - p is convertible to a T* type pointer
                - p can be deleted by calling "delete p;" and doing so will not throw exceptions
                - p != 0
            ensures
                - equivalent to shared_ptr(p).swap(*this)
        !*/

        template<typename Y, typename D>
        void reset(
            Y* p,
            const D& d
        );
        /*!
            requires
                - p is convertible to a T* type pointer
                - D is copy constructable (and the copy constructor of D doesn't throw)
                - p can be deleted by calling "d(p);" and doing so will not throw exceptions
                - p != 0
            ensures
                - equivalent to shared_ptr(p,d).swap(*this)
        !*/

        T* get(
        ) const;
        /*!
            ensures
                - returns the stored pointer
        !*/

        T& operator*(
        ) const;
        /*!
            requires
                - get() != 0
            ensures
                - returns a reference to *get()
        !*/

        T* operator->(
        ) const;
        /*!
            requires
                - get() != 0
            ensures
                - returns get()
        !*/

        bool unique(
        ) const;
        /*!
            ensures
                - returns (use_count() == 1)
        !*/

        long use_count(
        ) const;
        /*!
            ensures
                - The number of shared_ptr objects, *this included, that share ownership with *this, or 0 when *this
                  is empty.
        !*/

        operator bool(
        ) const;
        /*!
            ensures
                - returns (get() != 0)
        !*/

        void swap(
            shared_ptr& b
        );
        /*!
            ensures
                - swaps *this and item
        !*/

    };

// ----------------------------------------------------------------------------------------

    template<typename T, typename U>
    bool operator== (
        const shared_ptr<T>& a,
        const shared_ptr<U>& b
    );
    /*!
        ensures
            - returns a.get() == b.get()
    !*/

    template<typename T, typename U>
    bool operator!= (
        const shared_ptr<T>& a,
        const shared_ptr<U>& b
    ) { return a.get() != b.get(); }
    /*!
        ensures
            - returns a.get() != b.get()
    !*/

    template<typename T, typename U>
    bool operator< (
        const shared_ptr<T>& a,
        const shared_ptr<U>& b
    );
    /*!
        ensures
            - Defines an operator< on shared_ptr types appropriate for use in the associative
              containers.
    !*/

    template<typename T>
    void swap(
        shared_ptr<T>& a,
        shared_ptr<T>& b
    ) { a.swap(b); }
    /*!
        provides a global swap function
    !*/

    template<typename T, typename U>
    shared_ptr<T> static_pointer_cast(
        const shared_ptr<U>& r
    );
    /*!
        - if (r.get() == 0) then
            - returns shared_ptr<T>()
        - else
            - returns a shared_ptr<T> object that stores static_cast<T*>(r.get()) and shares
              ownership with r.
    !*/

    template<typename T, typename U>
    shared_ptr<T> const_pointer_cast(
        const shared_ptr<U>& r
    );
    /*!
        - if (r.get() == 0) then
            - returns shared_ptr<T>()
        - else
            - returns a shared_ptr<T> object that stores const_cast<T*>(r.get()) and shares
              ownership with r.
    !*/

    template<typename T, typename U>
    shared_ptr<T> dynamic_pointer_cast(
        const shared_ptr<U>& r
    );
    /*!
        ensures
            - if (dynamic_cast<T*>(r.get()) returns a nonzero value) then
                - returns a shared_ptr<T> object that stores a copy of
                  dynamic_cast<T*>(r.get()) and shares ownership with r
            - else
                - returns an empty shared_ptr<T> object.
    !*/

    template<typename E, typename T, typename Y>
    std::basic_ostream<E, T> & operator<< (
        std::basic_ostream<E, T> & os,
        const shared_ptr<Y>& p
    );
    /*!
        ensures
            - performs os << p.get()
            - returns os
    !*/

    template<typename D, typename T>
    D* get_deleter(
        const shared_ptr<T>& p
    );
    /*!
        ensures
            - if (*this owns a deleter d of type cv-unqualified D) then
                - returns &d
            - else
                - returns 0
    !*/

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_SHARED_PTr_ABSTRACT_


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Compute.Models
{
    internal partial class DiagnosticsProfile : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(BootDiagnostics))
            {
                writer.WritePropertyName("bootDiagnostics");
                writer.WriteObjectValue(BootDiagnostics);
            }
            writer.WriteEndObject();
        }

        internal static DiagnosticsProfile DeserializeDiagnosticsProfile(JsonElement element)
        {
            Optional<BootDiagnostics> bootDiagnostics = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("bootDiagnostics"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    bootDiagnostics = BootDiagnostics.DeserializeBootDiagnostics(property.Value);
                    continue;
                }
            }
            return new DiagnosticsProfile(bootDiagnostics.Value);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var routes = function() {
  var _routes = [];
  var me = this;

  this.parseRoute = function(path) {
    this.parseGroups = function(loc) {
      var nameRegexp = new RegExp(":([^/.\\\\]+)", "g");
      var newRegexp = "" + loc;
      var groups = {};
      var matches = null;
      var i = 0;

      // Find the places to edit.
      while(matches = nameRegexp.exec(loc)) {
        groups[matches[1]] = i++;
        newRegexp = newRegexp.replace(matches[0], "([^/.\\\\]+)");
      }

      newRegexp += "$"; // Only do a full string match

      return { "groups" : groups, "regexp": new RegExp(newRegexp)};
    };

    return this.parseGroups(path);
  };

  var matchRoute = function(url, e) {
    var route = null;
    for(var i = 0; route = _routes[i]; i ++) {
      var routeMatch = route.regex.regexp.exec(url);
      if(!!routeMatch == false) continue;

      var params = {};
      for(var g in route.regex.groups) {
        var group = route.regex.groups[g];
        params[g] = routeMatch[group + 1];
      }

      var values = {};
      if(e && e.target instanceof HTMLFormElement) {
        var form = e.target;
        var items = form.length;
        var item;
        for(var j = 0; item = form[j]; j++) {
          if(!!item.name) values[item.name] = item.value;
        }
      }

      route.callback({"url": url, "params": params, "values" : values, "e": e});
      return true;
    }

    return false;
  };

  this.get = function(route, callback) {
    _routes.push({regex: this.parseRoute(route), "callback": callback, method: "get"});
  };

  this.post = function(route, callback) {
    _routes.push({regex: this.parseRoute(route), "callback": callback, method: "post"});
  };

  this.test = function(url) {
    matchRoute(url);
  };

  this.getRoutes = function() {
    return _routes;
  };

  var attach = function() {
    var triggered = false;
    var cancelHashChange = false;
    var cancelPopstate = false;

    // Add a new event to HTML5 History
    if(!!window.history && !!window.history.pushState) {

      var pushStateProxy = history.__proto__.pushState;

      history.__proto__.pushState = function(state, title, url) {
        pushStateProxy.apply(history, arguments);

        //var evt = document.createEvent("PopStateEvent");
        //evt.initPopStateEvent("statechange", false, false, state);
        var evt = document.createEvent("Event");
        evt.initEvent("statechange",false, false);
        evt.state = state;
        window.dispatchEvent(evt);
        return;
      };
    }

    me.run = function() {
      if(!triggered) {
        matchRoute(document.location.pathname);
        triggered = true;
      }
    };

    var stateChangeHandler = function(e) {
      if(cancelPopstate) {
        cancelPopstate = false;
        cancelHashChange = false;
        return;
      }

      matchRoute(document.location.pathname);
    };

    // Intercept FORM submissions.
    window.addEventListener("submit", function(e) {
      if(e.target.method == "post") {
        if (matchRoute(e.target.action, e)) {
           e.preventDefault();
           return false;
        }
      }
      // If we haven't matched a URL let the normal request happen.
      return true;
    });

    window.addEventListener("statechange", stateChangeHandler, false);

    window.addEventListener("popstate", function(e) {
      stateChangeHandler();

      // popstate fires before a hash change, don't fire twice.
      cancelHashChange = true;
    }, false);

    window.addEventListener("load", function(e) {
      if(!triggered) {
        matchRoute(document.location.pathname);
        triggered = true;
      }

      cancelHashChange = true;
      cancelPopstate = true;
    }, false);

    window.addEventListener("hashchange", function(e) {
      if(cancelHashChange) {
        cancelHashChange = false;
        cancelPopstate = false;
        return;
      }
      matchRoute(document.location.pathname);
    }, false);
  };

  attach();
};


text:
package com.intellij.openapi.editor.actions;

import com.intellij.openapi.editor.actionSystem.EditorAction;

public class MoveCaretRightWithSelectionAction extends EditorAction {
  public MoveCaretRightWithSelectionAction() {
    super(new MoveCaretLeftOrRightWithSelectionHandler(true));
  }
}


text:
#ifndef DVPSCU_H
#define DVPSCU_H

#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */
#include "dcmtk/dcmpstat/dvpstyp.h"
#include "dcmtk/ofstd/ofstring.h"
#include "dcmtk/dcmdata/dctypes.h"
#include "dcmtk/dcmdata/dcerror.h"

class DcmItem;

/** the representation of one Curve in a DICOM image.
 */

class DVPSCurve
{
public:
  /// default constructor
  DVPSCurve();

  /// copy constructor
  DVPSCurve(const DVPSCurve& copy);

  /** clone method.
   *  @return a pointer to a new DVPSCurve object containing
   *  a copy of this object.
   */
  DVPSCurve *clone() { return new DVPSCurve(*this); }

  /// destructor
  virtual ~DVPSCurve();

  /** reads a curve from a DICOM dataset.
   *  The DICOM elements of the Graphic Object item are copied
   *  from the dataset to this object.
   *  The completeness of the curve (presence of all required elements,
   *  value multiplicity) is checked.
   *  If this method returns an error code, the object is in undefined state afterwards.
   *  @param dset the DICOM dataset from which the data is to be read
   *  @param group lower byte of the curve repeating group to be read
   *  @return EC_Normal if successful, an error code otherwise.
   */
  OFCondition read(DcmItem &dset, Uint8 group);

  /** get group number of curve repeating group managed by this object.
   *  @return the lower byte of the curve group
   */
  Uint8 getCurveGroup() { return curveGroup; }

  /** gets the number of points in the curve.
   *  @return number of points
   */
  size_t getNumberOfPoints() { return numberOfPoints; }

  /** gets the type of data in the curve (ROI or POLY).
   *  @return type of data in curve
   */
  DVPSCurveType getTypeOfData() { return typeOfData; }

  /** gets one point from the curve data.
   *  @param idx index of the curve point, must be < getNumberOfPoints();
   *  @param x upon success the x value of the point is returned in this parameter
   *  @param y upon success the y value of the point is returned in this parameter
   *  @return EC_Normal if successful, an error code otherwise.
   */
  OFCondition getPoint(size_t idx, double& x, double& y);

  /** gets the curve description string if present.
   *  If the description string is absent, this method returns NULL or an empty string.
   *  @return curve description
   */
  const char *getCurveDescription() { return curveDescription.c_str(); }

  /** gets the curve label string if present.
   *  If the label string is absent, this method returns NULL or an empty string.
   *  @return curve label
   */
  const char *getCurveLabel() { return curveLabel.c_str(); }

  /** gets the curve axis units string for the X dimension if present.
   *  If the string is absent, this method returns NULL or an empty string.
   *  @return curve description
   */
  const char *getCurveAxisUnitsX() { return axisUnitsX.c_str(); }

  /** gets the curve axis units string for the Y dimension if present.
   *  If the string is absent, this method returns NULL or an empty string.
   *  @return curve description
   */
  const char *getCurveAxisUnitsY() { return axisUnitsY.c_str(); }

private:
  /// private undefined assignment operator
  DVPSCurve& operator=(const DVPSCurve&);

  /// lower byte of the curve repeating group managed by this object
  Uint8 curveGroup;
  /// number of points in curve data
  size_t numberOfPoints;
  /// type of curve data
  DVPSCurveType typeOfData;
  /// curve data, converted to double
  double *curveData;
  /// curve data description if present
  OFString curveDescription;
  /// curve label if present
  OFString curveLabel;
  /// axis units X if present
  OFString axisUnitsX;
  /// axis units Y if present
  OFString axisUnitsY;

};

#endif

/*
 *  $Log: dvpscu.h,v $
 *  Revision 1.9  2010-10-14 13:16:36  joergr
 *  Updated copyright header. Added reference to COPYRIGHT file.
 *
 *  Revision 1.8  2010-10-07 14:31:35  joergr
 *  Removed leading underscore characters from preprocessor symbols (reserved).
 *
 *  Revision 1.7  2009-11-24 14:12:57  uli
 *  Switched to logging mechanism provided by the "new" oflog module.
 *
 *  Revision 1.6  2005-12-08 16:03:37  meichel
 *  Changed include path schema for all DCMTK header files
 *
 *  Revision 1.5  2001/09/26 15:36:09  meichel
 *  Adapted dcmpstat to class OFCondition
 *
 *  Revision 1.4  2001/06/01 15:50:13  meichel
 *  Updated copyright header
 *
 *  Revision 1.3  2000/06/02 16:00:44  meichel
 *  Adapted all dcmpstat classes to use OFConsole for log and error output
 *
 *  Revision 1.2  2000/03/08 16:28:50  meichel
 *  Updated copyright header.
 *
 *  Revision 1.1  1998/12/22 17:57:04  meichel
 *  Implemented Presentation State interface for overlays,
 *    VOI LUTs, VOI windows, curves. Added test program that
 *    allows to add curve data to DICOM images.
 *
 *
 */


text:
@interface UIImageView (SGImageCache_Private)
@property (nonatomic,strong) NSString *cachedImageURL;
@end

@implementation UIImageView (SGImageCache_Private)

@dynamic cachedImageURL;

- (void)setCachedImageURL:(NSString*)object {
     objc_setAssociatedObject(self, @selector(cachedImageURL), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString*)cachedImageURL {
    return objc_getAssociatedObject(self, @selector(cachedImageURL));
}

@end

@implementation UIImageView (SGImageCache)

#pragma mark - Setting Images via URL

- (void)setImageForURL:(NSString *)url {
    [self setImageForURL:url placeholder:nil];
}

- (void)setImageForURL:(NSString *)url placeholder:(UIImage *)placeholder {
    [self setImageForURL:url placeholder:placeholder crossFadeDuration:0];
}

- (void)setImageForURL:(NSString*)url
           placeholder:(UIImage*)placeholder
            stillValid:(BOOL(^)(void))stillValid {
    [self setImageForURL:url placeholder:placeholder crossFadeDuration:0 stillValid:stillValid];
}

- (void)setImageForURL:(NSString *)url
           placeholder:(UIImage *)placeholder
     crossFadeDuration:(NSTimeInterval)duration {
    [self setImageForURL:url placeholder:placeholder crossFadeDuration:duration stillValid:nil];
}

- (void)setImageForURL:(NSString *)url
           placeholder:(UIImage *)placeholder
     crossFadeDuration:(NSTimeInterval)duration
            stillValid:(BOOL(^)(void))stillValid {
    __weakSelf me = self;

    self.cachedImageURL = url;

    if ([SGImageCache haveImageForURL:url]) {
        UIImage *image = [SGImageCache imageForURL:url];
        self.image = image;
        [self trigger:SGImageViewImageChanged withContext:image];
    } else {
        if (self.image != placeholder) {
            self.image = placeholder;
            [me trigger:SGImageViewImageChanged withContext:placeholder];
        }
        [SGImageCache getImageForURL:url].then(^(UIImage *image) {
            if (!image) {
                return;
            }
            if (url != me.cachedImageURL) {
              return;
            }
            if (stillValid && !stillValid()) {
                return;
            }
            if (duration > 0 && me.window) {
                [UIView transitionWithView:me.superview
                                  duration:duration
                                   options:UIViewAnimationOptionTransitionCrossDissolve |
                                           UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionAllowUserInteraction
                                animations:^{
                                    me.image = image;
                                    [me trigger:SGImageViewImageChanged withContext:image];
                                } completion:nil];
            } else {
                me.image = image;
                [me trigger:SGImageViewImageChanged withContext:image];
            }
        });
    }
}

#pragma mark - Setting Images via Image name

- (void)setImageWithName:(NSString *)name {
    [self setImageWithName:name crossFadeDuration:0];
}

- (void)setImageWithName:(NSString *)name
       crossFadeDuration:(NSTimeInterval)duration {
    __weakSelf me = self;
    if (duration > 0 && me.window) {
        UIImage *image = [SGImageCache imageNamed:name];
        [UIView transitionWithView:me.superview
                          duration:duration
                           options:UIViewAnimationOptionTransitionCrossDissolve |
                                   UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionAllowUserInteraction
                        animations:^{
                            me.image = image;
                            [me trigger:SGImageViewImageChanged withContext:image];
                        } completion:nil];
    } else {
        UIImage *image = [SGImageCache imageNamed:name];
        self.image = image;
        [self trigger:SGImageViewImageChanged withContext:image];
    }
}

@end

#endif


text:
<?php

// autoload.php generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitac8aa686631fa03ef3cf7f7f96003b95::getLoader();


text:
$( document ).ready( function () {

	$("#bloque").convertirMayuscula();
	$("#observacion").convertirMayuscula();

	$( "#form" ).validate( {
		rules: {
			bloque:				{ required: true, maxlength:150 },
			estado:				{ required: true }
		},
		errorElement: "em",
		errorPlacement: function ( error, element ) {
			// Add the `help-block` class to the error element
			error.addClass( "help-block" );
			error.insertAfter( element );

		},
		highlight: function ( element, errorClass, validClass ) {
			$( element ).parents( ".col-sm-6" ).addClass( "has-error" ).removeClass( "has-success" );
		},
		unhighlight: function (element, errorClass, validClass) {
			$( element ).parents( ".col-sm-6" ).addClass( "has-success" ).removeClass( "has-error" );
		},
		submitHandler: function (form) {
			return true;
		}
	});

	$(".btn-danger").click(function () {
			var oID = $(this).attr("id");

			//Activa icono guardando
			if(window.confirm('Esta seguro de eliminar la Sesión?'))
			{
					$(".btn-danger").attr('disabled','-1');
					$.ajax ({
						type: 'POST',
						url: base_url + 'admin/eliminar_sesiones',
						data: {'identificador': oID},
						cache: false,
						success: function(data){

							if( data.result == "error" )
							{
								alert(data.mensaje);
								$(".btn-danger").removeAttr('disabled');
								return false;
							}

							if( data.result )//true
							{
								$(".btn-danger").removeAttr('disabled');

								var url = base_url + "admin/sesiones/" + data.idRecord;
								$(location).attr("href", url);
							}
							else
							{
								alert('Error. Reload the web page.');
								$(".btn-danger").removeAttr('disabled');
							}
						},
						error: function(result) {
							alert('Error. Reload the web page.');
							$(".btn-danger").removeAttr('disabled');
						}

					});
			}
	});

	$("#btnSubmit").click(function(){

		if ($("#form").valid() == true){

				//Activa icono guardando
				$('#btnSubmit').attr('disabled','-1');
				$("#div_error").css("display", "none");
				$("#div_load").css("display", "inline");

				$.ajax({
					type: "POST",
					url: base_url + "sitios/save_bloques",
					data: $("#form").serialize(),
					dataType: "json",
					contentType: "application/x-www-form-urlencoded;charset=UTF-8",
					cache: false,

					success: function(data){

						if( data.result == "error" )
						{
							$("#div_load").css("display", "none");
							$("#div_error").css("display", "inline");
							$("#span_msj").html(data.mensaje);
							$('#btnSubmit').removeAttr('disabled');
							alert(data.mensaje);
							return false;
						}

						if( data.result )//true
						{
							$("#div_load").css("display", "none");
							$('#btnSubmit').removeAttr('disabled');

							var url = base_url + "sitios/salones" + "/" + data.idRecord;
							$(location).attr("href", url);
						}
						else
						{
							alert('Error. Reload the web page.');
							$("#div_load").css("display", "none");
							$("#div_error").css("display", "inline");
							$('#btnSubmit').removeAttr('disabled');
						}
					},
					error: function(result) {
						alert('Error. Reload the web page.');
						$("#div_load").css("display", "none");
						$("#div_error").css("display", "inline");
						$('#btnSubmit').removeAttr('disabled');
					}

				});

		}//if
	});
});


text:
    #define DEBUG(x) Serial.print(x)
    #define DEBUGLN(x) Serial.println(x)
#else
    #define DEBUG(x)
    #define DEBUGLN(x)
#endif

#ifdef ERROR
    #define ERROR(x) Serial.print(x)
    #define ERRORLN(x) Serial.println(x)
#else
    #define ERROR(x)
    #define ERRORLN(x)
#endif

class ESP8266_Wifi {
public:
    static const int MODE_STA = 1;
    static const int MODE_AP = 2;
    static const int MODE_BOTH = 2;

    ESP8266_Wifi();
    void init();
    boolean connect(String ssid, String password);
    boolean get(String url, String &result);
    boolean get(String url, String &result, boolean fullResponse);

    void debugSerial(SoftwareSerial * serial);
    boolean reset();
    int getMode();
    void setMode(int mode);

private:
    SoftwareSerial * out;
    long timeout;
    String lineBuffer;

    void send(String data);
    void flush();
    boolean waitFor(char * waitFor);
    boolean waitFor(char * waitFor, String &returnValue);
    boolean waitFor(char * waitFor, String &returnValue, long timeout, boolean terminateImmediately);
    void handleCharacter(char c);
    void flushESPBuffer();
    boolean stringContains(String needle, String haystack);
    boolean parseUrl(String url,String &protocol,String &host,String &path,String &params);
    boolean start(String protocol, String ip, int port);
    boolean sendPayload(String get);
    boolean close();
};

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
using Mono.CSharp;
using Saltarelle.Compiler.Compiler;
using Saltarelle.Compiler.JSModel;
using Saltarelle.Compiler.JSModel.Minification;
using Saltarelle.Compiler.JSModel.Statements;
using Saltarelle.Compiler.OOPEmulation;
using TopologicalSort;

namespace Saltarelle.Compiler.Driver {
	public class CompilerDriver {
		private class Resource : IAssemblyResource {
			public string Name { get; private set; }
			public AssemblyResourceType Type { get { return AssemblyResourceType.Embedded; } }
			public string LinkedFileName { get { return null; } }
			public bool IsPublic { get; private set; }
			private readonly string _filename;

			public Stream GetResourceStream() {
				return File.OpenRead(_filename);
			}

			public Resource(string name, string filename, bool isPublic) {
				Name      = name;
				_filename = filename;
				IsPublic  = isPublic;
			}
		}

		private readonly IErrorReporter _errorReporter;

		private static string GetAssemblyName(CompilerOptions options) {
			if (options.OutputAssemblyPath != null)
				return Path.GetFileNameWithoutExtension(options.OutputAssemblyPath);
			else if (options.SourceFiles.Count > 0)
				return Path.GetFileNameWithoutExtension(options.SourceFiles[0]);
			else
				return null;
		}

		private static string ResolveReference(string filename, IEnumerable<string> paths, IErrorReporter er) {
			// Code taken from mcs, so it should match that behavior.
			bool? hasExtension = null;
			foreach (var path in paths) {
				var file = Path.Combine(path, filename);

				if (!File.Exists(file)) {
					if (!hasExtension.HasValue)
						hasExtension = filename.EndsWith(".dll", StringComparison.Ordinal) || filename.EndsWith(".exe", StringComparison.Ordinal);

					if (hasExtension.Value)
						continue;

					file += ".dll";
					if (!File.Exists(file))
						continue;
				}

				return Path.GetFullPath(file);
			}
			er.Region = DomRegion.Empty;
			er.Message(Messages._7997, filename);
			return null;
		}

		private static CompilerSettings MapSettings(CompilerOptions options, string outputAssemblyPath, string outputDocFilePath, IErrorReporter er) {
			var allPaths = options.AdditionalLibPaths.Concat(new[] { Environment.CurrentDirectory }).ToList();

			var result = new CompilerSettings {
				Target                    = (options.HasEntryPoint ? Target.Exe : Target.Library),
				Platform                  = Platform.AnyCPU,
				TargetExt                 = (options.HasEntryPoint ? ".exe" : ".dll"),
				MainClass                 = options.EntryPointClass,
				VerifyClsCompliance       = false,
				Optimize                  = false,
				Version                   = LanguageVersion.V_5,
				EnhancedWarnings          = false,
				LoadDefaultReferences     = false,
				TabSize                   = 1,
				WarningsAreErrors         = options.TreatWarningsAsErrors,
				FatalCounter              = 100,
				WarningLevel              = options.WarningLevel,
				Encoding                  = Encoding.UTF8,
				DocumentationFile         = !string.IsNullOrEmpty(options.DocumentationFile) ? outputDocFilePath : null,
				OutputFile                = outputAssemblyPath,
				AssemblyName              = GetAssemblyName(options),
				StdLib                    = false,
				StdLibRuntimeVersion      = RuntimeVersion.v4,
				StrongNameKeyContainer    = options.KeyContainer,
				StrongNameKeyFile         = options.KeyFile,
			};
			result.SourceFiles.AddRange(options.SourceFiles.Select((f, i) => new SourceFile(f, f, i + 1)));
			foreach (var r in options.References) {
				string resolvedPath = ResolveReference(r.Filename, allPaths, er);
				if (r.Alias == null)
					result.AssemblyReferences.Add(resolvedPath);
				else
					result.AssemblyReferencesAliases.Add(Tuple.Create(r.Alias, resolvedPath));
			}
			foreach (var c in options.DefineConstants)
				result.AddConditionalSymbol(c);
			foreach (var w in options.DisabledWarnings)
				result.SetIgnoreWarning(w);
			foreach (var w in options.WarningsAsErrors)
				result.AddWarningAsError(w);
			foreach (var w in options.WarningsNotAsErrors)
				result.AddWarningOnly(w);
			if (options.EmbeddedResources.Count > 0)
				result.Resources = options.EmbeddedResources.Select(r => new AssemblyResource(r.Filename, r.ResourceName, isPrivate: !r.IsPublic) { IsEmbeded = true }).ToList();

			if (result.AssemblyReferencesAliases.Count > 0) {	// NRefactory does currently not support reference aliases, this check will hopefully go away in the future.
				er.Region = DomRegion.Empty;
				er.Message(Messages._7998, "aliased reference");
			}

			return result;
		}

		private class ConvertingReportPrinter : ReportPrinter {
			private readonly IErrorReporter _errorReporter;

			public ConvertingReportPrinter(IErrorReporter errorReporter) {
				_errorReporter = errorReporter;
			}

			public override void Print(AbstractMessage msg, bool showFullPath) {
				base.Print(msg, showFullPath);
				_errorReporter.Region = new DomRegion(msg.Location.NameFullPath, msg.Location.Row, msg.Location.Column, msg.Location.Row, msg.Location.Column);
				_errorReporter.Message(msg.IsWarning ? MessageSeverity.Warning : MessageSeverity.Error, msg.Code, msg.Text.Replace("{", "{{").Replace("}", "}}"));
			}
		}

		private class SimpleSourceFile : ISourceFile {
			private readonly Encoding _encoding;
			private readonly string _filename;

			public SimpleSourceFile(string filename, Encoding encoding) {
				_filename = filename;
				_encoding = encoding;
			}

			public string Filename {
				get { return _filename; }
			}

			public TextReader Open() {
				return new StreamReader(Filename, _encoding);
			}
		}

		public class ErrorReporterWrapper : IErrorReporter {
			private readonly IErrorReporter _er;
			private readonly TextWriter _actualConsoleOut;

			public bool HasErrors { get; private set; }

			public ErrorReporterWrapper(IErrorReporter er, TextWriter actualConsoleOut) {
				_er = er;
				_actualConsoleOut = actualConsoleOut;
			}

			private void WithActualOut(Action a) {
				TextWriter old = Console.Out;
				try {
					Console.SetOut(_actualConsoleOut);
					a();
				}
				finally {
					Console.SetOut(old);
				}
			}

			public DomRegion Region {
				get { return _er.Region; }
				set { _er.Region = value; }
			}

			public void Message(MessageSeverity severity, int code, string message, params object[] args) {
				WithActualOut(() => _er.Message(severity, code, message, args));
				if (severity == MessageSeverity.Error)
					HasErrors = true;
			}

			public void InternalError(string text) {
				WithActualOut(() => _er.InternalError(text));
				HasErrors = true;
			}

			public void InternalError(Exception ex, string additionalText = null) {
				WithActualOut(() => _er.InternalError(ex, additionalText));
				HasErrors = true;
			}
		}

		public CompilerDriver(IErrorReporter errorReporter) {
			_errorReporter = errorReporter;
		}

		private bool IsEntryPointCandidate(IMethod m) {
			if (m.Name != "Main" || !m.IsStatic || m.DeclaringTypeDefinition.TypeParameterCount > 0 || m.TypeParameters.Count > 0)	// Must be a static, non-generic Main
				return false;
			if (!m.ReturnType.IsKnownType(KnownTypeCode.Void) && !m.ReturnType.IsKnownType(KnownTypeCode.Int32))	// Must return void or int.
				return false;
			if (m.Parameters.Count == 0)	// Can have 0 parameters.
				return true;
			if (m.Parameters.Count > 1)	// May not have more than 1 parameter.
				return false;
			if (m.Parameters[0].IsRef || m.Parameters[0].IsOut)	// The single parameter must not be ref or out.
				return false;

			var at = m.Parameters[0].Type as ArrayType;
			return at != null && at.Dimensions == 1 && at.ElementType.IsKnownType(KnownTypeCode.String);	// The single parameter must be a one-dimensional array of strings.
		}

		private static IEnumerable<System.Reflection.Assembly> TopologicalSortPlugins(IList<Tuple<IUnresolvedAssembly, IList<string>, System.Reflection.Assembly>> references) {
			return TopologicalSorter.TopologicalSort(references, r => r.Item1.AssemblyName, references.SelectMany(a => a.Item2, (a, r) => Edge.Create(a.Item1.AssemblyName, r)))
			                        .Select(r => r.Item3)
			                        .Where(a => a != null);
		}

		private static readonly Type[] _pluginTypes = new[] { typeof(IJSTypeSystemRewriter), typeof(IMetadataImporter), typeof(IRuntimeLibrary), typeof(IOOPEmulator), typeof(ILinker), typeof(INamer) };

		private static void RegisterPlugin(IWindsorContainer container, System.Reflection.Assembly plugin) {
			container.Register(AllTypes.FromAssembly(plugin).Where(t => _pluginTypes.Any(pt => pt.IsAssignableFrom(t))).WithServiceSelect((t, _) => t.GetInterfaces().Intersect(_pluginTypes)));
		}

		private static IEnumerable<IAssemblyResource> LoadResources(IEnumerable<EmbeddedResource> resources) {
			return resources.Select(r => new Resource(r.ResourceName, r.Filename, r.IsPublic));
		}

		public bool Compile(CompilerOptions options) {
			string intermediateAssemblyFile = Path.GetTempFileName(), intermediateDocFile = Path.GetTempFileName();
			var actualOut = Console.Out;
			var er = new ErrorReporterWrapper(_errorReporter, actualOut);
			try {
				Console.SetOut(new StringWriter());	// I don't trust the third-party libs to not generate spurious random messages, so make sure that any of those messages are suppressed.

				var settings = MapSettings(options, intermediateAssemblyFile, intermediateDocFile, er);
				if (er.HasErrors)
					return false;

				if (!options.AlreadyCompiled) {
					// Compile the assembly
					var ctx = new CompilerContext(settings, new ConvertingReportPrinter(er));
					var d = new Mono.CSharp.Driver(ctx);
					d.Compile();
					if (er.HasErrors)
						return false;
				}

				var references = LoadReferences(settings.AssemblyReferences, er);
				if (references == null)
					return false;

				PreparedCompilation compilation = PreparedCompilation.CreateCompilation(settings.AssemblyName, options.SourceFiles.Select(f => new SimpleSourceFile(f, settings.Encoding)), references.Select(r => r.Item1), options.DefineConstants, LoadResources(options.EmbeddedResources));

				IMethod entryPoint = FindEntryPoint(options, er, compilation);

				var container = new WindsorContainer();
				foreach (var plugin in TopologicalSortPlugins(references).Reverse())
					RegisterPlugin(container, plugin);

				container.Register(Component.For<IErrorReporter>().Instance(er),
				                   Component.For<CompilerOptions>().Instance(options),
				                   Component.For<ICompilation>().Instance(compilation.Compilation),
				                   Component.For<ICompiler>().ImplementedBy<Compiler.Compiler>()
				                  );

				container.Resolve<IMetadataImporter>().Prepare(compilation.Compilation.GetAllTypeDefinitions());

				var compiledTypes = container.Resolve<ICompiler>().Compile(compilation);

				foreach (var rewriter in container.ResolveAll<IJSTypeSystemRewriter>())
					compiledTypes = rewriter.Rewrite(compiledTypes);

				var invoker = new OOPEmulatorInvoker(container.Resolve<IOOPEmulator>(), container.Resolve<IMetadataImporter>(), container.Resolve<IErrorReporter>());

				var js = invoker.Process(compiledTypes.ToList(), entryPoint);
				js = container.Resolve<ILinker>().Process(js);

				if (er.HasErrors)
					return false;

				string outputAssemblyPath = !string.IsNullOrEmpty(options.OutputAssemblyPath) ? options.OutputAssemblyPath : Path.ChangeExtension(options.SourceFiles[0], ".dll");
				string outputScriptPath   = !string.IsNullOrEmpty(options.OutputScriptPath)   ? options.OutputScriptPath   : Path.ChangeExtension(options.SourceFiles[0], ".js");

				if (!options.AlreadyCompiled) {
					try {
						File.Copy(intermediateAssemblyFile, outputAssemblyPath, true);
					}
					catch (IOException ex) {
						er.Region = DomRegion.Empty;
						er.Message(Messages._7950, ex.Message);
						return false;
					}
					if (!string.IsNullOrEmpty(options.DocumentationFile)) {
						try {
							File.Copy(intermediateDocFile, options.DocumentationFile, true);
						}
						catch (IOException ex) {
							er.Region = DomRegion.Empty;
							er.Message(Messages._7952, ex.Message);
							return false;
						}
					}
				}

				if (options.MinimizeScript) {
					js = ((JsBlockStatement)Minifier.Process(JsStatement.Block(js))).Statements;
				}

				string script = options.MinimizeScript ? OutputFormatter.FormatMinified(js) : OutputFormatter.Format(js);
				try {
					File.WriteAllText(outputScriptPath, script, settings.Encoding);
				}
				catch (IOException ex) {
					er.Region = DomRegion.Empty;
					er.Message(Messages._7951, ex.Message);
					return false;
				}
				return true;
			}
			catch (Exception ex) {
				er.Region = DomRegion.Empty;
				er.InternalError(ex.ToString());
				return false;
			}
			finally {
				if (!options.AlreadyCompiled) {
					try { File.Delete(intermediateAssemblyFile); } catch {}
					try { File.Delete(intermediateDocFile); } catch {}
				}
				if (actualOut != null) {
					Console.SetOut(actualOut);
				}
			}
		}

		private IMethod FindEntryPoint(CompilerOptions options, ErrorReporterWrapper er, PreparedCompilation compilation) {
			if (options.HasEntryPoint) {
				List<IMethod> candidates;
				if (!string.IsNullOrEmpty(options.EntryPointClass)) {
					var t = compilation.Compilation.MainAssembly.GetTypeDefinition(new FullTypeName(options.EntryPointClass));
					if (t == null) {
						er.Region = DomRegion.Empty;
						er.Message(Messages._7950, "Could not find the entry point class " + options.EntryPointClass + ".");
						return null;
					}
					candidates = t.Methods.Where(IsEntryPointCandidate).ToList();
				}
				else {
					candidates =
						compilation.Compilation.MainAssembly.GetAllTypeDefinitions()
						           .SelectMany(t => t.Methods)
						           .Where(IsEntryPointCandidate)
						           .ToList();
				}
				if (candidates.Count != 1) {
					er.Region = DomRegion.Empty;
					er.Message(Messages._7950, "Could not find a unique entry point.");
					return null;
				}
				return candidates[0];
			}

			return null;
		}

		private static System.Reflection.Assembly LoadPlugin(IKVM.Reflection.Assembly asm) {
			foreach (var name in asm.GetManifestResourceNames()) {
				if (name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) {
					using (var strm = asm.GetManifestResourceStream(name))
					using (var ms = new MemoryStream())
					using (var uni = new IKVM.Reflection.Universe()) {
						strm.CopyTo(ms);
						ms.Position = 0;
						string referenceName = uni.LoadAssembly(uni.OpenRawModule(ms, name)).GetName().Name;
						var result = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == referenceName);
						if (result == null)
							result = System.Reflection.Assembly.Load(ms.ToArray());
						return result;
					}
				}
			}

			return null;
		}

		private static IEnumerable<string> GetReferencedAssemblyNames(IKVM.Reflection.Assembly asm) {
			return asm.GetReferencedAssemblies().Select(r => r.Name);
		}

		private static IList<Tuple<IUnresolvedAssembly, IList<string>, System.Reflection.Assembly>> LoadReferences(IEnumerable<string> references, IErrorReporter er) {
			using (var universe = new IKVM.Reflection.Universe(IKVM.Reflection.UniverseOptions.DisablePseudoCustomAttributeRetrieval | IKVM.Reflection.UniverseOptions.SupressReferenceTypeIdentityConversion)) {
				var assemblies = references.Select(universe.LoadFile).ToList();
				var indirectReferences = assemblies.SelectMany(GetReferencedAssemblyNames).Distinct();
				var directReferences = from a in assemblies select a.GetName().Name;
				var missingReferences = indirectReferences.Except(directReferences).ToList();

				if (missingReferences.Count > 0) {
					er.Region = DomRegion.Empty;
					foreach (var r in missingReferences)
						er.Message(Messages._7996, r);
					return null;
				}

				return assemblies.Select(asm => Tuple.Create(new IkvmLoader { IncludeInternalMembers = true }.LoadAssembly(asm), (IList<string>)GetReferencedAssemblyNames(asm).ToList(), LoadPlugin(asm))).ToList();
			}
		}
	}
}


text:
function gpio() {
	var request = new XMLHttpRequest();
	request.open('GET','read.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp0").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp0").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp0").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp0").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(2) == "1") {
				document.getElementById("gp1").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp1").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp1").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp1").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(4) == "1") {
				document.getElementById("gp2").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp2").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp2").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp2").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(6) == "1") {
				document.getElementById("gp3").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp3").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp3").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp3").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(8) == "1") {
				document.getElementById("gp4").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp4").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp4").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp4").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(10) == "1") {
				document.getElementById("gp5").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp5").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp5").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp5").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(12) == "1") {
				document.getElementById("gp6").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp6").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp6").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp6").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(14) == "1") {
				document.getElementById("gp7").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp7").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp7").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp7").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(16) == "1") {
				document.getElementById("gp21").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp21").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp21").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp21").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(18) == "1") {
				document.getElementById("gp22").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp22").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp22").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp22").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(20) == "1") {
				document.getElementById("gp23").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp23").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp23").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp23").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(22) == "1") {
				document.getElementById("gp24").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp24").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp24").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp24").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(24) == "1") {
				document.getElementById("gp25").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp25").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp25").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp25").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(26) == "1") {
				document.getElementById("gp26").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp26").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp26").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp26").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(28) == "1") {
				document.getElementById("gp27").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp27").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp27").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp27").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(30) == "1") {
				document.getElementById("gp28").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp28").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp28").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp28").innerHTML = "Turn ON";
			}

			if (request.responseText.charAt(32) == "1") {
				document.getElementById("gp29").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp29").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp29").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp29").innerHTML = "Turn ON";
			}

		}
	}
	request.send();
};

function storage(){
	var request = new XMLHttpRequest();
	request.open('GET', 'storage.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			var str = request.responseText.split(" ");
			document.getElementById("storage").innerHTML = Math.round((parseInt(str[12]) / 1024) *100)/100 + "/" + Math.round((parseInt(str[10]) / 1024) *100)/100 + " GB";
		}
	}
	request.send();
}

function ram(){
	var request = new XMLHttpRequest();
	request.open('GET', 'ram.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			var str = request.responseText.split(" ");
			document.getElementById("ram").innerHTML = str[19] + "/" + str[11] + " MB";
		}
	}
	request.send();
}

function cpu_usage(){
	var request = new XMLHttpRequest();
	request.open('GET', 'cpu_usage.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			var str = request.responseText.split(" ");
			document.getElementById("cpu").innerHTML = str[11].split(",")[0].split(".")[1] + " %";
		}
	}
	request.send();
}

function dashboard(){
	var request = new XMLHttpRequest();
	request.open('GET','dashboard.txt');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			document.getElementById("dashh").setAttribute("class", "active");
			document.getElementById("generalIO").setAttribute("class", "")
			document.getElementById("navTitle").innerHTML = "  Dashboard";
			document.getElementById("contt").innerHTML = request.responseText;
			storage();
			ram();
			cpu_usage();
		}
	}
	request.send();
};

function generalIO(){
	var request = new XMLHttpRequest();
	request.open('GET','generalIO.txt');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			document.getElementById("dashh").setAttribute("class", "");
			document.getElementById("generalIO").setAttribute("class", "active")
			document.getElementById("navTitle").innerHTML = "  GPIO";
			document.getElementById("contt").innerHTML = request.responseText;
			gpio();
		}
	}
	request.send();

};

document.onload = dashboard();

function gp0(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run0.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp0").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp0").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp0").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp0").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};

function gp1(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run1.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp1").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp1").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp1").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp1").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp2(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run2.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp2").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp2").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp2").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp2").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp3(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run3.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp3").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp3").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp3").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp3").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp4(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run4.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp4").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp4").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp4").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp4").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp5(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run5.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp5").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp5").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp5").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp5").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp6(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run6.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp6").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp6").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp6").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp6").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp7(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run7.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp7").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp7").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp7").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp7").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp21(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run21.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp21").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp21").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp21").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp21").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp22(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run22.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp22").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp22").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp22").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp22").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp23(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run23.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp23").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp23").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp23").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp23").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp24(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run24.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp24").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp24").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp24").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp24").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp25(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run25.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp25").setAttribute("class", "btn btn-success pull-right");
				document.getElementById("gp25").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp25").setAttribute("class", "btn btn-danger pull-right");
				document.getElementById("gp25").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp26(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run26.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp26").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp26").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp26").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp26").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp27(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run27.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp27").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp27").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp27").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp27").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp28(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run28.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp28").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp28").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp28").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp28").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};
function gp29(){
	var request = new XMLHttpRequest();
	request.open('GET','switches/run29.php');
	request.onreadystatechange = function() {
		if((request.status === 200) && (request.readyState === 4)) {
			console.log(request);
			if (request.responseText.charAt(0) == "1") {
				document.getElementById("gp29").setAttribute("class", "btn btn-success pull-left");
				document.getElementById("gp29").innerHTML = "Turn OFF";
			}
			else {
				document.getElementById("gp29").setAttribute("class", "btn btn-danger pull-left");
				document.getElementById("gp29").innerHTML = "Turn ON";
			}
		}
	}
	request.send();
};


text:
namespace foundation    { class IAbortSwitch; }
namespace renderer      { class Assembly; }
namespace renderer      { class Project; }

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // Cone-shaped EDF.
    //

    const char* Model = "cone_edf";

    class ConeEDF
      : public EDF
    {
      public:
        ConeEDF(
            const char*             name,
            const ParamArray&       params)
          : EDF(name, params)
        {
            m_inputs.declare("radiance", InputFormatSpectralIlluminance);
            m_inputs.declare("radiance_multiplier", InputFormatFloat, "1.0");
            m_inputs.declare("angle", InputFormatFloat, "90.0");
        }

        virtual void release() APPLESEED_OVERRIDE
        {
            delete this;
        }

        virtual const char* get_model() const APPLESEED_OVERRIDE
        {
            return Model;
        }

        virtual bool on_frame_begin(
            const Project&          project,
            const BaseGroup*        parent,
            OnFrameBeginRecorder&   recorder,
            IAbortSwitch*           abort_switch) APPLESEED_OVERRIDE
        {
            if (!EDF::on_frame_begin(project, parent, recorder, abort_switch))
                return false;

            check_non_zero_emission("radiance", "radiance_multiplier");

            m_cos_half_angle = cos(deg_to_rad(m_params.get_required<float>("angle", 90.0f) / 2.0f));

            return true;
        }

        virtual void sample(
            SamplingContext&        sampling_context,
            const void*             data,
            const Vector3f&         geometric_normal,
            const Basis3f&          shading_basis,
            const Vector2f&         s,
            Vector3f&               outgoing,
            Spectrum&               value,
            float&                  probability) const APPLESEED_OVERRIDE
        {
            assert(is_normalized(geometric_normal));

            const Vector3f wo = sample_cone_uniform(s, m_cos_half_angle);
            outgoing = shading_basis.transform_to_parent(wo);

            const InputValues* values = static_cast<const InputValues*>(data);
            value = values->m_radiance;
            value *= values->m_radiance_multiplier;

            probability = sample_cone_uniform_pdf(m_cos_half_angle);
            assert(probability > 0.0f);
        }

        virtual void evaluate(
            const void*             data,
            const Vector3f&         geometric_normal,
            const Basis3f&          shading_basis,
            const Vector3f&         outgoing,
            Spectrum&               value) const APPLESEED_OVERRIDE
        {
            assert(is_normalized(geometric_normal));
            assert(is_normalized(outgoing));

            // No emission outside the cone.
            const float cos_on = dot(outgoing, shading_basis.get_normal());
            if (cos_on <= m_cos_half_angle)
            {
                value.set(0.0f);
                return;
            }

            const InputValues* values = static_cast<const InputValues*>(data);
            value = values->m_radiance;
            value *= values->m_radiance_multiplier;
        }

        virtual void evaluate(
            const void*             data,
            const Vector3f&         geometric_normal,
            const Basis3f&          shading_basis,
            const Vector3f&         outgoing,
            Spectrum&               value,
            float&                  probability) const APPLESEED_OVERRIDE
        {
            assert(is_normalized(geometric_normal));
            assert(is_normalized(outgoing));

            // No emission outside the cone.
            const float cos_on = dot(outgoing, shading_basis.get_normal());
            if (cos_on <= m_cos_half_angle)
            {
                value.set(0.0f);
                probability = 0.0f;
                return;
            }

            const InputValues* values = static_cast<const InputValues*>(data);
            value = values->m_radiance;
            value *= values->m_radiance_multiplier;

            probability = sample_cone_uniform_pdf(m_cos_half_angle);
        }

        virtual float evaluate_pdf(
            const void*             data,
            const Vector3f&         geometric_normal,
            const Basis3f&          shading_basis,
            const Vector3f&         outgoing) const APPLESEED_OVERRIDE
        {
            assert(is_normalized(geometric_normal));
            assert(is_normalized(outgoing));

            // No emission outside the cone.
            const float cos_on = dot(outgoing, shading_basis.get_normal());
            if (cos_on <= m_cos_half_angle)
                return 0.0f;

            return sample_cone_uniform_pdf(m_cos_half_angle);
        }

      private:
        typedef ConeEDFInputValues InputValues;

        float m_cos_half_angle;
    };
}

//
// ConeEDFFactory class implementation.
//

const char* ConeEDFFactory::get_model() const
{
    return Model;
}

Dictionary ConeEDFFactory::get_model_metadata() const
{
    return
        Dictionary()
            .insert("name", Model)
            .insert("label", "Cone EDF");
}

DictionaryArray ConeEDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "radiance")
            .insert("label", "Radiance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "radiance_multiplier")
            .insert("label", "Radiance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "angle")
            .insert("label", "Angle")
            .insert("type", "numeric")
            .insert("min_value", "-360.0")
            .insert("max_value", "360.0")
            .insert("use", "required")
            .insert("default", "90.0"));

    add_common_input_metadata(metadata);

    return metadata;
}

auto_release_ptr<EDF> ConeEDFFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return auto_release_ptr<EDF>(new ConeEDF(name, params));
}

auto_release_ptr<EDF> ConeEDFFactory::static_create(
    const char*         name,
    const ParamArray&   params)
{
    return auto_release_ptr<EDF>(new ConeEDF(name, params));
}

}   // namespace renderer


text:
package org.andengine.opengl.vbo;

import java.nio.FloatBuffer;

import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes;

import android.opengl.GLES20;

/**
 * Compared to a {@link HighPerformanceVertexBufferObject}, the {@link LowMemoryVertexBufferObject} uses 50% less heap memory,
 * at the cost of significantly slower data buffering (up to 5x slower!).
 *
 * Usually a {@link LowMemoryVertexBufferObject} is preferred to a {@link HighPerformanceVertexBufferObject} when the following conditions are met:
 *

 *
The applications is close to run out of memory.

 *
You have very big {@link HighPerformanceVertexBufferObject} or an extreme number of small {@link HighPerformanceVertexBufferObject}s, where a 50% heap memory reduction would actually be significant.

 *
The content (color, vertices, texturecoordinates) of the {@link LowMemoryVertexBufferObject} is changed not often, or even better: never.

 *

 *
 * (c) Zynga 2011
 *
 * @author Nicolas Gramlich <ngramlich@zynga.com>
 * @since 14:42:18 - 15.11.2011
 */
public class LowMemoryVertexBufferObject extends VertexBufferObject {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	protected final FloatBuffer mFloatBuffer;

	// ===========================================================
	// Constructors
	// ===========================================================

	public LowMemoryVertexBufferObject(final VertexBufferObjectManager pVertexBufferObjectManager, final int pCapacity, final DrawType pDrawType, final boolean pAutoDispose, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) {
		super(pVertexBufferObjectManager, pCapacity, pDrawType, pAutoDispose, pVertexBufferObjectAttributes);

		this.mFloatBuffer = this.mByteBuffer.asFloatBuffer();
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public FloatBuffer getFloatBuffer() {
		return this.mFloatBuffer;
	}

	@Override
	public int getHeapMemoryByteSize() {
		return 0;
	}

	@Override
	public int getNativeHeapMemoryByteSize() {
		return this.getByteCapacity();
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	protected void onBufferData() {
		GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, this.mByteBuffer.limit(), this.mByteBuffer, this.mUsage);
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
import { TextureLoader } from 'three/src/loaders/TextureLoader';
import { JSONLoader } from 'three/src/loaders/JSONLoader';

export class AssetError {
  constructor(error, path) {
    this.error = error;
    this.path = path;
    this.stack = (new Error()).stack;
  }

  toString() {
    return `Error loading '${this.path}': ${this.error}.`;
  }
}

export class Asset {
  constructor(path) {
    this.path = path;
  }
}

export class ModelAsset extends Asset {
  constructor(path, geometry, material) {
    super(path);
    this.geometry = geometry;
    this.material = material;
  }
}

export class TextureAsset extends Asset {
  constructor(path, texture) {
    super(path);
    this.texture = texture;
    this.texture.anisotropy = 4;
  }
}

export class Loader {
  constructor(root) {
    this.root = root || '';
    this.textureLoader = new TextureLoader();
    this.jsonLoader = new JSONLoader();
    this.cache = {};
    this.typeToMethod = {
      'texture': this.loadTexture,
      'json/model': this.loadModelJSON
    }
  }

  getAsset(path) {
    return this.cache[path];
  }

  loadAssets(assetList, onComplete, onProgress, onError) {
    let loaded = 0;
    let failed = 0;
    let errors = [];
    let total = assetList.length;

    let checkProgress = function(path, asset, error) {
      if(onProgress != null) {
        onProgress(loaded, failed, total, path, asset, error);
      }
      if(loaded + failed == total && onComplete != null) {
        onComplete(errors, total, loaded, failed);
      }
    }

    let loadCb = function(asset) {
      loaded++;
      checkProgress(asset.path, asset, null);
    };

    let errorCb = function(error, path) {
      failed++;
      let err = new AssetError(error, path);
      errors.push(err);
      onError(err);
      checkProgress(path, null, error);
    }

    for(let item of assetList) {
      let {path, type} = item;
      let method = this.typeToMethod[type];
      if(method == null) {
        errorCb(`Unsupported type '${type}'`, path);
      } else {
        method.call(this, path, loadCb, errorCb);
      }
    }
  }

  loadModelJSON(path, loadCb, errorCb) {
    if(this.cache[path] != null) { return this.cache[path]; }
    this.jsonLoader.load(this.resolvePath(path), (geometry, material) => {
      let asset = this.cache[path] = new ModelAsset(path, geometry, material);
      loadCb(asset);
    }, undefined, (error) => { errorCb(error, path); });
  }

  loadTexture(path, loadCb, errorCb) {
    if(this.cache[path] != null) { return this.cache[path]; }
    this.textureLoader.load(this.resolvePath(path), (texture) => {
      let asset = this.cache[path] = new TextureAsset(path, texture);
      loadCb(asset);
    }, undefined, (error) => { errorCb(error, path); });
  }

  resolvePath(path) {
    if(path[0] === '/') {
      path = this.root + path;
    }
    return path;
  }
}


text:
import React from 'react'
import { Radio, Segment } from 'semantic-ui-react'

const RadioExampleFitted = () => (
  <div>
    <Segment compact>
      <Radio />
    </Segment>
    <Segment compact>
      <Radio slider />
    </Segment>
    <Segment compact>
      <Radio toggle />
    </Segment>
  </div>
)

export default RadioExampleFitted


text:
class Hexpress
  def starting(value = nil)
    add_value(Value::Starting, value)
  end
  alias_method :begins, :starting
  alias_method :begin, :starting
  alias_method :start, :starting

  module Value
    class Starting
      include Value

      def initialize(value = nil)
        @value = value
      end

      def to_s
        "^#{value}"
      end
    end
  end
end


text:
const http = require('http');

const sourceUrl = 'http://nodejs.org/dist/';
const pattern = /v(\d+\.\d+\.\d+)\//;

function getRegexGroup(re, n) {
  n = n || 1;
  return function (line) {
    const match = re.exec(line);
    if (!match) return null;
    return match[n];
  };
}

function versionSort(a, b) {
  const $ = parseInt;
  const aParts = a.split('.');
  const bParts = b.split('.');
  for (var i = 0; i < aParts.length; i++) {
    if ($(aParts[i]) > $(bParts[i])) return -1;
    if ($(aParts[i]) < $(bParts[i])) return 1;
  }
  return 0;
}

function getVersions(callback) {
  http.get(sourceUrl, function (res) {
    var body = '';
    res.on('data', function (chunk) { body += chunk; });

    res.on('end', function () {
      const versions = body
        .trim().split('\r\n')
        .filter(pattern.test.bind(pattern))
        .map(getRegexGroup(pattern))
        .sort(versionSort);
      return callback(versions);
    });
  });
}

module.exports = getVersions;


text:
class Sorter :

	# Initialize self.__attribute .  It will be abused later.
	def __init__ (self) :
		self.__attribute = None

	# Notice how __compare is dependant upon self.__attribute
	def __compare (self, x, y) :
		return cmp(x[self.__attribute], y[self.__attribute])

	# Pass the sort function the __compare function defined above.
	def __call__ (self, data, attribute = None) :
		if attribute == None :
			data.sort()

		else :
			self.__attribute = attribute
			data.sort(self.__compare)

			# This is useful if you want to inline things.
			# I don't know how much innefficiency it introduces.
			# Is this just a new reference?  (that would be cool.)
			return data

# Instanciate the Sorter class once in the module.
# All calls will subsequently abuse this instance.
sort = Sorter()

if __name__ == '__main__' :

	list = [(1, 2), (4, 8), (0, 3)]
	dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0}, {'a': 9, 'b': 9}]
	dumb = [1, 4, 6, 7, 2, 5, 9, 2, 4, 6]

	print

	print 'list normal:', list
	sort(list, 0)
	print 'sort by [0]:', list
	sort(list, 1)
	print 'sort by [1]:', list

	print
	print

	print "dict normal:", dict
	sort(dict, 'a')
	print "sort by 'a':",  dict
	sort(dict, 'b')
	print "sort by 'b':",  dict

	print
	print

	print 'dumb normal:', dumb
	sort(dumb)
	print 'normal sort:', dumb

	print


text:
+++
title = "Note on Jul 29 EDT 2014 at 12:5"
publishdate = 2014-07-29T16:05:11+00:00
draft = false
syndicated = [ 'https://twitter.com/chrisjohndeluca/status/494151662836006900?s=20' ]
+++

I'm pretty sure this is a serious link. It's someone arguing that the Beatles were Astronauts. http://t.co/k4tQfTnvj4 #Beatles #Conspiracy


text:
package org.schoellerfamily.geoservice.keys;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.schoellerfamily.geoservice.exception.GeoCodeRuntimeException;

/**
 * @author Dick Schoeller
 */
public final class KeyManagerImpl implements KeyManager {
    /** */
    private final String fileName;

    /** */
    private String geocodingKey;

    /** */
    private String mapKey;

    /**
     * Constructor.
     *
     * @param fileName the name of the file to read.
     */
    public KeyManagerImpl(final String fileName) {
        this.fileName = fileName;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getGeocodingKey() {
        if (geocodingKey != null) {
            return geocodingKey;
        }
        try (FileInputStream fileStream = new FileInputStream(fileName);
                InputStreamReader iStreamReader =
                        new InputStreamReader(fileStream, "UTF-8");
                BufferedReader br = new BufferedReader(iStreamReader);) {
            final StringBuilder sb = new StringBuilder();
            final String line = br.readLine();
            if (line != null) {
                sb.append(line.replace("\n", ""));
            }
            geocodingKey = sb.toString();
            return geocodingKey;
        } catch (IOException e) {
            throw new GeoCodeRuntimeException(
                    "Couldn't open key file: " + fileName, e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getMapsKey() {
        if (mapKey != null) {
            return mapKey;
        }
        try (FileInputStream fileStream = new FileInputStream(fileName);
                InputStreamReader iStreamReader =
                        new InputStreamReader(fileStream, "UTF-8");
                BufferedReader br = new BufferedReader(iStreamReader);) {
            final StringBuilder sb = new StringBuilder();
            // Ignore first line, that's the geocoding key
            br.readLine();
            final String line = br.readLine();
            if (line != null) {
                sb.append(line.replace("\n", ""));
            }
            mapKey = sb.toString();
            return mapKey;
        } catch (IOException e) {
            throw new GeoCodeRuntimeException(
                    "Couldn't read key file: " + fileName, e);
        }
    }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 IITP RAS
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Kirill Andreev <andreev@iitp.ru>
 */

#include "peer-link-frame.h"
#include "ie-dot11s-peer-management.h"
#include "ns3/mesh-wifi-interface-mac.h"
#include "ns3/test.h"
#include "ns3/packet.h"

namespace ns3 {
namespace dot11s {
NS_OBJECT_ENSURE_REGISTERED (PeerLinkFrameStart);

PeerLinkFrameStart::PeerLinkFrameStart () :
  m_subtype (255), m_capability (0), m_aid (0), m_rates (SupportedRates ()), m_meshId (),
  m_config (IeConfiguration ()), m_reasonCode ((uint16_t)REASON11S_RESERVED)
{
}
void
PeerLinkFrameStart::SetPlinkFrameSubtype (uint8_t subtype)
{
  m_subtype = subtype;
}
void
PeerLinkFrameStart::SetPlinkFrameStart (PeerLinkFrameStart::PlinkFrameStartFields fields)
{
  m_subtype = fields.subtype;
  m_protocol = fields.protocol;
  if (m_subtype != (uint8_t)(WifiActionHeader::PEER_LINK_CLOSE))
    {
      m_capability = fields.capability;
    }
  if (m_subtype == (uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM))
    {
      m_aid = fields.aid;
    }
  if (m_subtype != (uint8_t)(WifiActionHeader::PEER_LINK_CLOSE))
    {
      m_rates = fields.rates;
    }
  if (m_subtype != (uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM))
    {
      m_meshId = fields.meshId;
    }
  if (m_subtype != (uint8_t)(WifiActionHeader::PEER_LINK_CLOSE))
    {
      m_config = fields.config;
    }
  else
    {
      m_reasonCode = fields.reasonCode;
    }
}
PeerLinkFrameStart::PlinkFrameStartFields
PeerLinkFrameStart::GetFields () const
{
  PlinkFrameStartFields retval;
  //TODO: protocol version:
  retval.subtype = m_subtype;
  retval.capability = m_capability;
  retval.aid = m_aid;
  retval.rates = m_rates;
  retval.meshId = m_meshId;
  retval.config = m_config;
  retval.reasonCode = m_reasonCode;
  return retval;
}
TypeId
PeerLinkFrameStart::GetTypeId ()
{
  static TypeId tid = TypeId ("ns3::dot11s::PeerLinkFrameStart").SetParent<Header> ().AddConstructor<
      PeerLinkFrameStart> ();
  return tid;
}
TypeId
PeerLinkFrameStart::GetInstanceTypeId () const
{
  return GetTypeId ();
}
void
PeerLinkFrameStart::Print (std::ostream &os) const
{
  os << "subtype = " << (uint16_t) m_subtype << std::endl << "capability = " << m_capability << std::endl << "laid = "
     << (uint16_t) m_aid << std::endl << "rates = " << m_rates << std::endl << "meshId = ";
  m_meshId.Print (os);
  os << std::endl << "configuration = ";
  m_config.Print (os);
  os << std::endl << "reason code = " << m_reasonCode;
}
uint32_t
PeerLinkFrameStart::GetSerializedSize () const
{
  uint32_t size = 3; //Peering protocol
  NS_ASSERT (m_subtype < 3);
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      size += 2; //capability
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) == m_subtype)
    {
      size += 2; //AID of remote peer
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      size += m_rates.GetSerializedSize ();
      size += m_rates.extended.GetSerializedSize ();
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) != m_subtype)
    {
      size += m_meshId.GetInformationFieldSize () + 2;
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      size += m_config.GetInformationFieldSize () + 2;
    }
  else
    {
      size += 2; //reasonCode
    }
  return size;
}
void
PeerLinkFrameStart::Serialize (Buffer::Iterator start) const
{
  Buffer::Iterator i = start;
  NS_ASSERT (m_subtype < 3);
  i = m_protocol.Serialize (i);
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      i.WriteHtolsbU16 (m_capability);
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) == m_subtype)
    {
      i.WriteHtolsbU16 (m_aid);
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      i = m_rates.Serialize (i);
      i = m_rates.extended.Serialize (i);
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) != m_subtype)
    {
      i = m_meshId.Serialize (i);
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      i = m_config.Serialize (i);
    }
  else
    {
      i.WriteHtolsbU16 (m_reasonCode);
    }
}
uint32_t
PeerLinkFrameStart::Deserialize (Buffer::Iterator start)
{
  Buffer::Iterator i = start;
  NS_ASSERT (m_subtype < 3);
  {
    uint8_t id = i.ReadU8 ();
    uint8_t length = i.ReadU8 ();
    m_protocol.DeserializeInformationField (i, length);
    if ((m_protocol.ElementId () != (WifiInformationElementId) id) || (m_protocol.GetInformationFieldSize () != length))
      {
        NS_FATAL_ERROR ("Broken frame: Element ID does not match IE itself!");
      }
    i.Next (m_protocol.GetInformationFieldSize ());
  }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      m_capability = i.ReadLsbtohU16 ();
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) == m_subtype)
    {
      m_aid = i.ReadLsbtohU16 ();
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      i = m_rates.Deserialize (i);
      i = m_rates.extended.DeserializeIfPresent (i);
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CONFIRM) != m_subtype)
    {
      uint8_t id = i.ReadU8 ();
      uint8_t length = i.ReadU8 ();
      m_meshId.DeserializeInformationField (i, length);
      if ((m_meshId.ElementId () != (WifiInformationElementId) id) || (m_meshId.GetInformationFieldSize () != length))
        {
          NS_FATAL_ERROR ("Broken frame: Element ID does not match IE itself!");
        }
      i.Next (m_meshId.GetInformationFieldSize ());
    }
  if ((uint8_t)(WifiActionHeader::PEER_LINK_CLOSE) != m_subtype)
    {
      uint8_t id = i.ReadU8 ();
      uint8_t length = i.ReadU8 ();
      m_config.DeserializeInformationField (i, length);
      if ((m_config.ElementId () != (WifiInformationElementId) id) || (m_config.GetInformationFieldSize () != length))
        {
          NS_FATAL_ERROR ("Broken frame: Element ID does not match IE itself!");
        }
      i.Next (m_config.GetInformationFieldSize ());
    }
  else
    {
      m_reasonCode = i.ReadLsbtohU16 ();
    }
  return i.GetDistanceFrom (start);
}
bool
operator== (const PeerLinkFrameStart & a, const PeerLinkFrameStart & b)
{
  return ((a.m_subtype == b.m_subtype) && (a.m_capability == b.m_capability) && (a.m_aid == b.m_aid)
          && (a.m_meshId.IsEqual (b.m_meshId)) && (a.m_config == b.m_config)
          && (a.m_reasonCode == b.m_reasonCode));
}
} // namespace dot11s
} // namespace ns3


text:
namespace torrent
{
    class Session
    {
        public:
            static void initialize ();
            static void load_torrent_states ();

            static std::vector < libtorrent::torrent_handle > get_torrents ();
            static libtorrent::torrent_handle add_torrent ( libtorrent::add_torrent_params const& params );
            static std::shared_ptr < libtorrent::alert > pop_alert ();

        private:
            Session ();

            static std::unique_ptr < Session > instance;
            libtorrent::session session;
    };
}

#endif //TORRENT_SESSION_GUARD


text:
@(telField: Field, typeField: Field, isMultiple: Boolean, optionMap: Map[String, Boolean])

    Telephone

      <input type="text"
             class="form-control"
             id="@telField.id"
             name="@telField.name"
             value="@telField.value.getOrElse("")"
             placeholder="XXX-XXX-XXXX" />
      @{telField.error.map { error => error.message }}

      <select
        class="form-control"
        id="@typeField.id"
        name="@if(isMultiple) {@(typeField.name + "[]")} else {@typeField.name}"
        @if(isMultiple) {multiple="multiple"}>
        @if(!isMultiple) {<option class="blank" value="">Please select a value</option>}
        @for((optionName, isSelected) <- optionMap) {
          <option id="@optionName" value="@optionName" @if(isSelected) {selected}>@optionName</option>
        }
      </select>
      @{typeField.error.map { error => error.message }}


text:
All functions in the AGEpy pakcage can be accessed using:

```python
import AGEpy as age
help(age.readGTF)
```

Alternatively, functions from the different modules can be accessed with for example:

```python
from AGEpy import gtf
help(gtf.readGTF)
```

### Help

In bash:

```bash
pydoc AGEpy.AGEpy
```

In python:

```python
help("AGEpy.AGEpy")
```

### Example usage

```python
import AGEpy as age

gtf=age.readGTF("/path/to/file.gtf")

gtf.head()
```


text:
Expenses

            Expense
            Description
            Amount

            {{item.title}}
            {{item.description}}
            {{item.amount | currency}}


text:
SCRIPT_PATH="$(readlink -f "$(dirname "$0")")"

C_NONE="\033[0;00m"
C_RED="\033[1;31m"
C_GREEN="\033[1;32m"

INSTALL_DIRS=(bin
              sofaboard
              plugins
              tools
              )
BIN_FILES=(bin/sofa
           bin/sofa_record.py
           bin/sofa_preprocess.py
           bin/sofa_analyze.py
           bin/STree.py
           bin/sofa_viz.py
           bin/sofa_config.py
           bin/sofa_print.py
           bin/sofa_common.py
           bin/potato_pb2.py
           bin/potato_pb2_grpc.py
           )
PLUGIN_FILES=(plugins/.placeholder
              )
SOFABOARD_FILES=(sofaboard/index.html
                 sofaboard/context.txt
                 sofaboard/cpu-report.html
                 sofaboard/gpu-report.html
                 sofaboard/comm-report.html
                 sofaboard/overhead.html
                 sofaboard/timeline.js
                 sofaboard/potato_report.css
                 )

print_help(){
    echo "This script will install the sofa scripts to your system under the specified <PREFIX> directory."
    echo ""
    echo "Usage: $0 PREFIX"
    echo "Examples: $0 ~/third-parties/sofa"
    echo "          sudo $0 /opt/sofa"
}

function clear_install_dir()
{
    # Use uninstall script to safely remove old files
    if [[ -f ${PREFIX}/tools/uninstall.sh ]]; then
        echo "Uninstalling SOFA..."
        bash ${PREFIX}/tools/uninstall.sh
    fi
    echo "Creating directories..."
    mkdir -p ${PREFIX}
    mkdir -p ${PREFIX}/bin
    mkdir -p ${PREFIX}/sofaboard
    mkdir -p ${PREFIX}/plugins
    mkdir -p ${PREFIX}/tools
}

function install_sofa()
{
    echo "Installing..."
    cp -raf ${SCRIPT_PATH}/bin       ${PREFIX}
    cp -raf ${SCRIPT_PATH}/plugins   ${PREFIX}
    cp -raf ${SCRIPT_PATH}/sofaboard ${PREFIX}

    # Create a new file for SOFA environment
################## heredoc style
    cat > ${PREFIX}/tools/activate.sh <<EOF
export PATH=${PREFIX}/bin:\$PATH
export PATH=\$PATH:/usr/local/cuda/bin
export PYTHONPATH=\$PYTHONPATH:${PREFIX}/plugins
export PYTHONPATH=\$PYTHONPATH:${PREFIX}/bin
EOF
##################

    # Create an uninstall script
################## heredoc style
    cat > ${PREFIX}/tools/uninstall.sh <<EOF
# Remove installed files
rm -r ${PREFIX}/bin
rm -r ${PREFIX}/sofaboard
rm -r ${PREFIX}/plugins
rm -r ${PREFIX}/tools
# Remove directory only if it is empty!
rmdir --ignore-fail-on-non-empty ${PREFIX}
EOF

chmod +x ${PREFIX}/tools/uninstall.sh
##################
}

for i in "$@"
do
case $i in
    -h|--help)
        print_help
        exit 0
    ;;
    *)
        # unknown option
    ;;
esac
done

# Detect empty string
if [[ "$1" == "" ]]; then
    echo -e "${C_RED}Please specify the install directory!${C_NONE}"
    print_help
    exit 1
fi

# Detect white space in the path
if [[ "$1" != "${1%[[:space:]]*}" ]]; then
    echo -e "${C_RED}The installation path cannot contain space character.${C_NONE}"
    exit 1
fi

# Get the first argument and also remove the tailing "/" if present
PREFIX="${1%/}"
# Add sofa to PREFIX if not present
[[ $(basename "$PREFIX") != "sofa" ]] && PREFIX="${PREFIX}/sofa"
# Resolve the abs path
PREFIX="$(readlink -f "$(dirname  "$PREFIX")")/$(basename "$PREFIX")"
#PREFIX="$(readlink -f "$PREFIX")"
echo -e "${C_GREEN}Installation directory is ${PREFIX}${C_NONE}"
if [[ $(pwd) == $PREFIX ]]; then
    echo -e "${C_RED}Warning! Installation directory is the same as the source code directory.${C_NONE}"
    echo -e "${C_RED}Please try another installation direcotry.${C_NONE}"
    exit 1
fi

# Print every executed command for debugging
set -x -e
clear_install_dir
install_sofa
# Disable printing every executed command for debugging
set +x +e

echo -e "${C_GREEN}Please try 'source ${PREFIX}/tools/activate.sh' to enjoy sofa!${C_NONE}\n"
echo -e "${C_GREEN}Add 'source ${PREFIX}/tools/activate.sh' to your ~/.bashrc if you want to enable sofa on every shells.${C_NONE}\n\n"