text:
define("p3/widget/InteractionsContainer", [
  'dojo/_base/declare', 'dijit/layout/BorderContainer', 'dojo/on',
  './ActionBar', './ContainerActionBar', 'dijit/layout/TabContainer',
  'dijit/layout/ContentPane'
], function (
  declare, BorderContainer, on,
  ActionBar, ContainerActionBar, TabContainer,
  ContentPane
) {

  return declare([BorderContainer], {
    gutters: false,
    design: 'sidebar',
    style: 'padding-left: 4px;',
    query: null,
    _setQueryAttr: function (query) {
      this.query = query;
      if (this.grid) {
        this.grid.set('query', query);
      }
    },
    startup: function () {
      if (this._started) {
        return;
      }
      this.containerActionBar = new ContainerActionBar({
        region: 'top',
        splitter: false,
        className: 'BrowserHeader'
      });
      this.selectionActionBar = new ActionBar({
        region: 'right',
        layoutPriority: 2,
        style: 'width:48px;text-align:center;',
        splitter: false
      });
      this.tabContainer = new TabContainer({ region: 'center' });
      this.ppiPanel = new ContentPane({ title: 'Protein-Protein Interactions (PPI)', content: 'PPI Graph' });
      this.ttiPanel = new ContentPane({ title: 'Taxon-Taxon Interactions (TTI)', content: 'TTI Graph' });
      this.tabContainer.addChild(this.ppiPanel);
      this.tabContainer.addChild(this.ttiPanel);

      this.interactionsGrid = new ContentPane({
        title: 'Taxon-Taxon Interactions (TTI)',
        content: 'Interactions Grid',
        region: 'bottom',
        style: 'height:150px',
        splitter: true
      });
      this.addChild(this.containerActionBar);
      this.addChild(this.tabContainer);
      this.addChild(this.selectionActionBar);
      this.addChild(this.interactionsGrid);

      this.inherited(arguments);
    }
  });
});


text:
declare module 'redux-mock-store' {
    import * as Redux from 'redux'

    function createMockStore<T>(middlewares?: Redux.Middleware[]): mockStore<T>;

    export type mockStore<T> = (state?: T) => IStore<T>;

    export interface IStore<T> {
        dispatch(action: any): any;
        getState(): T;
        getActions(): any[];
        clearActions(): void;
        subscribe(listener: Function): Function;
    }

    export default createMockStore
}

redpajama_set_name: RedPajamaGithub


text:
package ionescu.dan.rccameracontroller.communication;

import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Communicator {
    private Mqttt mqttt;
    private SerialCommandFormatter serialCommandFormatter;
    private IncommingRobotCommunicationCallback incommingRobotCommunicationCallback;
    private DirectionsInterpretter directionsInterpretter;

    public Communicator(Mqttt mqttt, SerialCommandFormatter serialCommandFormatter,
                        DirectionsInterpretter directionsInterpretter) {
        this.mqttt = mqttt;
        this.serialCommandFormatter = serialCommandFormatter;
        this.directionsInterpretter = directionsInterpretter;
    }

    public void sendMotionCommand(MoveEvent moveEvent) {
        String command = this.serialCommandFormatter.
                formatDirection(
                        directionsInterpretter.getScaledX(moveEvent),
                        directionsInterpretter.getScaledY(moveEvent)
                );
        Log.d("motion-cmd:", command);
        this.mqttt.send(command);
    }

    public void sendLightCommand(boolean state) {
        String command = this.serialCommandFormatter.formatLights(state);
        Log.d("light-cmd:", command);
        this.mqttt.send(command);
    }

    public void addIncommingMessageListener(final IncommingRobotCommunicationCallback incommingRobotCommunicationCallback) {
        this.mqttt.addMessageArrivedListener(new MessageArrivedCallback() {
            Pattern batteryUpdate = Pattern.compile("B:([0-9/.]{3,4});");
            Pattern distanceUpdate = Pattern.compile("F=([0-9]{1,2}):B=([0-9]{1,2});");

            @Override
            public void messageArrived(String topic, String message) {
                Matcher batteryMatcher = batteryUpdate.matcher(message);
                Matcher distanceMatcher = distanceUpdate.matcher(message);
                if (batteryMatcher.matches()) {
                    incommingRobotCommunicationCallback.batteryLevelUpdated(
                            Float.parseFloat(batteryMatcher.group(1))
                    );
                }
                if (distanceMatcher.matches()) {
                    incommingRobotCommunicationCallback.distanceUpdated(
                            Float.parseFloat(distanceMatcher.group(1)),
                            Float.parseFloat(distanceMatcher.group(2))
                    );
                }
            }
        });
        this.incommingRobotCommunicationCallback = incommingRobotCommunicationCallback;
    }

    public void addConectionStatusListener(final ConnectionStatusCallback connectionStatusCallback) {
        this.mqttt.addConectionStatusListener(connectionStatusCallback);
    }

    public void initialize() {
        this.mqttt.connect();
    }
}


text:
(function($){

	// Preloader
   	$(window).load(function() {
       	$('#status').fadeOut();
        $('#preloader').delay(100).fadeOut('slow');
        $('body').delay(100).css({'overflow':'visible'});
    });

	$(document).ready(function() {

		// Handling Window Resize
		var countdown =  $('.countdown-time');

		createTimeCicles();

		$(window).on('resize', windowSize);

		function windowSize(){
			countdown.TimeCircles().destroy();
		    createTimeCicles();
			countdown.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', function() {
        		countdown.removeClass('animated bounceIn');
        	});
		}

		// TimeCicles
		function createTimeCicles() {
			countdown.addClass('animated bounceIn');
			countdown.TimeCircles({
				bg_width: 1,
    			fg_width: 0.04,
				circle_bg_color: '#bdc3c7',
				time: {
    				    Days: {color: '#c0392b'}
    			,	   Hours: {color: '#27ae60'}
    			,	 Minutes: {color: '#2980b9'}
    			,	 Seconds: {color: '#8e44ad'}
    			}
			});
			countdown.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', function() {
        		countdown.removeClass('animated bounceIn');
        	});
		}

		// Open modal window on click
		$('.links a').on('click', function(e) {
			var mainInner = $('.overlay'),
				modal = $('#' + $(this).attr('data-modal'));

			mainInner.animate({opacity: 0}, 400, function(){
				$('html,body').scrollTop(0);
				modal.addClass('active').fadeIn(400);
				countdown.TimeCircles().destroy();
			});
			e.preventDefault();

			$('.modal-close').on('click', function(e) {
				modal.removeClass('active').fadeOut(400, function(){
					mainInner.animate({opacity: 1}, 400);
		       		createTimeCicles();
					countdown.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', function() {
        				countdown.removeClass('animated bounceIn');
        			});
				});
				e.preventDefault();
			});
		});

		// Tooltips
		$('.links a, .share a').tooltip();

		$('.links a, .share a').on('click', function () {
			$(this).tooltip('hide')
		});

	});
})(jQuery);

// "Typewriter"
(function($){
	$.fn.typewriter = function() {
		this.each(function() {
			var $ele = $(this), str = $ele.html(), progress = 0;
			$ele.html('');
			var timer = setInterval(function() {
				var current = str.substr(progress, 1);
				if (current == '<') {
					progress = str.indexOf('>', progress) + 1;
				} else {
					progress++;
				}
				$ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
				if (progress >= str.length) {
					clearInterval(timer);
				}
			}, 75);
		});
		return this;
	};
})(jQuery);

// Error Message (If your "browser" doesn't support canvas)
if (!document.createElement('canvas').getContext) {
	var msg = document.createElement("div");
		msg.id = "errorMsg";
		msg.innerHTML = "Your 'browser' doesn't support HTML5!<br/> Try a real web browser ;)";
		document.body.appendChild(msg);
	$("#code").css("display", "none")
}
else {
	$("#code").typewriter();
}


text:
#ifndef EM_RINGBUF_CPP_H
#define EM_RINGBUF_CPP_H

#include "RingBufHelpers.h"

template <typename Type, size_t MaxElements>
class RingBufCPP
{
public:

RingBufCPP()
{
     RB_ATOMIC_START
     {
         _numElements = 0;

         _head = 0;
     }
     RB_ATOMIC_END
}

/**
* Add element obj to the buffer.
*
* If there is already MaxElements in the buffer,
* the oldest element will either be overwritten (when overwrite is true) or
* this add will have no effect (when overwrite is false).
*
* Return: true if there was room in the buffer to add this element
*/
bool add(const Type &obj, bool overwrite=false)
{
    bool full = false;
    RB_ATOMIC_START
    {
        full = isFull();
        if (!full || overwrite) {
            _buf[_head] = obj;
            _head = (_head + 1)%MaxElements;
            _numElements = full ? _numElements : (_numElements + 1);
        }
    }
    RB_ATOMIC_END

    return !full;
}

/**
* Remove last element from buffer, and copy it to dest
* Return: true on success
*/
bool pull(Type *dest)
{
    bool ret = false;
    size_t tail;

    RB_ATOMIC_START
    {
        if (!isEmpty()) {
            tail = getTail();
            *dest = _buf[tail];
            _numElements--;

            ret = true;
        }
    }
    RB_ATOMIC_END

    return ret;
}

/**
* Peek at num'th element in the buffer
* Return: a pointer to the num'th element
*/
Type* peek(size_t num)
{
    Type *ret = NULL;

    RB_ATOMIC_START
    {
        if (num < _numElements) //make sure not out of bounds
            ret = &_buf[(getTail() + num)%MaxElements];
    }
    RB_ATOMIC_END

    return ret;
}

/**
* Return: true if buffer is full
*/
bool isFull() const
{
    bool ret;

    RB_ATOMIC_START
    {
        ret = _numElements >= MaxElements;
    }
    RB_ATOMIC_END

    return ret;
}

/**
* Return: number of elements in buffer
*/
size_t numElements() const
{
    size_t ret;

    RB_ATOMIC_START
    {
        ret = _numElements;
    }
    RB_ATOMIC_END

    return ret;
}

/**
* Return: true if buffer is empty
*/
bool isEmpty() const
{
    bool ret;

    RB_ATOMIC_START
    {
        ret = !_numElements;
    }
    RB_ATOMIC_END

    return ret;
}

protected:
/**
* Calculates the index in the array of the oldest element
* Return: index in array of element
*/
size_t getTail() const
{
    return (_head + (MaxElements - _numElements))%MaxElements;
}

// underlying array
Type _buf[MaxElements];

size_t _head;
size_t _numElements;
private:

};

#endif


text:
module Neo4j
  module Wrapper
    module Rule
      module Functions

        # A function for counting number of nodes of a given class.
        class Size < Function
          def initialize
            @property = '_classname'
            @@lock ||= Java::java.lang.Object.new
          end

          def calculate?(changed_property)
            true
          end

          def delete(rule_name, rule_node, _)
            key = rule_node_property(rule_name)
            rule_node[key] ||= 0
            rule_node[key] -= 1
          end

          def add(rule_name, rule_node, _)
            key = rule_node_property(rule_name)
            rule_node[key] ||= 0
            rule_node[key] += 1
          end

          def update(*)
            # we are only counting, not interested in property changes
          end

          def classes_changed(rule_name, rule_node, class_change)
            key = rule_node_property(rule_name)
            @@lock.synchronized do
              rule_node[key] ||= 0
              rule_node[key] += class_change.net_change
            end
          end

          def self.function_name
            :size
          end
        end
      end
    end
  end
end


text:
package com.jaquadro.minecraft.storagedrawers.integration.refinedrelocation;

import com.dynious.refinedrelocation.api.APIUtils;
import com.dynious.refinedrelocation.api.filter.IFilter;
import com.dynious.refinedrelocation.api.tileentity.ISortingInventory;
import com.dynious.refinedrelocation.api.tileentity.ISpecialSortingInventory;
import com.dynious.refinedrelocation.api.tileentity.grid.SpecialLocalizedStack;
import com.dynious.refinedrelocation.api.tileentity.handlers.ISortingInventoryHandler;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroup;
import com.jaquadro.minecraft.storagedrawers.storage.IUpgradeProvider;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;

public class DrawerSortingInventory
{
    private ISpecialSortingInventory parent;
    private IDrawerGroup group;
    private IInventory inventory;
    private IUpgradeProvider upgrade;

    private ISortingInventoryHandler sortingHandler;
    private DrawerFilter filter;
    private boolean isAttached;

    public DrawerSortingInventory (TileEntity tileEntity, IDrawerGroup group, IInventory inventory, IUpgradeProvider upgrade) {
        parent = (ISpecialSortingInventory)tileEntity;
        this.group = group;
        this.inventory = inventory;
        this.upgrade = upgrade;

        sortingHandler = APIUtils.createSortingInventoryHandler(tileEntity);
        filter = new DrawerFilter(group);
    }

    public void attach () {
        if (!isAttached) {
            getHandler().onTileAdded();
            isAttached = true;
        }
    }

    public void detach () {
        if (isAttached) {
            getHandler().onTileRemoved();
            isAttached = false;
        }
    }

    public boolean isAttached () {
        return isAttached;
    }

    public boolean putStackInSlot (ItemStack itemStack, int slotIndex) {
        inventory.setInventorySlotContents(slotIndex, itemStack);
        return true;
    }

    public ItemStack putInInventory (ItemStack itemStack, boolean simulate) {
        for (int i = 0; i < group.getDrawerCount(); i++) {
            if (!group.isDrawerEnabled(i))
                continue;

            IDrawer drawer = group.getDrawer(i);
            if (drawer.isEmpty() || !drawer.canItemBeStored(itemStack))
                continue;

            int added = upgrade.isVoid() ? itemStack.stackSize : Math.min(drawer.getRemainingCapacity(), itemStack.stackSize);
            if (!simulate)
                drawer.setStoredItemCount(drawer.getStoredItemCount() + added);

            itemStack.stackSize -= added;
            if (itemStack.stackSize == 0)
                return null;
        }

        return itemStack;
    }

    public SpecialLocalizedStack getLocalizedStackInSlot (int slot) {
        ItemStack itemStack = inventory.getStackInSlot(slot);
        if (itemStack != null) {
            int drawerSlot = group.getDrawerInventory().getDrawerSlot(slot);
            if (!group.isDrawerEnabled(drawerSlot))
                return null;

            IDrawer drawer = group.getDrawer(drawerSlot);
            return new SpecialLocalizedStack(itemStack, parent, slot, drawer.getStoredItemCount());
        }

        return null;
    }

    public void alterStackSize (int slot, int alteration) {
        int drawerSlot = group.getDrawerInventory().getDrawerSlot(slot);
        if (!group.isDrawerEnabled(drawerSlot))
            return;

        IDrawer drawer = group.getDrawer(drawerSlot);
        drawer.setStoredItemCount(drawer.getStoredItemCount() + alteration);
    }

    public ISortingInventory.Priority getPriority () {
        return ISortingInventory.Priority.NORMAL_HIGH;
    }

    public void setPriority (ISortingInventory.Priority priority) {

    }

    public IFilter getFilter () {
        return filter;
    }

    public ISortingInventoryHandler getHandler () {
        return sortingHandler;
    }

    public void markDirty () {
        getHandler().onInventoryChange();
    }
}


text:
package seedu.lifekeeper.commons.events.model;

import seedu.lifekeeper.commons.events.BaseEvent;

/**
 * Indicates that the data file location has changed.
 */
public class SaveEvent extends BaseEvent {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <title>IE issues</title>

Issues in Internet Explorer 5.5 & 6

$Id: ie_issues.html 10655 2006-12-18 15:47:57Z hallvord $

         These are different issues I encountered when
         making the ASCII and Image version of SpaceInvaders play
         in Internet Explorer 5.5 and 6.

JavaScript Issues

            Issue
            Description
            What to do

            JS methods are read-only.

               You can't redefine javscript methods, i.e.

   setTimeout =
      function()
      {
         ...
      };

               if( !isExplorer() ) { .. }

            Event.EVENTTYPE
            IE don't support capture/relaseEvents, where you use Event.EVENTTYPE

               Only used when doing NSish things like
               window.captureEvents( Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP )
               and window.releaseEvents( Event.MOUSEMOVE );

            Event object

               IE doesn't pass the event object
               to the handler function.

               Read the global window.event
               instead when isExplorer(). This works in Opera 7, but
               not in Mozilla 1.1 or Opera 6.

            Event.which

               IE doesn't have the which property
               of the event object, used for finding
               out the ASCII code for the key pressed

                  Use window.event.keyCode
                  instead when isExplorer().

                  This does not work in Opera 6
                  ( where you need to use the passed event object
                  instead of window.event ),
                  Mozilla returns 0 on all keyCodes (!), and Opera 7 returns
                  undefined when used with a mouse event,
                  bug #84079.

            screenX or screenY

               IE doesn't have the screenX and screenY properties
               of the event object, used for finding
               where the mouse was when the event triggered.

                  Use window.event.clientX and
                  window.event.clientY instead
                  when isExplorer().

                  This does not work in Opera 6
                  ( where you need to use the passed event object
                  instead of window.event ), and Opera 7 returns undefined
                  when used with a key event,
                  bug #84066.
                  Works in Mozilla 1.1.

            window.innerWidth and window.innerHeight

               IE doesn't have window.innerWidth or
               window.innerHeight.

                  Use document.body.clientWidth and
                  document.body.clientHeight instead
                  when isExplorer(). This works in Opera 7 and Mozilla 1.1.

                  Be careful, especially with the height if you're using the DOM,
                  since clientHeight only gives you the initial height
                  of the elements making the document. You don't get
                  the actually window area you see the document occupies.
                  So, if you're using the DOM to expand your page height,
                  the IE property will not reflect this.

DOM Issues

            Issue
            Description
            What to do

            Applying CSS to DOM created element

               When using setAttribute() to
               set CSS properties to an element, these are not
               applied to the element in IE 6. e.g.
               setAttribute( "style", "text-align: center" );

               Define all CSS in external stylesheet, with general
               declarations for elements as far as you can, IE doesn't understad the
               setting of style or class attribute.

            tables

               When using the DOM to create tables, IE does not
               render anything if you don't include everythin in a
               TBODY element. However, it will create all elements that
               you specify for your table and return all values give it.

               Use TBODY as the parent of all TR elements, this
               is understood by all the browsers1).

            document.lastChild.lastChild

               document.lastChild.lastChild returns the BODY element
               in Mozilla, Galeon, Opera and IE 6. However, IE 5 returns
               undefined.

              Use document.body instead, this works in
              all browsers1).

Other

            Transparent PNG images

                  IE 6 has huge problems with transparent PNG images.
                  Only two out of 14 images used in the Image version
                  of SpaceInvaders are displayed with transparent background.

                  The Gimp was used
                  for editing/creating the PNG images.

               !isExplorer() { .. }

                  IE is known for its problems with PNG images. It uses a
                  different PNG library from Opera and Mozilla.

         1) Tested in Opera 7 for Windows, Mozilla 1.0 on
         Linux and Windows, Galeon on Linux, and IE 5.5 & IE 6 on Windows.

         torstein@opera.com


text:
/*
 * Note - used PUBLIC DOMAIN http://sourceforge.net/projects/libb64/files/libb64/libb64/libb64-1.2.src.zip/download
 * code as a starting point.
 */
#include "../../../StroikaPreComp.h"

#include <algorithm>
#include <cstdlib>

#include "../../../Containers/Common.h"
#include "../../../DataExchange/BadFormatException.h"
#include "../../../Debug/Assertions.h"
#include "../../../Memory/BLOB.h" // ONLY FOR QUICKHACK IMPL OF ENCODE...
#include "../../../Memory/StackBuffer.h"

#include "Base64.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::Encoding;
using namespace Stroika::Foundation::Cryptography::Encoding::Algorithm;
using namespace Stroika::Foundation::Memory;

using std::byte;

/**
 *  IMPLEMENTATION NOTES:
 *
 *      The public domain (private) code in this file - is designed to operate in a STREAM mode. I've preserved that
 *  internally, evne though my current API doesn't work that way, because we will soon support a STREAM based API here,
 *  and that will fit perfectly.
 *
 *  @see    http://libb64.sourceforge.net/ - which explains the design of the routines, and the queer nested loop / switch
 *          construct.
 *
 *      -- LGP 2011-06-21
 */

/*
 ********************************************************************************
 *************************** Encoding::DecodeBase64 *****************************
 ********************************************************************************
 */
namespace {
    enum base64_decodestep_ {
        step_a,
        step_b,
        step_c,
        step_d
    };
    struct base64_decodestate_ {
        base64_decodestep_ step{step_a};
#if qCompilerAndStdLib_relaxedEnumClassInitializationRules_Buggy
        byte plainchar{(byte)0};
#else
        byte plainchar{0};
#endif
    };
    int base64_decode_value_ (signed char value_in)
    {
        static constexpr signed char kDecoding[] = {62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};
        value_in -= 43;
        if (value_in < 0 || static_cast<unsigned char> (value_in) >= NEltsOf (kDecoding)) {
            return -1;
        }
        Assert (0 <= value_in and static_cast<unsigned char> (value_in) < NEltsOf (kDecoding));
        return kDecoding[(int)value_in];
    }
    size_t base64_decode_block_ (const signed char* code_in, size_t length_in, byte* plaintext_out, base64_decodestate_* state)
    {
        RequireNotNull (code_in);
        RequireNotNull (plaintext_out);

        const signed char* codechar  = code_in;
        byte*              plainchar = plaintext_out;
        signed char        fragment  = '\0';

        *plainchar = state->plainchar;

        switch (state->step) {
            while (true) {
                case step_a:
                    do {
                        if (codechar == code_in + length_in) {
                            state->step      = step_a;
                            state->plainchar = *plainchar;
                            return plainchar - plaintext_out;
                        }
                        fragment = (signed char)base64_decode_value_ (*codechar++);
                    } while (fragment < 0);
                    *plainchar = byte ((fragment & 0x03f) << 2);
                case step_b:
                    do {
                        if (codechar == code_in + length_in) {
                            state->step      = step_b;
                            state->plainchar = *plainchar;
                            return plainchar - plaintext_out;
                        }
                        fragment = (signed char)base64_decode_value_ (*codechar++);
                    } while (fragment < 0);
                    *plainchar++ |= byte ((fragment & 0x030) >> 4);
                    *plainchar = byte ((fragment & 0x00f) << 4);
                case step_c:
                    do {
                        if (codechar == code_in + length_in) {
                            state->step      = step_c;
                            state->plainchar = *plainchar;
                            return plainchar - plaintext_out;
                        }
                        fragment = (signed char)base64_decode_value_ (*codechar++);
                    } while (fragment < 0);
                    *plainchar++ |= byte ((fragment & 0x03c) >> 2);
                    *plainchar = byte ((fragment & 0x003) << 6);
                case step_d:
                    do {
                        if (codechar == code_in + length_in) {
                            state->step      = step_d;
                            state->plainchar = *plainchar;
                            return plainchar - plaintext_out;
                        }
                        fragment = (signed char)base64_decode_value_ (*codechar++);
                    } while (fragment < 0);
                    *plainchar++ |= byte (fragment & 0x03f);
            }
        }
        return plainchar - plaintext_out;
    }
}

Memory::BLOB Algorithm::DecodeBase64 (const Characters::String& s)
{
    //@todo - improve/fix this
    return DecodeBase64 (s.AsUTF8 ());
}

Memory::BLOB Algorithm::DecodeBase64 (const string& s)
{
    if (s.empty ()) {
        return Memory::BLOB{};
    }
    size_t              dataSize1 = s.length ();
    StackBuffer<byte>   buf1{Memory::eUninitialized, dataSize1}; // MUCH more than big enuf
    base64_decodestate_ state{};
    size_t              r = base64_decode_block_ (reinterpret_cast<const signed char*> (Containers::Start (s)), s.length (), buf1.begin (), &state);
    Assert (r <= dataSize1);
    // @todo - should validate this produced a good result? - maybe check resulting state?
    return Memory::BLOB{buf1.begin (), buf1.begin () + r};
}

void Algorithm::DecodeBase64 (const string& s, const Streams::OutputStream<byte>::Ptr& out)
{
    // QUICKIE implementation...
    Memory::BLOB tmp = DecodeBase64 (s);
    out.Write (tmp.begin (), tmp.end ());
}

/*
 ********************************************************************************
 ************************** Algorithm::EncodeBase64 *****************************
 ********************************************************************************
 */
namespace {
    enum base64_encodestep {
        step_A,
        step_B,
        step_C
    };
    struct base64_encodestate {
        base64_encodestep step{step_A};
        signed char       result{0};
        int               stepcount{0};
        LineBreak         fLineBreak;

        base64_encodestate (LineBreak lb)
            : fLineBreak{lb}
        {
        }
    };

    signed char base64_encode_value_ (signed char value_in)
    {
        const signed char BASE64_CHARS_[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        Assert (NEltsOf (BASE64_CHARS_) == (2 * 26 + 10 + 2 + 1));
        if (value_in > 63) {
            return '=';
        }
        return BASE64_CHARS_[(int)value_in];
    }

    size_t base64_encode_block_ (const byte* plaintext_in, size_t length_in, signed char* code_out, base64_encodestate* state)
    {
        const int CHARS_PER_LINE = 76;

        const byte*       plainchar    = plaintext_in;
        const byte* const plaintextend = plaintext_in + length_in;
        signed char*      codechar     = code_out;
        signed char       result       = state->result;

        signed char fragment = '\0';
        switch (state->step) {
            while (1) {
                case step_A:
                    if (plainchar == plaintextend) {
                        state->result = result;
                        state->step   = step_A;
                        return codechar - code_out;
                    }
                    fragment    = to_integer<signed char> (*plainchar++);
                    result      = (fragment & 0x0fc) >> 2;
                    *codechar++ = base64_encode_value_ (result);
                    result      = (fragment & 0x003) << 4;
                case step_B:
                    if (plainchar == plaintextend) {
                        state->result = result;
                        state->step   = step_B;
                        return codechar - code_out;
                    }
                    fragment = to_integer<signed char> (*plainchar++);
                    result |= (fragment & 0x0f0) >> 4;
                    *codechar++ = base64_encode_value_ (result);
                    result      = (fragment & 0x00f) << 2;
                case step_C:
                    if (plainchar == plaintextend) {
                        state->result = result;
                        state->step   = step_C;
                        return codechar - code_out;
                    }
                    fragment = to_integer<signed char> (*plainchar++);
                    result |= (fragment & 0x0c0) >> 6;
                    *codechar++ = base64_encode_value_ (result);
                    result      = (fragment & 0x03f) >> 0;
                    *codechar++ = base64_encode_value_ (result);

                    ++(state->stepcount);
                    if (state->stepcount == CHARS_PER_LINE / 4) {
                        switch (state->fLineBreak) {
                            case LineBreak::eLF_LB:
                                *codechar++ = '\n';
                                break;
                            case LineBreak::eCRLF_LB:
                                *codechar++ = '\r';
                                *codechar++ = '\n';
                                break;
                        }
                        state->stepcount = 0;
                    }
            }
        }
        return codechar - code_out;
    }
    inline size_t base64_encode_blockend_ (signed char* code_out, base64_encodestate* state)
    {
        signed char* codechar = code_out;
        switch (state->step) {
            case step_B:
                *codechar++ = base64_encode_value_ (state->result);
                *codechar++ = '=';
                *codechar++ = '=';
                break;
            case step_C:
                *codechar++ = base64_encode_value_ (state->result);
                *codechar++ = '=';
                break;
            case step_A:
                break;
        }
        return static_cast<size_t> (codechar - code_out);
    }
}

string Algorithm::EncodeBase64 (const Streams::InputStream<byte>::Ptr& from, LineBreak lb)
{
#if 0
    // Use look doing multiple base64_encode_block_() calls!
#elif 1
    // quick hack impl
    Memory::BLOB bytes = Streams::InputStream<byte>::Ptr (from).ReadAll ();
    const byte* start = bytes.begin ();
    const byte* end = bytes.end ();
    Require (start == end or start != nullptr);
    Require (start == end or end != nullptr);
    base64_encodestate state{lb};
    size_t srcLen = end - start;
    size_t bufSize = 4 * srcLen;
    Assert (bufSize >= srcLen); // no overflow!
    StackBuffer<signed char> data{Memory::eUninitialized, bufSize};
    size_t mostBytesCopied = base64_encode_block_ (start, srcLen, data.begin (), &state);
    size_t extraBytes = base64_encode_blockend_ (data.begin () + mostBytesCopied, &state);
    size_t totalBytes = mostBytesCopied + extraBytes;
    Assert (totalBytes <= bufSize);
    return string{data.begin (), data.begin () + totalBytes};
#else
    Require (start == end or start != nullptr);
    Require (start == end or end != nullptr);

    base64_encodestate state{lb};
    size_t             srcLen  = end - start;
    size_t             bufSize = 4 * srcLen;
    Assert (bufSize >= srcLen); // no overflow!
    StackBuffer<char> data{Memory::eUninitialized, bufSize};
    size_t            mostBytesCopied = base64_encode_block_ (start, srcLen, data.begin (), &state);
    size_t            extraBytes      = base64_encode_blockend_ (data.begin () + mostBytesCopied, &state);
    size_t            totalBytes      = mostBytesCopied + extraBytes;
    Assert (totalBytes <= bufSize);
    return string{data.begin (), data.begin () + totalBytes};
#endif
}

string Algorithm::EncodeBase64 (const Memory::BLOB& from, LineBreak lb)
{
    const byte* start = from.begin ();
    const byte* end   = from.end ();
    Require (start == end or start != nullptr);
    Require (start == end or end != nullptr);
    base64_encodestate state{lb};
    size_t             srcLen  = end - start;
    size_t             bufSize = 4 * srcLen;
    Assert (bufSize >= srcLen); // no overflow!
    StackBuffer<signed char> data{Memory::eUninitialized, bufSize};
    size_t                   mostBytesCopied = base64_encode_block_ (start, srcLen, data.begin (), &state);
    size_t                   extraBytes      = base64_encode_blockend_ (data.begin () + mostBytesCopied, &state);
    size_t                   totalBytes      = mostBytesCopied + extraBytes;
    Assert (totalBytes <= bufSize);
    return string{data.begin (), data.begin () + totalBytes};
}


text:
<?php

use Wasp\DI\DependencyInjectionAwareTrait;

/**
 * Just a test service
 *
 * @package Wasp
 * @subpackage Tests
 * @author Dan Cox
 */
class Service
{
    use DependencyInjectionAwareTrait;

    /**
     * An Instance of the Test Library
     *
     * @var Object
     */
    protected $library;

    /**
     * Set up class dependencies
     *
     * @return void
     * @author Dan Cox
     */
    public function __construct($library = NULL)
    {
        $this->library = $library;
    }

    /**
     * Test func
     *
     * @return void
     * @author Dan Cox
     */
    public function fs()
    {
        return $this->DI->get('fs');
    }

    /**
     * Test fun
     *
     * @return void
     * @author Dan Cox
     */
    public function useLibrary()
    {
        return $this->library->foo();
    }

} // END class Service


text:
package confighistory

import (
	"fmt"
	"path/filepath"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset"
	"github.com/hyperledger/fabric-protos-go/peer"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/common/ledger/snapshot"
	"github.com/hyperledger/fabric/core/ledger"
	"github.com/hyperledger/fabric/internal/fileutil"
	"github.com/pkg/errors"
)

var (
	logger                 = flogging.MustGetLogger("confighistory")
	importConfigsBatchSize = 1024 * 1024
)

const (
	collectionConfigNamespace = "lscc" // lscc namespace was introduced in version 1.2 and we continue to use this in order to be compatible with existing data
	snapshotFileFormat        = byte(1)
	snapshotDataFileName      = "confighistory.data"
	snapshotMetadataFileName  = "confighistory.metadata"
)

// Mgr manages the history of configurations such as chaincode's collection configurations.
// It should be registered as a state listener. The state listener builds the history.
type Mgr struct {
	ccInfoProvider ledger.DeployedChaincodeInfoProvider
	dbProvider     *dbProvider
}

// NewMgr constructs an instance that implements interface `Mgr`
func NewMgr(dbPath string, ccInfoProvider ledger.DeployedChaincodeInfoProvider) (*Mgr, error) {
	p, err := newDBProvider(dbPath)
	if err != nil {
		return nil, err
	}
	return &Mgr{ccInfoProvider, p}, nil
}

// Name returns the name of the listener
func (m *Mgr) Name() string {
	return "collection configuration history listener"
}

// Initialize implements function from the interface ledger.StateListener
func (m *Mgr) Initialize(ledgerID string, qe ledger.SimpleQueryExecutor) error {
	// Noop
	return nil
}

// InterestedInNamespaces implements function from the interface ledger.StateListener
func (m *Mgr) InterestedInNamespaces() []string {
	return m.ccInfoProvider.Namespaces()
}

// StateCommitDone implements function from the interface ledger.StateListener
func (m *Mgr) StateCommitDone(ledgerID string) {
	// Noop
}

// HandleStateUpdates implements function from the interface ledger.StateListener
// In this implementation, the latest collection config package is retrieved via
// ledger.DeployedChaincodeInfoProvider and is persisted as a separate entry in a separate db.
// The composite key for the entry is a tuple of <blockNum, namespace, key>
func (m *Mgr) HandleStateUpdates(trigger *ledger.StateUpdateTrigger) error {
	updatedCCs, err := m.ccInfoProvider.UpdatedChaincodes(extractPublicUpdates(trigger.StateUpdates))
	if err != nil {
		return err
	}
	// updated chaincodes can be empty if the invocation to this function is triggered
	// because of state updates that contains only chaincode approval transaction output
	if len(updatedCCs) == 0 {
		return nil
	}
	updatedCollConfigs := map[string]*peer.CollectionConfigPackage{}
	for _, cc := range updatedCCs {
		ccInfo, err := m.ccInfoProvider.ChaincodeInfo(trigger.LedgerID, cc.Name, trigger.PostCommitQueryExecutor)
		if err != nil {
			return err
		}

		// DeployedChaincodeInfoProvider implementation in new lifecycle return an empty 'CollectionConfigPackage'
		// (instead of a nil) to indicate the absence of collection config, so check for both conditions
		if ccInfo.ExplicitCollectionConfigPkg == nil || len(ccInfo.ExplicitCollectionConfigPkg.Config) == 0 {
			continue
		}
		updatedCollConfigs[ccInfo.Name] = ccInfo.ExplicitCollectionConfigPkg
	}
	if len(updatedCollConfigs) == 0 {
		return nil
	}
	dbHandle := m.dbProvider.getDB(trigger.LedgerID)
	batch := dbHandle.newBatch()
	err = prepareDBBatch(batch, updatedCollConfigs, trigger.CommittingBlockNum)
	if err != nil {
		return err
	}
	return dbHandle.writeBatch(batch, true)
}

// ImportConfigHistory imports the collection config history associated with a given
// ledgerID from the snapshot files present in the dir
func (m *Mgr) ImportFromSnapshot(ledgerID string, dir string) error {
	exist, _, err := fileutil.FileExists(filepath.Join(dir, snapshotDataFileName))
	if err != nil {
		return err
	}
	if !exist {
		// when the ledger being bootstapped never had a private data collection for
		// any chaincode, the snapshot files associated with the confighistory store
		// will not be present in the snapshot directory. Hence, we can return early
		return nil
	}
	db := m.dbProvider.getDB(ledgerID)
	empty, err := db.IsEmpty()
	if err != nil {
		return err
	}
	if !empty {
		return errors.New(fmt.Sprintf(
			"config history for ledger [%s] exists. Incremental import is not supported. "+
				"Remove the existing ledger data before retry",
			ledgerID,
		))
	}

	configMetadata, err := snapshot.OpenFile(filepath.Join(dir, snapshotMetadataFileName), snapshotFileFormat)
	if err != nil {
		return err
	}
	numCollectionConfigs, err := configMetadata.DecodeUVarInt()
	if err != nil {
		return err
	}
	collectionConfigData, err := snapshot.OpenFile(filepath.Join(dir, snapshotDataFileName), snapshotFileFormat)
	if err != nil {
		return err
	}

	batch := db.NewUpdateBatch()
	currentBatchSize := 0
	for i := uint64(0); i < numCollectionConfigs; i++ {
		key, err := collectionConfigData.DecodeBytes()
		if err != nil {
			return err
		}
		val, err := collectionConfigData.DecodeBytes()
		if err != nil {
			return err
		}
		batch.Put(key, val)
		currentBatchSize += len(key) + len(val)
		if currentBatchSize >= importConfigsBatchSize {
			if err := db.WriteBatch(batch, true); err != nil {
				return err
			}
			currentBatchSize = 0
			batch.Reset()
		}
	}
	return db.WriteBatch(batch, true)
}

// GetRetriever returns an implementation of `ledger.ConfigHistoryRetriever` for the given ledger id.
func (m *Mgr) GetRetriever(ledgerID string) *Retriever {
	return &Retriever{
		ledgerID: ledgerID,
		dbHandle: m.dbProvider.getDB(ledgerID),
	}
}

// Close implements the function in the interface 'Mgr'
func (m *Mgr) Close() {
	m.dbProvider.Close()
}

// Drop drops channel-specific data from the config history db
func (m *Mgr) Drop(ledgerid string) error {
	return m.dbProvider.Drop(ledgerid)
}

// Retriever helps consumer retrieve collection config history
type Retriever struct {
	ledgerID string
	dbHandle *db
}

// MostRecentCollectionConfigBelow implements function from the interface ledger.ConfigHistoryRetriever
func (r *Retriever) MostRecentCollectionConfigBelow(blockNum uint64, chaincodeName string) (*ledger.CollectionConfigInfo, error) {
	compositeKV, err := r.dbHandle.mostRecentEntryBelow(blockNum, collectionConfigNamespace, constructCollectionConfigKey(chaincodeName))
	if err != nil || compositeKV == nil {
		return nil, err
	}
	return compositeKVToCollectionConfig(compositeKV)
}

// ExportConfigHistory exports configuration history from the confighistoryDB to
// a file. Currently, we store only one type of configuration in the db, i.e.,
// private data collection configuration.
// We write the full key and value stored in the database as is to the file.
// Though we could decode the key and write a proto message with exact ns, key,
// block number, and collection config, we store the full key and value to avoid
// unnecessary encoding and decoding of proto messages.
// The key format stored in db is "s" + ns + byte(0) + key + "~collection" + byte(0)
// + blockNum. As we store the key as is, we store 13 extra bytes. For a million
// records, it would add only 12 MB overhead. Note that the protobuf also adds some
// extra bytes. Further, the collection config namespace is not expected to have
// millions of entries.
func (r *Retriever) ExportConfigHistory(dir string, newHashFunc snapshot.NewHashFunc) (map[string][]byte, error) {
	nsItr, err := r.dbHandle.getNamespaceIterator(collectionConfigNamespace)
	if err != nil {
		return nil, err
	}
	defer nsItr.Release()

	var numCollectionConfigs uint64 = 0
	var dataFileWriter *snapshot.FileWriter
	for nsItr.Next() {
		if err := nsItr.Error(); err != nil {
			return nil, errors.Wrap(err, "internal leveldb error while iterating for collection config history")
		}
		if numCollectionConfigs == 0 { // first iteration, create the data file
			dataFileWriter, err = snapshot.CreateFile(filepath.Join(dir, snapshotDataFileName), snapshotFileFormat, newHashFunc)
			if err != nil {
				return nil, err
			}
			defer dataFileWriter.Close()
		}
		if err := dataFileWriter.EncodeBytes(nsItr.Key()); err != nil {
			return nil, err
		}
		if err := dataFileWriter.EncodeBytes(nsItr.Value()); err != nil {
			return nil, err
		}
		numCollectionConfigs++
	}

	if dataFileWriter == nil {
		return nil, nil
	}

	dataHash, err := dataFileWriter.Done()
	if err != nil {
		return nil, err
	}
	metadataFileWriter, err := snapshot.CreateFile(filepath.Join(dir, snapshotMetadataFileName), snapshotFileFormat, newHashFunc)
	if err != nil {
		return nil, err
	}
	defer metadataFileWriter.Close()
	if err = metadataFileWriter.EncodeUVarint(numCollectionConfigs); err != nil {
		return nil, err
	}
	metadataHash, err := metadataFileWriter.Done()
	if err != nil {
		return nil, err
	}

	return map[string][]byte{
		snapshotDataFileName:     dataHash,
		snapshotMetadataFileName: metadataHash,
	}, nil
}

func prepareDBBatch(batch *batch, chaincodeCollConfigs map[string]*peer.CollectionConfigPackage, committingBlockNum uint64) error {
	for ccName, collConfig := range chaincodeCollConfigs {
		key := constructCollectionConfigKey(ccName)
		var configBytes []byte
		var err error
		if configBytes, err = proto.Marshal(collConfig); err != nil {
			return errors.WithStack(err)
		}
		batch.add(collectionConfigNamespace, key, committingBlockNum, configBytes)
	}
	return nil
}

func compositeKVToCollectionConfig(compositeKV *compositeKV) (*ledger.CollectionConfigInfo, error) {
	conf := &peer.CollectionConfigPackage{}
	if err := proto.Unmarshal(compositeKV.value, conf); err != nil {
		return nil, errors.Wrap(err, "error unmarshalling compositeKV to collection config")
	}
	return &ledger.CollectionConfigInfo{
		CollectionConfig:   conf,
		CommittingBlockNum: compositeKV.blockNum,
	}, nil
}

func constructCollectionConfigKey(chaincodeName string) string {
	return chaincodeName + "~collection" // collection config key as in version 1.2 and we continue to use this in order to be compatible with existing data
}

func extractPublicUpdates(stateUpdates ledger.StateUpdates) map[string][]*kvrwset.KVWrite {
	m := map[string][]*kvrwset.KVWrite{}
	for ns, updates := range stateUpdates {
		m[ns] = updates.PublicUpdates
	}
	return m
}


text:
use rand::Rng;
use rand::distributions::{Range, Sample};

use std::f64;
use std::usize;

use super::MCMove;
use super::select_molecule;

use sys::{EnergyCache, System};
use types::Vector3D;

/// Monte Carlo move for translating a molecule
pub struct Translate {
    /// Type of molecule to translate. `None` means all molecules.
    moltype: Option<u64>,
    /// Index of the molecule to translate
    molid: usize,
    /// New positions of the atom in the translated molecule
    newpos: Vec<Vector3D>,
    /// Maximum displacement value
    delta: f64,
    /// The maximum value must not exceed this value, if set
    maximum_cutoff: Option<f64>,
    /// Translation range for random number generation
    range: Range<f64>,
}

impl Translate {
    /// Create a new `Translate` move, with maximum displacement of `delta`.
    /// Translating all the molecules in the system.
    pub fn new(delta: f64) -> Translate {
        Translate::create(delta, None)
    }

    /// Create a new `Translate` move, with maximum displacement of `delta`.
    /// Translating only molecules with `moltype` type.
    pub fn with_moltype(delta: f64, moltype: u64) -> Translate {
        Translate::create(delta, Some(moltype))
    }

    /// Factorizing the constructors
    fn create(delta: f64, moltype: Option<u64>) -> Translate {
        assert!(delta > 0.0, "delta must be positive in Translate move");
        let delta = delta / f64::sqrt(3.0);
        Translate {
            moltype: moltype,
            molid: usize::MAX,
            newpos: Vec::new(),
            delta: delta,
            maximum_cutoff: None,
            range: Range::new(-delta, delta),
        }
    }
}

impl Default for Translate {
    fn default() -> Translate {
        Translate::new(1.0)
    }
}

impl MCMove for Translate {
    fn describe(&self) -> &str {
        "molecular translation"
    }

    fn setup(&mut self, system: &System) {
        // Limit the displacement range to the maximum cutoff
        self.maximum_cutoff = system.maximum_cutoff();
        if let Some(max) = self.maximum_cutoff {
            if self.delta > max {
                warn!(
                    "Changing the maximal displacement for Translate, \
                     because the interactions cutoff is too low."
                );
                self.delta = max
            }
        }
    }

    fn prepare(&mut self, system: &mut System, rng: &mut Box<Rng>) -> bool {
        if let Some(id) = select_molecule(system, self.moltype, rng) {
            self.molid = id;
        } else {
            warn!("Can not translate molecule: no molecule of this type in the system.");
            return false;
        }

        // Create random displacement vector.
        let delta =
            Vector3D::new(self.range.sample(rng), self.range.sample(rng), self.range.sample(rng));

        // Generate displaced coordinates
        // Note that this may move a particles' center-of-mass (com) out of
        // the cell. If the move is accepted, we have to wrap the com such
        // that it lies inside the cell.
        let indexes = system.molecule(self.molid).iter();
        self.newpos = system.particles().position[indexes].to_vec();
        for newpos in &mut self.newpos {
            *newpos += delta;
        }
        return true;
    }

    fn cost(&self, system: &System, beta: f64, cache: &mut EnergyCache) -> f64 {
        let idxes = system.molecule(self.molid).iter().collect::<Vec<_>>();
        let cost = cache.move_particles_cost(system, idxes, &self.newpos);
        return cost * beta;
    }

    fn apply(&mut self, system: &mut System) {
        {
            // Update positions.
            let indexes = system.molecule(self.molid).iter();
            let positions = &mut system.particles_mut().position[indexes];
            for (position, newpos) in izip!(positions, &self.newpos) {
                *position = *newpos;
            }
        }
        // Move molecule such that its center-of-mass is inside the simulation
        // cell. Note that particles of the molecule may still be outside the
        // cell, but that is not important.
        system.wrap_molecule(self.molid)
    }

    fn restore(&mut self, _: &mut System) {
        // Nothing to do.
    }

    fn update_amplitude(&mut self, scaling_factor: Option<f64>) {
        if let Some(s) = scaling_factor {
            if let Some(max) = self.maximum_cutoff {
                if (self.delta * s) > max {
                    warn_once!(
                        "Tried to increase the maximum amplitude for translations \
                         to more than the maximum cutoff -- ignoring."
                    );
                    return;
                }
            }

            self.delta *= s;
            self.range = Range::new(-self.delta, self.delta);
        };
    }
}


text:
import React from 'react'
import { provide, types } from 'ioc'
import { Link, Router } from '../routes'
import Component1 from '../components/component1'

const posts = [
  { slug: 'hello-world', title: 'Hello world' },
  { slug: 'another-blog-post', title: 'Another blog post' },
]

@provide({
  @types.func.isRequired
  Link,

  @types.object
  Router,
})
export default class extends React.Component {
  static async getInitialProps({ query, res }) {
    const post = posts.find(post => post.slug === query.slug)

    if (!post && res) {
      res.statusCode = 404
    }

    return { post }
  }

  render() {
    const { post } = this.props

    if (!post) return
Post not found

    return (

{post.title}

        <Component1 />

    )
  }
}


text:
{% extends "main_django.html" %}
{% load staticfiles %}
{% block title %}<title>Reset Your {{ PLATFORM_NAME }} Password</title>{% endblock %}
{% block main_vendor_js %}{% endblock %}
{% block headextra %}

{% endblock %}

{% block bodyclass %}view-passwordreset{% endblock %}

{% block body %}

Reset Your {{ PLATFORM_NAME }} Password

      {% if validlink %}

Password Reset Form

      <form role="form" id="passwordreset-form" method="post" data-remote="true" action="">{% csrf_token %}

We're sorry, {{ PLATFORM_NAME }} enrollment is not available in your region

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

The following errors occured while processing your registration:

You must complete all fields.

The two password fields didn't match.

We're sorry, our systems seem to be having trouble processing your password reset

Someone has been made aware of this issue. Please try again shortly. Please contact us about any concerns you have.

          Por favor ingrese su nueva contraseña dos veces para que podamos verificar que la ha escrito correctamente.

          Los campos requeridos se denotan con texto en negrita y un asterisco (*).

        <fieldset class="group group-form group-form-requiredinformation">
          <legend class="sr">Información Requerida</legend>

              Nuevo Password
              <input id="new_password1" type="password" name="new_password1" placeholder="*****" />

              Confirmar Nuevo Password
              <input id="new_password2" type="password" name="new_password2" placeholder="*****" />

        </fieldset>

          <button name="submit" type="submit" id="submit" class="action action-primary action-update">Cambiar Contraseña</button>

      </form>

      {% else %}

No se puedo restablecer su contraseña

El enlace para restablecer la contraseña no es válida, posiblemente porque el enlace ya ha sido utilizada. Por favor, vuelva a la página de inicio de sesión Iniciar Sesión e iniciar el proceso de restablecimiento de contraseña nuevamente.

      {% endif %}

Password Reset Help

Need Help?

View our help section for contact information and answers to commonly asked questions

{% endblock %}


text:
<!DOCTYPE html>

        <title>GeoExt WMS Capabilities Example</title>

        <link rel="stylesheet" type="text/css" href="../shared/example.css" />

WMS Capabilities Example

This example shows how to load a grid with data from a WMS
        capabilities document.  You can double-click on a row to see
        a map preview of the layer.

Note that the js is not minified so it is readable.
        See wmscapabilities.js.


text:
<?php

class Vote extends \Eloquent {
	protected $fillable = array('value', 'album_id', 'voter_id');

	public function album()
	{
		return $this->belongsTo('Album');
	}

	public function voter()
	{
		return $this->belongsTo('User');
	}
}


text:
using Mono.Addins;

namespace FSpot.Extensions
{
	public enum ViewMode {
		Unknown,
		Single,
		Library
	}

	// Defines a view mode condition, which determines which view mode is used.
	//
	// There are two valid values for the "mode" attribute, which
	// should be added to the Condition tag.
	//   - single: Single view mode.
	//   - library: Full F-Spot mode.
	//
	// This class contains a very nasty hack using a static initialization method
	// to keep track of the current view mode. This is (unfortunately) needed
	// because there is no way to get hold of a reference to the current window.
	public class ViewModeCondition : ConditionType
	{
		private delegate void ViewModeChangedHandler ();
		private static event ViewModeChangedHandler ViewModeChanged;

		private static ViewMode mode = ViewMode.Unknown;
		public static ViewMode Mode {
			get { return mode; }
			set {
				mode = value;

				if (ViewModeChanged != null)
					ViewModeChanged ();
			}
		}

		public ViewModeCondition ()
		{
			ViewModeChanged += delegate { NotifyChanged (); };
		}

		public override bool Evaluate (NodeElement conditionNode)
		{
			string val = conditionNode.GetAttribute ("mode");
			if (val.Length > 0) {
				foreach (string mode in val.Split(',')) {
					if (mode == "single" && Mode == ViewMode.Single) {
						return true;
					} else if (mode == "library" && Mode == ViewMode.Library) {
						return true;
					}
				}
			}
			return false;
		}
	}
}


text:
describe('Filter TEST', function() {

    describe('Filter.prototype.getType', function() {

        // Negative

        it('should return "none"', function() {
            var filter = new Filter('', []);

            expect(filter.getType()).toEqual('none');
        });

        // Positive

        it('should return "none"', function() {
            var filter = new Filter(Filter.NONE, []);

            expect(filter.getType()).toEqual('none');
        });

        it('should return "redemphasis"', function() {
            var filter = new Filter(Filter.REDEMPHASIS, []);

            expect(filter.getType()).toEqual('redemphasis');
        });

        it('should return "grayscale"', function() {
            var filter = new Filter(Filter.GRAYSCALE, []);

            expect(filter.getType()).toEqual('grayscale');
        });

        it('should return "reverse"', function() {
            var filter = new Filter(Filter.REVERSE, []);

            expect(filter.getType()).toEqual('reverse');
        });

        it('should return "noise"', function() {
            var filter = new Filter(Filter.NOISE, []);

            expect(filter.getType()).toEqual('noise');
        });

        it('should return "blur"', function() {
            var filter = new Filter(Filter.BLUR, []);

            expect(filter.getType()).toEqual('blur');
        });

    });

});


text:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var favicon = require('express-favicon');
var db = require('./models');
var passport = require('./config/passportJwt');
var tk = require('jsonwebtoken');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var sockets = require('./controllers/websockets')(io);

app.set('superSecret', process.env.JWT_SECRET);
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '/static')));
app.use(favicon(__dirname + '/static/favicon.ico'));

app.post('/api/signup', function(req, res) {
  db.user.findOrCreate({
    where: {email: req.body.email},
    defaults: {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      password: req.body.password
    }
  }).spread(function(user, created) {
    if (created) {
      var serializedUser = user.getWithNoPassword();
      var token = tk.sign(serializedUser, process.env.JWT_SECRET, {
        expiresIn: process.env.TOKEN_EXPIRATION_TIME // expires in 24 hours
      });
      res.send({
        success: true,
        message: 'User created!',
        token: token,
        user: serializedUser
      });
    } else {
      res.status(401).send({message: 'A user with that email address already exists'});
    }
  }).catch(function(error) {
    if (error.message) {
      res.status(500).send({message: error.message});
    } else {
      res.status(500).send({message: 'An error occurred. Try again.'});
    }
  });
});

app.post('/api/login', function(req, res) {
  db.user.find({ where: {email: req.body.email}}).then(function(user) {
    if (!user) {
      res.status(401).send({ success: false, message: 'Authentication failed. User not found.' });
    } {
      user.checkPassword(req.body.password, function(err, result) {
        if (err || !result) {
          res.status(401).send({ success: false, message: 'Authentication failed. Wrong password.' });
        } else {
          var token = tk.sign(user.getWithNoPassword(), process.env.JWT_SECRET, {
            expiresIn: process.env.TOKEN_EXPIRATION_TIME // expires in 24 hours
          });

          res.send({
            success: true,
            message: 'Authenticated!',
            token: token
          });
        }
      });
    }
  });
});

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'views/index.html'));
});

app.use('/api/users', passport.authenticate('jwt', {session: false}), require('./controllers/user'));
app.use('/api/questions', require('./controllers/question'));

// Requests that don't match any of the above should be sent to index
app.use(function(req, res) {
  res.sendFile(path.join(__dirname, 'views/index.html'));
});

http.listen(process.env.PORT || 3000);


text:
package eu.hyvar.feature.constraint.resource.hyconstraints.mopp;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * The HyconstraintsTokenResolverFactory class provides access to all generated
 * token resolvers. By giving the name of a defined token, the corresponding
 * resolve can be obtained. Despite the fact that this class is called
 * TokenResolverFactory is does NOT create new token resolvers whenever a client
 * calls methods to obtain a resolver. Rather, this class maintains a map of all
 * resolvers and creates each resolver at most once.
 */
public class HyconstraintsTokenResolverFactory implements eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolverFactory {

	private Map<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver> tokenName2TokenResolver;
	private Map<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver> featureName2CollectInTokenResolver;
	private static eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver defaultResolver = new eu.hyvar.feature.constraint.resource.hyconstraints.analysis.HyconstraintsDefaultTokenResolver();

	public HyconstraintsTokenResolverFactory() {
		tokenName2TokenResolver = new LinkedHashMap<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver>();
		featureName2CollectInTokenResolver = new LinkedHashMap<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver>();
		registerTokenResolver("QUOTED_34_34", new eu.hyvar.feature.constraint.resource.hyconstraints.analysis.HyexpressionQUOTED_34_34TokenResolver());
		registerTokenResolver("IDENTIFIER_TOKEN", new eu.hyvar.feature.constraint.resource.hyconstraints.analysis.HydatavalueIDENTIFIER_TOKENTokenResolver());
		registerTokenResolver("DATE", new eu.hyvar.feature.constraint.resource.hyconstraints.analysis.HydatavalueDATETokenResolver());
		registerTokenResolver("INTEGER_LITERAL", new eu.hyvar.feature.constraint.resource.hyconstraints.analysis.HydatavalueINTEGER_LITERALTokenResolver());
	}

	public eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver createTokenResolver(String tokenName) {
		return internalCreateResolver(tokenName2TokenResolver, tokenName);
	}

	public eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver createCollectInTokenResolver(String featureName) {
		return internalCreateResolver(featureName2CollectInTokenResolver, featureName);
	}

	protected boolean registerTokenResolver(String tokenName, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver resolver){
		return internalRegisterTokenResolver(tokenName2TokenResolver, tokenName, resolver);
	}

	protected boolean registerCollectInTokenResolver(String featureName, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver resolver){
		return internalRegisterTokenResolver(featureName2CollectInTokenResolver, featureName, resolver);
	}

	protected eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver deRegisterTokenResolver(String tokenName){
		return tokenName2TokenResolver.remove(tokenName);
	}

	private eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver internalCreateResolver(Map<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver> resolverMap, String key) {
		if (resolverMap.containsKey(key)){
			return resolverMap.get(key);
		} else {
			return defaultResolver;
		}
	}

	private boolean internalRegisterTokenResolver(Map<String, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver> resolverMap, String key, eu.hyvar.feature.constraint.resource.hyconstraints.IHyconstraintsTokenResolver resolver) {
		if (!resolverMap.containsKey(key)) {
			resolverMap.put(key,resolver);
			return true;
		}
		return false;
	}

}


text:
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {

    },

    onBtnClick: function (event) {
        var target = event.target;
        var shapeClassName = `cc.${target.name}Collider`;
        var nodePath = 'Canvas/root/' + target.parent.name;
        var collider = cc.find(nodePath).getComponent(shapeClassName);
        collider.enabled = !collider.enabled;

        var label = target.getChildByName('Label').getComponent(cc.Label);
        if (collider.enabled) {
            label.string = label.string.replace('Show', 'Hide');
        }
        else {
            label.string = label.string.replace('Hide', 'Show');
        }
    }
});


text:
Create your custom popin.
You can use this module with `browserify` and `require('popin')`.

### How it works
The plugin will look for all element who have the *js-popin* class and bind it to open a div with an id equal to the *data-target* or a content past in params.

### Example :
```html
<a href="#" class="js-popin" data-target="popin-alpha">test popin</a>

<div id="popin-alpha" class="popin">
    <div class="popin-header">
      <a class="js-popin-linkClose popin-header-linkClose" href="#" title="">Fermer X</a>
    </div>
    <div class="popin-content">
      <!-- popin content goes here -->
    </div>
</div>
```

### Installation
You can use the minified file in **lib/popin.js** for production or if you use Browserify, you just have to `require('popin')` and `npm i`

### Setup
Simply create a new instance of the **Popin** object.

```js
var Popin = require('popin');

document.addEventListener('DOMContentLoaded', function () {
  var popinInstance = new Popin();
  popinInstance.init();//all popins will instancied with default params
}, false);

```
#### CSS
Copy the styles in `styles/popin.scss` in your css or import the file in your scss.

#### Defaults parameters
var defaultParams = {
  overlay : true
}

#### Use custom init params
```js
var popinInstance = new Popin({
  overlay:false //to disable overlay for all popins
});
```

#### Defaults options
var defaultOptions = {
    className : "js-popin", //css class
    overlayVisible : true, //show the overlay for the popin
    closeButton : true //the popin have close button
  }

#### Use custom init options
You can use a custom class to trigger your popin, in the initialisation you just need to pass an object like this :
```js
popinInstance.init({
  className:'customClass', //element in DOM to trigger click
  overlayVisible : false, //disable the overlay for the popin
  closeButton:false, //if you don't need close button
  content:'<div><div class="popin-header"></div>popin ajax</div>',//popin content not in default DOM loaded,
  buttonSticky:true //to sticky the top of the popin at the top of the button
});
```
```html
<a href="#" class="customClass" data-target="popin-beta">test popin</a>
```

#### callback
You have 4 callback options
```js
popinInstance.init({
  beforeOpen: function() {}, //trigger before the openning
  afterOpen : function() {}, //trigger when the popin is visible in the screen
  beforeClose:function() {},  //trigger before the closing
  afterClose:function() {} //trigger when the popin is out of screen
});
```

## Support
This module uses classList who isn't available on IE9 and below, if you have to play around just use a polyfill :smile:


text:
package piramide.interaction.reasoner.creator.membershipgenerator.regionaccumulator;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

abstract class AbstractRegion {
	protected final Map<Number, Double> values2trends;
	protected final List<Number> orderedKeys;
	protected final double sumOfValues;

	AbstractRegion(Map<Number, Double> values2trends) {
		this.values2trends = values2trends;
		this.orderedKeys = Arrays.asList(values2trends.keySet().toArray(new Number[]{}));
		Collections.sort(this.orderedKeys, new Comparator<Number>() {
			@Override
			public int compare(Number number1, Number number2) {
				return new Double(number1.doubleValue()).compareTo(Double.valueOf(number2.doubleValue()));
			}
		});
		this.sumOfValues = calculateSumOfValues();
	}

	Map<Number, Double> getResults2trends() {
		return this.values2trends;
	}

	private double calculateSumOfValues() {
		double total = 0.0;

		for(double value : this.values2trends.values()){
			total += value;
		}
		return total;
	}

}


text:
KiddoPaint.Tools.Toolbox.Placer = function() {
    var tool = this;
    this.isDown = false;
    this.image = {};
    this.prevTool = {};
    this.size = {};

    this.mousedown = function(ev) {
        tool.isDown = true;
        tool.mousemove(ev);
    };

    this.mousemove = function(ev) {
        var ctx = tool.isDown ? KiddoPaint.Display.context : KiddoPaint.Display.previewContext;
        var alt = KiddoPaint.Current.modifiedAlt;
        var ctrl = KiddoPaint.Current.modifiedMeta;

        // https://stackoverflow.com/a/37388113
        function drawImageff(img, x, y, width, height, flip, flop, center) {
            ctx.save();
            if (typeof width === "undefined") width = img.width;
            if (typeof height === "undefined") height = img.height;
            if (typeof center === "undefined") center = false;
            // Set rotation point to center of image, instead of top/left
            if (center) {
                x -= width / 2;
                y -= height / 2;
            }

            // Set the origin to the center of the image
            ctx.translate(x + width / 2, y + height / 2);

            // Rotate the canvas around the origin
            //var rad = 2 * Math.PI - deg * Math.PI / 180;
            //context.rotate(rad);

            // Flip/flop the canvas
            ctx.scale((flip) ? -1 : 1, (flop) ? -1 : 1);

            // Draw the image
            ctx.drawImage(img, -width / 2, -height / 2);
            ctx.restore();
        }

        if (KiddoPaint.Current.modifiedRange != 0) {
            var scale = 1 + KiddoPaint.Current.modifiedRange / 100.0;
            var scaledImg = scaleImageDataCanvasAPI(tool.image, scale);
            drawImageff(scaledImg, ev._x, ev._y, tool.size.width * scale, tool.size.height * scale, KiddoPaint.Current.modifiedAlt, KiddoPaint.Current.modifiedMeta, true);
        } else {
            drawImageff(tool.image, ev._x, ev._y, tool.size.width, tool.size.height, KiddoPaint.Current.modifiedAlt, KiddoPaint.Current.modifiedMeta, true);
        }
    };

    this.mouseup = function(ev) {
        if (tool.isDown) {
            tool.isDown = false;
            tool.image = {};
            KiddoPaint.Display.saveMain();
            KiddoPaint.Current.tool = tool.prevTool;
            reset_ranges();
            tool.prevTool = {};
            tool.size = {};
        }
    };
};
KiddoPaint.Tools.Placer = new KiddoPaint.Tools.Toolbox.Placer();


text:
package org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.user.node;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.mode.manager.cluster.coordinator.registry.status.StatusNode;

/**
 * User status node.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class UserStatusNode {

    private static final String PRIVILEGE_NODES = "privilege_nodes";

    /**
     * Get privilege node path.
     *
     * @return privilege node path
     */
    public static String getPrivilegeNodePath() {
        return String.join("/", "", StatusNode.ROOT_NODE, PRIVILEGE_NODES);
    }
}


text:
def longest_substring(s):
    start = end = 0
    longest = ''
    pool = set()

    while end < len(s):
        char = s[end]

        if char not in pool:
            pool.add(char)

            if len(s[start:end+1]) > len(longest):
                longest = s[start:end+1]

            end += 1
            continue

        while start < end and s[start] != char:
            pool.remove(s[start])
            start += 1

        start += 1
        end += 1

    return longest

result = longest_substring('')
assert result == '', result

result = longest_substring('ABCBDX')
assert result == 'CBDX', result


text:
package com.google.devtools.build.android.desugar.langmodel;

import static com.google.common.truth.Truth.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link ClassMemberKey}. */
@RunWith(JUnit4.class)
public class ClassMemberKeyTest {

  @Test
  public void fieldKey_bridgeOfInstanceRead() {
    FieldKey fieldKey =
        FieldKey.create(ClassName.create("a/b/Charlie"), "instanceFieldOfLongType", "J");
    assertThat(fieldKey.bridgeOfInstanceRead())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"),
                "instanceFieldOfLongType$bridge_getter",
                "(La/b/Charlie;)J"));
  }

  @Test
  public void fieldKey_bridgeOfInstanceWrite() {

    FieldKey fieldKey =
        FieldKey.create(ClassName.create("a/b/Charlie"), "instanceFieldOfLongType", "J");
    assertThat(fieldKey.bridgeOfInstanceWrite())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"),
                "instanceFieldOfLongType$bridge_setter",
                "(La/b/Charlie;J)J"));
  }

  @Test
  public void fieldKey_bridgeOfStaticRead() {
    FieldKey fieldKey =
        FieldKey.create(ClassName.create("a/b/Charlie"), "staticFieldOfLongType", "J");
    assertThat(fieldKey.bridgeOfStaticRead())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"), "staticFieldOfLongType$bridge_getter", "()J"));
  }

  @Test
  public void fieldKey_bridgeOfStaticWrite() {
    FieldKey fieldKey =
        FieldKey.create(ClassName.create("a/b/Charlie"), "staticFieldOfLongType", "J");
    assertThat(fieldKey.bridgeOfStaticWrite())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"), "staticFieldOfLongType$bridge_setter", "(J)J"));
  }

  @Test
  public void methodKey_bridgeOfClassInstanceMethod() {
    MethodKey methodKey = MethodKey.create(ClassName.create("a/b/Charlie"), "twoLongSum", "(JJ)J");
    assertThat(methodKey.bridgeOfClassInstanceMethod())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"), "twoLongSum$bridge", "(La/b/Charlie;JJ)J"));
  }

  @Test
  public void methodKey_bridgeOfClassStaticMethod() {
    MethodKey methodKey = MethodKey.create(ClassName.create("a/b/Charlie"), "twoLongSum", "(JJ)J");
    assertThat(methodKey.bridgeOfClassStaticMethod())
        .isEqualTo(MethodKey.create(ClassName.create("a/b/Charlie"), "twoLongSum$bridge", "(JJ)J"));
  }

  @Test
  public void methodKey_bridgeOfConstructor() {
    MethodKey methodKey = MethodKey.create(ClassName.create("a/b/Charlie"), "<init>", "(JJ)V");
    assertThat(methodKey.bridgeOfConstructor(ClassName.create("a/b/Charlie$NestCC")))
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"), "<init>", "(JJLa/b/Charlie$NestCC;)V"));
  }

  @Test
  public void methodKey_substituteOfInterfaceInstanceMethod() {
    MethodKey methodKey =
        MethodKey.create(ClassName.create("a/b/Charlie"), "instanceInstanceMethod", "(JJ)J");
    assertThat(methodKey.substituteOfInterfaceInstanceMethod())
        .isEqualTo(
            MethodKey.create(
                ClassName.create("a/b/Charlie"), "instanceInstanceMethod", "(La/b/Charlie;JJ)J"));
  }

  @Test
  public void methodKey_substituteOfInterfaceStaticMethod() {

    MethodKey methodKey =
        MethodKey.create(ClassName.create("a/b/Charlie"), "instanceStaticMethod", "(JJ)J");
    assertThat(methodKey.substituteOfInterfaceStaticMethod())
        .isEqualTo(
            MethodKey.create(ClassName.create("a/b/Charlie"), "instanceStaticMethod", "(JJ)J"));
  }
}