text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-parent</artifactId>
        <version>2.6.0</version>
        <relativePath>../../parent</relativePath>
    </parent>

    <artifactId>camel-spring-ws</artifactId>
    <packaging>bundle</packaging>
    <name>Camel :: Spring Web Services</name>
    <description>Camel support for Spring Web Services</description>

    <properties>
        <camel.osgi.export.pkg>org.apache.camel.component.spring.ws.*</camel.osgi.export.pkg>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>${spring-ws-version}</version>
            <!-- spring-webmvc is only used by Spring 2.5 -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-webmvc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-support</artifactId>
            <version>${spring-ws-version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-servlet_2.5_spec</artifactId>
            <version>1.2</version>
            <scope>provided</scope>
        </dependency>

        <!-- these is needed by JDK 1.5 -->
        <dependency>
            <groupId>javax.xml.soap</groupId>
            <artifactId>saaj-api</artifactId>
            <version>1.3</version>
            <exclusions>
                <exclusion>
                    <!-- exclude dependency on javax.activation due to sun binary license
                        restrictions geronimo-activation dependency directly below provides a workaround -->
                    <groupId>javax.activation</groupId>
                    <artifactId>activation</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <!-- workaround for saaj dependency on javax.activation -->
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-activation_1.1_spec</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.messaging.saaj</groupId>
            <artifactId>saaj-impl</artifactId>
            <version>1.3.2</version>
            <scope>provided</scope>
        </dependency>

        <!-- testing -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jaxb</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.javacrumbs</groupId>
            <artifactId>spring-ws-test</artifactId>
            <version>0.19</version>
            <exclusions>
                <exclusion>
                    <groupId>xmlunit</groupId>
                    <artifactId>xmlunit</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <profiles>
        <profile>
            <id>spring-2.x</id>
            <dependencies>
                <!-- need spring-webmvc when using Spring 2.x -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-webmvc</artifactId>
                    <version>${spring-version}</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

</project>


text:
var dotBox = dotBox || {};
dotBox.ai = dotBox.ai || {};

dotBox.ai.SingleBoxCloser = (function () {

    var util = dotBox.utility,
        SingleBoxCloser;

    SingleBoxCloser = function SingleBoxCloser(playerIndex, gameEngine) {

        if (!(this instanceof SingleBoxCloser)) {
            //Pass arguments to this constructor.
            return SingleBoxCloser.apply(new SingleBoxCloser(), arguments);
        }

        //noinspection JSUnusedGlobalSymbols
        this.playerIndex = playerIndex;
        this.gameEngine = gameEngine;
    };

    util.inherit(SingleBoxCloser, dotBox.ai.AvoidThirdSide);

    SingleBoxCloser.prototype.move = function move() {

        var closeableBoxes,
            rndClosedBox;

        closeableBoxes = dotBox.ai.utility.findCloseableBoxes(this.gameEngine);

        if (closeableBoxes.length > 0) {

            rndClosedBox = util.getRandomItem(closeableBoxes);
            return rndClosedBox.openLine;

        }

        return SingleBoxCloser.uber.move.apply(this);

    };

    return SingleBoxCloser;

}());

redpajama_set_name: RedPajamaGithub


text:
class Array
  attr_accessor :baseIndex
  alias init initialize
  alias getitem []
  alias setitem []=

  def initialize(size = 0, baseIndex = 0)
    init(size, nil)
    @baseIndex = baseIndex
  end

  def length=(value)
    tmp = Array.new(value, nil)

    for i in 0...[length, value].min
      tmp.setitem(i, getitem(i))
    end

    clear
    setitem(value - 1, nil) if value > 0

    for i in 0...tmp.length
      setitem(i, tmp.getitem(i))
    end
  end

  protected :getitem, :setitem

  def getOffset(index)
    @baseIndex = 0 if @baseIndex.nil?
    raise IndexError unless (@baseIndex...@baseIndex + length) === index
    index - @baseIndex
  end

  def [](index)
    getitem(getOffset(index))
  end

  def []=(index, value)
    setitem(getOffset(index), value)
  end
end


text:
namespace Photon.Realtime
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using ExitGames.Client.Photon;

    #if SUPPORTED_UNITY
    using UnityEngine;
    #endif
    #if SUPPORTED_UNITY || NETFX_CORE
    using Hashtable = ExitGames.Client.Photon.Hashtable;
    using SupportClass = ExitGames.Client.Photon.SupportClass;
    #endif

    ///
    /// Summarizes a "player" within a room, identified (in that room) by ID (or "actorNumber").
    ///
    /// <remarks>
    /// Each player has a actorNumber, valid for that room. It's -1 until assigned by server (and client logic).
    /// </remarks>
    public class Player
    {
        ///
        /// Used internally to identify the masterclient of a room.
        ///
        protected internal Room RoomReference { get; set; }

        /// Backing field for property.
        private int actorNumber = -1;

        /// Identifier of this player in current room. Also known as: actorNumber or actorNumber. It's -1 outside of rooms.
        /// <remarks>The ID is assigned per room and only valid in that context. It will change even on leave and re-join. IDs are never re-used per room.</remarks>
        public int ActorNumber
        {
            get { return this.actorNumber; }
        }

        /// Only one player is controlled by each client. Others are not local.
        public readonly bool IsLocal;

        public bool HasRejoined
        {
            get; internal set;
        }

        /// Background field for nickName.
		private string nickName = string.Empty;

        /// Non-unique nickname of this player. Synced automatically in a room.
        /// <remarks>
        /// A player might change his own playername in a room (it's only a property).
        /// Setting this value updates the server and other players (using an operation).
        /// </remarks>
        public string NickName
        {
            get
            {
                return this.nickName;
            }
            set
            {
                if (!string.IsNullOrEmpty(this.nickName) && this.nickName.Equals(value))
                {
                    return;
                }

                this.nickName = value;

                // update a room, if we changed our nickName locally
                if (this.IsLocal)
                {
                    this.SetPlayerNameProperty();
                }
            }
        }

        /// UserId of the player, available when the room got created with RoomOptions.PublishUserId = true.
        /// <remarks>Useful for <see cref="LoadBalancingClient.OpFindFriends"/> and blocking slots in a room for expected players (e.g. in <see cref="LoadBalancingClient.OpCreateRoom"/>).</remarks>
        public string UserId { get; internal set; }

        ///
        /// True if this player is the Master Client of the current room.
        ///
        public bool IsMasterClient
        {
            get
            {
                if (this.RoomReference == null)
                {
                    return false;
                }

                return this.ActorNumber == this.RoomReference.MasterClientId;
            }
        }

        /// If this player is active in the room (and getting events which are currently being sent).
        /// <remarks>
        /// Inactive players keep their spot in a room but otherwise behave as if offline (no matter what their actual connection status is).
        /// The room needs a PlayerTTL != 0. If a player is inactive for longer than PlayerTTL, the server will remove this player from the room.
        /// For a client "rejoining" a room, is the same as joining it: It gets properties, cached events and then the live events.
        /// </remarks>
        public bool IsInactive { get; protected internal set; }

        /// Read-only cache for custom properties of player. Set via Player.SetCustomProperties.
        /// <remarks>
        /// Don't modify the content of this Hashtable. Use SetCustomProperties and the
        /// properties of this class to modify values. When you use those, the client will
        /// sync values with the server.
        /// </remarks>
        /// <see cref="SetCustomProperties"/>
        public Hashtable CustomProperties { get; set; }

        /// Can be used to store a reference that's useful to know "by player".
        /// <remarks>Example: Set a player's character as Tag by assigning the GameObject on Instantiate.</remarks>
        public object TagObject;

        ///
        /// Creates a player instance.
        /// To extend and replace this Player, override LoadBalancingPeer.CreatePlayer().
        ///
        /// <param name="nickName">NickName of the player (a "well known property").</param>
        /// <param name="actorNumber">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param>
        /// <param name="isLocal">If this is the local peer's player (or a remote one).</param>
        protected internal Player(string nickName, int actorNumber, bool isLocal) : this(nickName, actorNumber, isLocal, null)
        {
        }

        ///
        /// Creates a player instance.
        /// To extend and replace this Player, override LoadBalancingPeer.CreatePlayer().
        ///
        /// <param name="nickName">NickName of the player (a "well known property").</param>
        /// <param name="actorNumber">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param>
        /// <param name="isLocal">If this is the local peer's player (or a remote one).</param>
        /// <param name="playerProperties">A Hashtable of custom properties to be synced. Must use String-typed keys and serializable datatypes as values.</param>
        protected internal Player(string nickName, int actorNumber, bool isLocal, Hashtable playerProperties)
        {
            this.IsLocal = isLocal;
            this.actorNumber = actorNumber;
            this.NickName = nickName;

            this.CustomProperties = new Hashtable();
            this.InternalCacheProperties(playerProperties);
        }

        ///
        /// Get a Player by ActorNumber (Player.ID).
        ///
        /// <param name="id">ActorNumber of the a player in this room.</param>
        /// <returns>Player or null.</returns>
        public Player Get(int id)
        {
            if (this.RoomReference == null)
            {
                return null;
            }

            return this.RoomReference.GetPlayer(id);
        }

        /// Gets this Player's next Player, as sorted by ActorNumber (Player.ID). Wraps around.
        /// <returns>Player or null.</returns>
        public Player GetNext()
        {
            return GetNextFor(this.ActorNumber);
        }

        /// Gets a Player's next Player, as sorted by ActorNumber (Player.ID). Wraps around.
        /// <remarks>Useful when you pass something to the next player. For example: passing the turn to the next player.</remarks>
        /// <param name="currentPlayer">The Player for which the next is being needed.</param>
        /// <returns>Player or null.</returns>
        public Player GetNextFor(Player currentPlayer)
        {
            if (currentPlayer == null)
            {
                return null;
            }
            return GetNextFor(currentPlayer.ActorNumber);
        }

        /// Gets a Player's next Player, as sorted by ActorNumber (Player.ID). Wraps around.
        /// <remarks>Useful when you pass something to the next player. For example: passing the turn to the next player.</remarks>
        /// <param name="currentPlayerId">The ActorNumber (Player.ID) for which the next is being needed.</param>
        /// <returns>Player or null.</returns>
        public Player GetNextFor(int currentPlayerId)
        {
            if (this.RoomReference == null || this.RoomReference.Players == null || this.RoomReference.Players.Count < 2)
            {
                return null;
            }

            Dictionary<int, Player> players = this.RoomReference.Players;
            int nextHigherId = int.MaxValue;    // we look for the next higher ID
            int lowestId = currentPlayerId;     // if we are the player with the highest ID, there is no higher and we return to the lowest player's id

            foreach (int playerid in players.Keys)
            {
                if (playerid < lowestId)
                {
                    lowestId = playerid;        // less than any other ID (which must be at least less than this player's id).
                }
                else if (playerid > currentPlayerId && playerid < nextHigherId)
                {
                    nextHigherId = playerid;    // more than our ID and less than those found so far.
                }
            }

            //UnityEngine.Debug.LogWarning("Debug. " + currentPlayerId + " lower: " + lowestId + " higher: " + nextHigherId + " ");
            //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(currentPlayerId));
            //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(lowestId));
            //if (nextHigherId != int.MaxValue) UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(nextHigherId));
            return (nextHigherId != int.MaxValue) ? players[nextHigherId] : players[lowestId];
        }

        /// Caches properties for new Players or when updates of remote players are received. Use SetCustomProperties() for a synced update.
        /// <remarks>
        /// This only updates the CustomProperties and doesn't send them to the server.
        /// Mostly used when creating new remote players, where the server sends their properties.
        /// </remarks>
        protected internal virtual void InternalCacheProperties(Hashtable properties)
        {
            if (properties == null || properties.Count == 0 || this.CustomProperties.Equals(properties))
            {
                return;
            }

            if (properties.ContainsKey(ActorProperties.PlayerName))
            {
                string nameInServersProperties = (string)properties[ActorProperties.PlayerName];
                if (nameInServersProperties != null)
                {
                    if (this.IsLocal)
                    {
                        // the local playername is different than in the properties coming from the server
                        // so the local nickName was changed and the server is outdated -> update server
                        // update property instead of using the outdated nickName coming from server
                        if (!nameInServersProperties.Equals(this.nickName))
                        {
                            this.SetPlayerNameProperty();
                        }
                    }
                    else
                    {
                        this.NickName = nameInServersProperties;
                    }
                }
            }
            if (properties.ContainsKey(ActorProperties.UserId))
            {
                this.UserId = (string)properties[ActorProperties.UserId];
            }
            if (properties.ContainsKey(ActorProperties.IsInactive))
            {
                this.IsInactive = (bool)properties[ActorProperties.IsInactive]; //TURNBASED new well-known propery for players
            }

            this.CustomProperties.MergeStringKeys(properties);
            this.CustomProperties.StripKeysWithNullValues();
        }

        ///
        /// Brief summary string of the Player: ActorNumber and NickName
        ///
        public override string ToString()
        {
            return string.Format("#{0:00} '{1}'",this.ActorNumber, this.NickName);
        }

        ///
        /// String summary of the Player: player.ID, name and all custom properties of this user.
        ///
        /// <remarks>
        /// Use with care and not every frame!
        /// Converts the customProperties to a String on every single call.
        /// </remarks>
        public string ToStringFull()
        {
            return string.Format("#{0:00} '{1}'{2} {3}", this.ActorNumber, this.NickName, this.IsInactive ? " (inactive)" : "", this.CustomProperties.ToStringFull());
        }

        ///
        /// If players are equal (by GetHasCode, which returns this.ID).
        ///
        public override bool Equals(object p)
        {
            Player pp = p as Player;
            return (pp != null && this.GetHashCode() == pp.GetHashCode());
        }

        ///
        /// Accompanies Equals, using the ID (actorNumber) as HashCode to return.
        ///
        public override int GetHashCode()
        {
            return this.ActorNumber;
        }

        ///
        /// Used internally, to update this client's playerID when assigned (doesn't change after assignment).
        ///
        protected internal void ChangeLocalID(int newID)
        {
            if (!this.IsLocal)
            {
                //Debug.LogError("ERROR You should never change Player IDs!");
                return;
            }

            this.actorNumber = newID;
        }

        ///
        /// Updates and synchronizes this Player's Custom Properties. Optionally, expectedProperties can be provided as condition.
        ///
        /// <remarks>
        /// Custom Properties are a set of string keys and arbitrary values which is synchronized
        /// for the players in a Room. They are available when the client enters the room, as
        /// they are in the response of OpJoin and OpCreate.
        ///
        /// Custom Properties either relate to the (current) Room or a Player (in that Room).
        ///
        /// Both classes locally cache the current key/values and make them available as
        /// property: CustomProperties. This is provided only to read them.
        /// You must use the method SetCustomProperties to set/modify them.
        ///
        /// Any client can set any Custom Properties anytime (when in a room).
        /// It's up to the game logic to organize how they are best used.
        ///
        /// You should call SetCustomProperties only with key/values that are new or changed. This reduces
        /// traffic and performance.
        ///
        /// Unless you define some expectedProperties, setting key/values is always permitted.
        /// In this case, the property-setting client will not receive the new values from the server but
        /// instead update its local cache in SetCustomProperties.
        ///
        /// If you define expectedProperties, the server will skip updates if the server property-cache
        /// does not contain all expectedProperties with the same values.
        /// In this case, the property-setting client will get an update from the server and update it's
        /// cached key/values at about the same time as everyone else.
        ///
        /// The benefit of using expectedProperties can be only one client successfully sets a key from
        /// one known value to another.
        /// As example: Store who owns an item in a Custom Property "ownedBy". It's 0 initally.
        /// When multiple players reach the item, they all attempt to change "ownedBy" from 0 to their
        /// actorNumber. If you use expectedProperties {"ownedBy", 0} as condition, the first player to
        /// take the item will have it (and the others fail to set the ownership).
        ///
        /// Properties get saved with the game state for Turnbased games (which use IsPersistent = true).
        /// </remarks>
        /// <param name="propertiesToSet">Hashtable of Custom Properties to be set. </param>
        /// <param name="expectedValues">If non-null, these are the property-values the server will check as condition for this update.</param>
        /// <param name="webFlags">Defines if this SetCustomProperties-operation gets forwarded to your WebHooks. Client must be in room.</param>
        /// <returns>
        /// False if propertiesToSet is null or empty or have zero string keys.
        /// True in offline mode even if expectedProperties or webFlags are used.
        /// If not in a room, returns true if local player and expectedValues and webFlags are null.
        /// (Use this to cache properties to be sent when joining a room).
        /// Otherwise, returns if this operation could be sent to the server.
        /// </returns>
        public bool SetCustomProperties(Hashtable propertiesToSet, Hashtable expectedValues = null, WebFlags webFlags = null)
        {
            if (propertiesToSet == null || propertiesToSet.Count == 0)
            {
                return false;
            }

            Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable;

            if (this.RoomReference != null)
            {
                if (this.RoomReference.IsOffline)
                {
                    if (customProps.Count == 0)
                    {
                        return false;
                    }
                    this.CustomProperties.Merge(customProps);
                    this.CustomProperties.StripKeysWithNullValues();
                    // invoking callbacks
                    this.RoomReference.LoadBalancingClient.InRoomCallbackTargets.OnPlayerPropertiesUpdate(this, customProps);
                    return true;
                }
                else
                {
                    Hashtable customPropsToCheck = expectedValues.StripToStringKeys() as Hashtable;

                    // send (sync) these new values if in online room
                    return this.RoomReference.LoadBalancingClient.OpSetPropertiesOfActor(this.actorNumber, customProps, customPropsToCheck, webFlags);
                }
            }
            if (this.IsLocal)
            {
                if (customProps.Count == 0)
                {
                    return false;
                }
                if (expectedValues == null && webFlags == null)
                {
                    this.CustomProperties.Merge(customProps);
                    this.CustomProperties.StripKeysWithNullValues();
                    return true;
                }
            }

            return false;
        }

        /// Uses OpSetPropertiesOfActor to sync this player's NickName (server is being updated with this.NickName).
        private bool SetPlayerNameProperty()
        {
            if (this.RoomReference != null && !this.RoomReference.IsOffline)
            {
                Hashtable properties = new Hashtable();
                properties[ActorProperties.PlayerName] = this.nickName;
                return this.RoomReference.LoadBalancingClient.OpSetPropertiesOfActor(this.ActorNumber, properties);
            }

            return false;
        }
    }
}


text:
package com.cloud.storage.datastore;

import com.cloud.engine.subsystem.api.storage.CopyCommandResult;
import com.cloud.engine.subsystem.api.storage.CreateCmdResult;
import com.cloud.engine.subsystem.api.storage.DataMotionService;
import com.cloud.engine.subsystem.api.storage.DataObject;
import com.cloud.framework.async.AsyncCallbackDispatcher;
import com.cloud.framework.async.AsyncCompletionCallback;
import com.cloud.framework.async.AsyncRpcContext;
import com.cloud.legacymodel.exceptions.CloudRuntimeException;
import com.cloud.legacymodel.exceptions.ConcurrentOperationException;
import com.cloud.legacymodel.exceptions.NoTransitionException;
import com.cloud.legacymodel.storage.ObjectInDataStoreStateMachine;
import com.cloud.legacymodel.storage.ObjectInDataStoreStateMachine.Event;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class DataObjectManagerImpl implements DataObjectManager {
    private static final Logger s_logger = LoggerFactory.getLogger(DataObjectManagerImpl.class);
    protected long waitingTime = 1800; // half an hour
    protected long waitingRetries = 10;
    @Inject
    ObjectInDataStoreManager objectInDataStoreMgr;
    @Inject
    DataMotionService motionSrv;

    @Override
    public void update(final DataObject data, final String path, final Long size) {
        throw new CloudRuntimeException("not implemented");
    }

    @Override
    public void copyAsync(final DataObject srcData, final DataObject destData, final AsyncCompletionCallback<CreateCmdResult> callback) {
        try {
            objectInDataStoreMgr.update(destData, ObjectInDataStoreStateMachine.Event.CopyingRequested);
        } catch (final NoTransitionException | ConcurrentOperationException e) {
            s_logger.debug("failed to change state", e);
            try {
                objectInDataStoreMgr.update(destData, ObjectInDataStoreStateMachine.Event.OperationFailed);
            } catch (final Exception e1) {
                s_logger.debug("failed to further change state to OperationFailed", e1);
            }
            final CreateCmdResult res = new CreateCmdResult(null, null);
            res.setResult("Failed to change state: " + e.toString());
            callback.complete(res);
        }

        final CopyContext<CreateCmdResult> anotherCall = new CopyContext<>(callback, srcData, destData);
        final AsyncCallbackDispatcher<DataObjectManagerImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
        caller.setCallback(caller.getTarget().copyCallback(null, null)).setContext(anotherCall);

        motionSrv.copyAsync(srcData, destData, caller);
    }

    protected Void copyCallback(final AsyncCallbackDispatcher<DataObjectManagerImpl, CopyCommandResult> callback, final CopyContext<CreateCmdResult> context) {
        final CopyCommandResult result = callback.getResult();
        final DataObject destObj = context.destObj;

        if (result.isFailed()) {
            try {
                objectInDataStoreMgr.update(destObj, Event.OperationFailed);
            } catch (final NoTransitionException e) {
                s_logger.debug("Failed to update copying state", e);
            } catch (final ConcurrentOperationException e) {
                s_logger.debug("Failed to update copying state", e);
            }
            final CreateCmdResult res = new CreateCmdResult(null, null);
            res.setResult(result.getResult());
            context.getParentCallback().complete(res);
        }

        try {
            objectInDataStoreMgr.update(destObj, ObjectInDataStoreStateMachine.Event.OperationSuccessed);
        } catch (final NoTransitionException | ConcurrentOperationException e) {
            s_logger.debug("Failed to update copying state: ", e);
            try {
                objectInDataStoreMgr.update(destObj, ObjectInDataStoreStateMachine.Event.OperationFailed);
            } catch (final Exception e1) {
                s_logger.debug("failed to further change state to OperationFailed", e1);
            }
            final CreateCmdResult res = new CreateCmdResult(null, null);
            res.setResult("Failed to update copying state: " + e.toString());
            context.getParentCallback().complete(res);
        }
        final CreateCmdResult res = new CreateCmdResult(result.getPath(), null);
        context.getParentCallback().complete(res);
        return null;
    }

    class CopyContext<T> extends AsyncRpcContext<T> {
        DataObject destObj;
        DataObject srcObj;

        public CopyContext(final AsyncCompletionCallback<T> callback, final DataObject srcObj, final DataObject destObj) {
            super(callback);
            this.srcObj = srcObj;
            this.destObj = destObj;
        }
    }
}


text:
package com.siyeh.ig.numeric;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiArrayInitializerExpression;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ExpressionUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Bas Leijdekkers
 */
class ConvertOctalLiteralsToDecimalsFix extends InspectionGadgetsFix {

  @Nls
  @NotNull
  @Override
  public String getFamilyName() {
    return InspectionGadgetsBundle.message("convert.octal.literals.to.decimal.literals.quickfix");
  }

  @Override
  protected void doFix(Project project, ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (!(element instanceof PsiArrayInitializerExpression)) {
      return;
    }
    final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)element;
    for (PsiExpression initializer : arrayInitializerExpression.getInitializers()) {
      initializer = PsiUtil.skipParenthesizedExprDown(initializer);
      if (!(initializer instanceof PsiLiteralExpression)) {
        continue;
      }
      final PsiLiteralExpression literal = (PsiLiteralExpression)initializer;
      if (!ExpressionUtils.isOctalLiteral(literal)) {
        continue;
      }
      ConvertOctalLiteralToDecimalFix.replaceWithDecimalLiteral(literal);
    }
  }
}


text:
package com.intellij.execution.impl.statistics;

import com.intellij.internal.statistic.eventLog.events.EventField;
import com.intellij.internal.statistic.eventLog.events.EventFields;
import com.intellij.internal.statistic.service.fus.collectors.FeatureUsageCollectorExtension;

import java.util.List;

public class RunConfigurationTypeLanguageExtension implements FeatureUsageCollectorExtension {
  @Override
  public String getGroupId() {
    return RunConfigurationTypeUsagesCollector.GROUP.getId();
  }

  @Override
  public String getEventId() {
    return RunConfigurationTypeUsagesCollector.CONFIGURED_IN_PROJECT;
  }

  @Override
  public List<EventField> getExtensionFields() {
    return List.of(EventFields.Language, RunConfigurationUsageTriggerCollector.ALTERNATIVE_JRE_VERSION);
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Martin Devera</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="css/creative.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Martin Devera

                        About

                        Portfolio

                        Contact

Martin Devera

Welcome to my website

                About me

Hi there!

I graduated in August 2017 from the University of Washington earning a Bachelor of Arts in Earth and Space Science and a minor in Computer Science and Software Engineering. I have a great interest in the environment, technology, and data. I worked as a Student Technology Assistant for the Communications Department at UW from May 2015 to June 2017. In September 2016 I earned Associate Level Certification as an AWS Solutions Architect. Below are some of the projects I've been working on.

                    Projects

                                    Web Development with PHP and D3.

                                    Uses PHP to store cookies, login, and data about a user's todo list. Todo list weights tasks with points based on due date, importance, and personal gratification of performing the task. Creates a data visualization of the points accumulated after completing tasks. Future work includes creating a game to spend the accumulated points.

                                    GIS - Goldfinch Breeding Grounds in Oregon

                                   Used GIS to generate maps of the American Goldfinch's breeding grounds. Performed different analyses including boolean raster manipulations to find relationships and patterns such as proximity to highways, certain vegetation, and streams.

                                    Computer Simulation of Epidemic Modeling in Python

                                    Led a team to research, design, develop, and present a computer simulation of an epidemic spreading across a school campus based on their class schedule and campus layout. Used agent-based modeling with discrete-space scheduled walkers. Developed in Python.

                                    Interactive Tsunami History Visualization

                                    Uses the D3.js framework to display data about tsunami's around the world. Has adjustable sliders to interactively select a subset of the data based on year, earthquake magnitude, and cause of tsunami.

                                    Huky Wushu Team - Web Development

                                    Led a team to update the website for the Husky Wushu Team. Created a responsive, mobile friendly UI using Bootstrap. Used PHP to create contact messages in-site.

                                    Web Development

                                    i467 Studios

Let's Get In Touch!

Contact Me

jmdevera21@gmail.com


text:
from oslo_config import cfg
from oslo_log import log as logging
from pysnmp.entity.engine import SnmpEngine
from pysnmp.hlapi.asyncore.sync.compat.ntforg import sendNotification
from pysnmp.hlapi.asyncore.transport import UdpTransportTarget
from pysnmp.hlapi.auth import CommunityData
from pysnmp.hlapi.context import ContextData
from pysnmp.proto.rfc1902 import OctetString
from pysnmp.smi.rfc1902 import NotificationType
from pysnmp.smi.rfc1902 import ObjectIdentity
import re

from vitrage.common.constants import VertexProperties as VProps
from vitrage.notifier.plugins.snmp.base import SnmpSenderBase
from vitrage.utils.file import load_yaml_file

CONF = cfg.CONF
LOG = logging.getLogger(__name__)

# TODO(annarez): change NA to N/A
NA = 'NA'
SNMP_TREE = 'snmp_tree'
SEVERITY_MAPPING = 'severity_mapping'
OID = 'oid'
NEXT = 'next'
WITH_VALS = 'with_values'
SEVERITY = 'SEVERITY'
ALARM_OID = 'ALARM_OID'
IP_PAT = re.compile(r'\d+\.\d+\.\d+\.\d+')
PORT_PAT = re.compile(r'\d+')

class SnmpSender(SnmpSenderBase):
    def __init__(self):
        self.hosts = load_yaml_file(CONF.snmp.consumers, True)
        self.oid_tree = load_yaml_file(CONF.snmp.oid_tree, True)
        self.alarm_mapping = \
            load_yaml_file(CONF.snmp.alarm_oid_mapping, True)
        self.oids, self.var_fields = self._build_oids()

    def send_snmp(self, alarm_data):

        alert_details, alert_severity_oid = self._get_details(alarm_data)

        if alert_details:
            alarm_oid = \
                self._get_alert_oid(alert_details[OID], alert_severity_oid)
            if not alarm_oid:
                return
            for host in self.hosts:
                self._send_snmp_trap(host,
                                     self._get_var_binds(alarm_data),
                                     alarm_oid)
        else:
            LOG.info('Vitrage snmp Info: Unrecognized alarm. Alarm type: %s',
                     alarm_data[VProps.NAME])

    def _get_details(self, alarm_data):

        if not (self.hosts and self.alarm_mapping and
                self.oids and self.var_fields):
            LOG.error('Vitrage snmp Error: definitions is '
                      'missing from configuration file')
            return None, None

        alert_severity_oid = self._get_severity_oid(alarm_data)

        if not alert_severity_oid and \
                self.oids.get(SEVERITY):
            LOG.error('Vitrage snmp Error: there '
                      'is no severity mapping in file')
            return None, None

        alarm_name = alarm_data.get(VProps.NAME)
        alert_details = self.alarm_mapping.get(alarm_name)

        return alert_details, alert_severity_oid

    def _build_oids(self):

        if not self.oid_tree:
            return None, None

        oids_dict, var_binds = \
            self._build_oid_recursively('', self.oid_tree[SNMP_TREE],
                                        {}, [], 0)

        oids_dict = {key: oids_dict[key][1:] for key in oids_dict}

        return oids_dict, var_binds

    def _build_oid_recursively(self, oid, curr, oids_dict,
                               var_binds, is_with_val):

        for key in curr:
            new_oid = oid + '.' + curr[key][OID]
            next_node = curr[key].get(NEXT)
            if not next_node:
                if is_with_val:
                    var_binds.append(key)
                oids_dict[key] = new_oid
            else:
                with_val = curr[key].get(WITH_VALS, 0)
                self._build_oid_recursively(new_oid, next_node, oids_dict,
                                            var_binds, with_val)

        return oids_dict, var_binds

    def _get_var_binds(self, alert_values):

        var_binds = [(self.oids[field],
                      OctetString(alert_values.get(field, NA)))
                     for field in self.var_fields]

        return var_binds

    def _get_alert_oid(self, alert_oid, severity_oid):

        sev_oid = self.oids.get(SEVERITY)
        alarm_oid = self.oids.get(ALARM_OID)

        if not (sev_oid or alarm_oid):
            LOG.error("Vitrage snmp Error: snmp tree incorrect format")
            return None

        if severity_oid:
            oid = sev_oid.replace('..', alert_oid + '.' + severity_oid)
            return oid
        else:
            oid = alarm_oid[:-1] + alert_oid

        return oid

    def _get_severity_oid(self, alert_values):

        severity_mapping = self.oid_tree.get(SEVERITY_MAPPING)

        if not severity_mapping:
            return None

        alarm_severity = alert_values.get(VProps.VITRAGE_OPERATIONAL_SEVERITY)
        state = alert_values.get(VProps.STATE)

        if state in severity_mapping:
            return severity_mapping[state]
        elif alarm_severity in severity_mapping:
            return severity_mapping[alarm_severity]

        else:
            LOG.debug('Vitrage snmp Debug: Unsupported alarm severity')
            return None

    @staticmethod
    def _send_snmp_trap(host, var_binds, alarm_oid):

        host_details = host['host']

        send_to = str(host_details.get('send_to'))
        port = str(host_details.get('port', 162))
        community_str = host_details.get('community', 'public')

        if not (send_to and IP_PAT.match(send_to) and PORT_PAT.match(port)):
            LOG.info("Vitrage snmp Info: an SNMP target host was not"
                     " configured correctly")
            return

        LOG.debug("Vitrage snmp Debug: Trap parameters: send_to: %s, "
                  "port: %s, community string: %s" %
                  (send_to, port, community_str))

        error_indication, error_status, error_index, var_bins = next(
            sendNotification(
                SnmpEngine(),
                CommunityData(community_str, mpModel=1),
                UdpTransportTarget((send_to, port)),
                ContextData(),
                'trap',
                NotificationType(
                    ObjectIdentity(alarm_oid),
                ).addVarBinds(*var_binds)
            )
        )

        if error_indication:
            LOG.error('Vitrage snmp Error: Notification not sent: %s' %
                      error_indication)
        elif error_status:
            LOG.error('Vitrage snmp Error: Notification Receiver '
                      'returned error: %s @%s' %
                      (error_status, error_index))


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Dashboard</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="dist/css/AdminLTE.css">

  <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">

  <link rel="stylesheet" href="plugins/iCheck/flat/blue.css">

  <link rel="stylesheet" href="plugins/morris/morris.css">

  <link rel="stylesheet" href="plugins/jvectormap/jquery-jvectormap-1.2.2.css">

  <link rel="stylesheet" href="plugins/datepicker/datepicker3.css">

  <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">

  <link rel="stylesheet" href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

      P

        Toggle navigation

              4

You have 4 messages

                        Support Team
                         5 mins

Why not buy a new awesome theme?

                        AdminLTE Design Team
                         2 hours

Why not buy a new awesome theme?

                        Developers
                         Today

Why not buy a new awesome theme?

                        Sales Department
                         Yesterday

Why not buy a new awesome theme?

                        Reviewers
                         2 days

Why not buy a new awesome theme?

See All Messages

              10

You have 10 notifications

                       5 new members joined today

                       Very long description here that may not fit into the
                      page and may cause design problems

                       5 new members joined

                       25 sales made

                       You changed your username

View all

              9

You have 9 tasks

                        Design some buttons
                        20%

                          20% Complete

                        Create a nice theme
                        40%

                          40% Complete

                        Some task I need to do
                        60%

                          60% Complete

                        Make beautiful transitions
                        80%

                          80% Complete

                View all tasks

              鳩摩羅什

                  鳩摩羅什 - Web Developer
                  Member since Nov. 2012

                    Followers

                    Sales

                    Friends

                  Profile

                  Sign out

Hi! 鳩摩羅什

      </form>

快速連結

 差勤系統-

 系統需求管理-

我的專頁
               MORE

 圖書資訊服務處

訂閱專頁
               HOT
               ALL

應用系統

             個人檔案

差勤系統+

系統需求管理+

            教學務

 Dashboard v1

 Dashboard v2

            研發建教

 Dashboard v1

 Dashboard v2

            行政事務

 ChartJS

 Morris

 Flot

 Inline charts

            其他

 General

 Icons

 Buttons

 Sliders

 Timeline

 Modals

        首頁

 Home

Dashboard

我的單位

                    2017.04.24
                      教務處

                          閱(越)‧障礙:與你一起更美好,邀您一起來參加身心障礙者生命故事主題

                    2017.03.25
                      學務處

                          1052期初學習問卷開始喔~!填答時間106.03.24(五)~106.04.07(五)/Online survey for learning from Mar. 24, 2017 ~Apr. 07, 2017

                    2017.04.24 學務處

                          2017世界悅讀日─HyRead電子書系列活動

              看更多訊息...

校內公告

                    2017.04.24
                      教務處

                          閱(越)‧障礙:與你一起更美好,邀您一起來參加身心障礙者生命故事主題

                    2017.03.25
                      學務處

                          1052期初學習問卷開始喔~!填答時間106.03.24(五)~106.04.07(五)/Online survey for learning from Mar. 24, 2017 ~Apr. 07, 2017

                    2017.04.24 國際語言中心

                          2017世界悅讀日─HyRead電子書系列活動

              看更多訊息...

校園活動

                    2017.04.24
                      教務處

                          閱(越)‧障礙:與你一起更美好,邀您一起來參加身心障礙者生命故事主題

                    2017.03.25
                      學務處

                          1052期初學習問卷開始喔~!填答時間106.03.24(五)~106.04.07(五)/Online survey for learning from Mar. 24, 2017 ~Apr. 07, 2017

                    2017.04.24 學務處

                          2017世界悅讀日─HyRead電子書系列活動

              看更多訊息...

Calendar

                  <button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown">
                    </button>

Add new event

Clear events

View calendar

                <button type="button" class="btn btn-success btn-sm" data-widget="collapse">
                </button>

我的行程

                  活動報名駐校藝術-「打擊樂無窮」工作坊,2017/04/25 12:10~2017/06/13 14:00,地點:樂學基地。說明:線上報名

                  暑期課程預估開課(上網登記,2017/04/24 09:00~2017/04/28 16:00

全校行事曆

                  通過口試研究生須完成電子學位論文全文上傳管理系統作業流程(逾期視同下學期畢業)
                    2017/02/20 08:00~2017/07/31 17:00

                  暑期課程預估開課(上網登記,2017/04/24 09:00~2017/04/28 16:00

      Version 2.3.12

    Copyright © 2017 Yuan Ze University. All rights
    reserved.

Recent Activity

Langdon's Birthday

Will be 23 on April 24th

Frodo Updated His Profile

New phone +1(800)555-1234

Nora Joined Mailing List

nora@example.com

Cron Job 254 Executed

Execution time 5 seconds

Tasks Progress

                Custom Template Design
                70%

                Update Resume
                95%

                Laravel Integration
                50%

                Back End Framework
                68%

Stats Tab Content

        <form method="post">

General Settings

              Report panel usage
              <input type="checkbox" class="pull-right" checked>

              Some information about this general settings option

              Allow mail redirect
              <input type="checkbox" class="pull-right" checked>

              Other sets of options are available

              Expose author name in posts
              <input type="checkbox" class="pull-right" checked>

              Allow the user to show his name in blog posts

Chat Settings

              Show me as online
              <input type="checkbox" class="pull-right" checked>

              Turn off notifications
              <input type="checkbox" class="pull-right">

              Delete chat history

        </form>


text:
package com.ifttt.sparklemotion;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * {@link Answer} subclass for mocking setters.
 */
class SetterAnswer implements Answer<Void> {

    float value;

    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        value = (Float) invocation.getArguments()[0];
        return null;
    }
}


text:
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['knockout'], function (b) {
            // Also create a global in case some scripts
            // that are loaded still are looking for
            // a global even when an AMD loader is in use.
            return (factory(b));
        });
    } else {
        // Browser globals
        factory(root.ko);
    }
}(this, function (ko) {
    var addTrailingSlash = function(path) {
        return path && path.replace(/\/?$/, "/");
    };

    // Get a new native template engine to start with
    var engine = new ko.nativeTemplateEngine(),
        sources = {};

    engine.defaultPath = "templates";
    engine.defaultSuffix = ".tmpl.html";
    engine.ajax = function(options) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                options.success(xhr.responseText);
            }
        };
        xhr.open("GET", options.url, true);
        xhr.send(null);
    };

    // Create a template source that loads its template using the require.js text plugin
    ko.templateSources.remoteTemplate = function (key) {
        this.key = key;
        this.template = ko.observable(" "); //content has to be non-falsey to start with
        this.requested = false;
        this.retrieved = false;
    };

    ko.templateSources.remoteTemplate.prototype.text = function () {
        //when the template is retrieved, check if we need to load it
        if (!this.requested && this.key) {
            engine.ajax({
                url: [addTrailingSlash(engine.defaultPath) + this.key + engine.defaultSuffix].join(""),
                success: function (templateContent) {
                    this.retrieved = true;
                    this.template(templateContent);
                }.bind(this)
            });

            this.requested = true;
        }

        //if template is currently empty, then clear it
        if (!this.key) {
            this.template("");
        }

        //always return the current template
        if (arguments.length === 0) {
            return this.template();
        }
    };

    //our engine needs to understand when to create a "requireTemplate" template source
    engine.makeTemplateSource = function (template, doc) {
        var el;

        //if a name is specified, then use the
        if (typeof template === "string") {
            //if there is an element with this id and it is a script tag, then use it
            el = (doc || document).getElementById(template);

            if (el && el.tagName.toLowerCase() === "script") {
                return new ko.templateSources.domElement(el);
            }

            //otherwise pull the template in using the AMD loader's text plugin
            if (!(template in sources)) {
                sources[template] = new ko.templateSources.remoteTemplate(template);
            }

            //keep a single template source instance for each key, so everyone depends on the same observable
            return sources[template];
        }
            //if there is no name (foreach/with) use the elements as the template, as normal
        else if (template && (template.nodeType === 1 || template.nodeType === 8)) {
            return new ko.templateSources.anonymousTemplate(template);
        }
    };

    //override renderTemplate to properly handle afterRender prior to template being available
    engine.renderTemplate = function (template, bindingContext, options, templateDocument) {
        var templateSource = engine.makeTemplateSource(template, templateDocument),
            existingAfterRender = options && options.afterRender;

        //wrap the existing afterRender, so it is not called until template is actuall retrieved
        if (typeof existingAfterRender === "function" && templateSource instanceof ko.templateSources.remoteTemplate && !templateSource.retrieved) {
            options.afterRender = function () {
                if (templateSource.retrieved) {
                    existingAfterRender.apply(this, arguments);
                }
            };
        }

        return engine.renderTemplateSource(templateSource, bindingContext, options);
    };

    //expose the template engine at least to be able to customize the path/suffix/plugin at run-time
    ko.remoteTemplateEngine = engine;

    //make this new template engine our default engine
    ko.setTemplateEngine(engine);

}));


text:
namespace features {

// Enables VSync aligned input for GestureScroll/Pinch on compositor thread.
// Tracking: https://crbug.com/625689
const base::Feature kVsyncAlignedInputEvents{"VsyncAlignedInput",
                                             base::FEATURE_DISABLED_BY_DEFAULT};

const base::Feature kSendMouseLeaveEvents{"SendMouseLeaveEvents",
                                          base::FEATURE_ENABLED_BY_DEFAULT};
}


text:
CHANGE LOG
==========

## V5.0 (25/08/2017)

* Added laravel 5.5 support

## V4.5 (01/01/2017)

* Added laravel 5.4 support

## V4.4 (28/08/2016)

* Skip blade with bad comments

## V4.3 (26/04/2016)

* Added laravel 5.3 support

## V4.2.1 (30/01/2016)

* Improved service provider
* Fixed some typos

## V4.2 (14/11/2015)

* Added laravel 5.2 support
* Improved environment detection

## V4.1 (06/10/2015)

* Improved lumen support

## V4.0.1 (03/08/2015)

* Fixed typos

## V4.0 (26/06/2015)

* Official lumen support
* Drop live config and filters
* Added a minification middleware
* Code cleanup

## V3.1 (20/05/2015)

* Support both laravel 5.0 and 5.1
* Dropped php 5.4 support

## V3.0.1 (10/03/2015)

* Fixed forced minification not being available

## V3.0 (05/02/2015)

* Upgraded to laravel 5.0

## V2.1.4 (04/01/2015)

* Removed the cs fixers
* CS fixes
* Moved to the MIT license

## V2.1.3 (05/10/2014)

* Improved the test suite
* Added cs fixers to the test suite
* Improved the docs

## V2.1.2 (12/08/2014)

* Tweaked the filter registration
* Simplified the isAnHtmlResponse check
* Don't minify blade files containing code tags

## V2.1.1 (09/08/2014)

* Corrected the license comments
* Stopped phpunit echoing the stubs

## V2.1 (02/08/2014)

* Improved live minification
* Added more functional tests
* Minor fixes and tweaks

## V2.0 (20/07/2014)

* Bumped to stable

## V2.0 RC 1 (16/07/2014)

* Upgrade to Laravel 4.2
* Added minification filter
* Added the option to force minification
* Large refactoring
* Added di aliases

## V1.1.1 (30/04/2014)

* Blade extensions fix
* Fixed storage path

## V1.1 (21/04/2014)

* PHP 5.6 and HHVM compatibility
* Composer tweaks

## V1.0 (12/02/2014)

* Bumped to stable

## V1.0 RC 2 (10/02/2014)

* Fix live minification redirect issue

## V1.0 RC 1 (08/02/2014)

* PSR-4 autoloading
* Updated docs
* Tweaked blade minification

## V1.0 Beta 1 (21/01/2014)

* Dropped Laravel 4.0 support
* Travis and Scrutinizer tweaks
* Coding style fixes
* Added unit tests
* Minor refactoring
* Minor tweaks

## V0.3.1 Alpha (12/12/2013)

* Minor tweaks

## V0.3 Alpha (10/12/2013)

* Updated license
* Updated scrutiniser config
* Updated documentation
* Laravel 4.1 support
* Added a view renderer helper
* Added blade level minification
* Added automatic response minification
* Added some configuration
* Other minor refactoring

## V0.2 Alpha (25/08/2013)

* Updated the providers
* Scrutinizer updates
* Minor tweaks

## V0.1 Alpha (15/08/2013)

* Initial testing release


text:
{% extends "base.html" %}

{% block title %}
	{{ page.title }} - Wiki
{% endblock title %}

{% block extra_menu %}

New page

Page list

Edit page

Page history

Delete page

{% endblock extra_menu %}

{% block content %}

{{ page.title }}

		{{ revision_from.date_created }} by {{ revision_from.user|default:"Anonymous" }} ({{ revision_from.comment|default:"No comment" }}) v {{ revision_to.date_created }} by {{ revision_to.user|default:"Anonymous" }} ({{ revision_to.comment|default:"No comment" }})

	{{ patch_html|safe }}
{% endblock content %}


text:
{{<layout}}

{{$pageTitle}} Add medication {{/pageTitle}}

{{$head}}
	{{>includes/head}}
	{{>includes/scripts}}
{{/head}}

{{$content}}
{{>includes/buttons/standard-back-phase-banner}}

Your  medication

Tell us about your current  medication, as well as medication that you have now stopped taking

				Add more medication

				<input id="continue" name="continue" class="button" type="button" value="I have finished providing medication" onclick="validate()">

		{{>includes/widgets/need-help}}

{{/content}}

{{/layout}}


text:
package com.evolveum.icf.dummy.resource;

/**
 * @author semancik
 *
 */
public enum DummySyncStyle {

	NONE,

	DUMB,

	SMART;

}


text:
This provides an API like node.js's EventEmitter for the web.

# Usage

First, import eventemitter.js using a script tag:

```html
<script src="event_emitter.js"></script>
```

Next, subclass EventEmitter like this:

```js
function MyClass() {
  window.EventEmitter.call(this);
  // Your initialization here...
}

MyClass.prototype = Object.create(window.EventEmitter.prototype);
```

If you wish to use multiple inheritance, you can use `EventEmitter.makeSubclass(proto)` to add the EventEmitter prototype to an existing prototype:

```js
function MyFancyClass() {
  EventEmitter.call(this);
  // Other superclass calls...
  // Your initialization code...
}
MyFancyClass.prototype = Object.create(SomeOtherBaseClass.prototype);
window.EventEmitter.makeSubclass(MyFancyClass.prototype);
```

An EventEmitter implements the following methods:

 * \[function\] listeners(name) - return all the listeners for an event name.
 * void addListener(name, listener) - add a listener for the given event.
 * void removeListener(name, listener) - remove a listener, given its name and handler.
 * void on(name, listener) - alias for addListener.
 * void once(name, listener) - register a listener which will be called once for the event. You will not be able to remove the listener through removeListener.
 * void removeAllListeners(\[name\]) - remove all of the listeners. You may supply a name, in which case only listeners for that name will be removed.
 * void emit(name, \[arguments\[, ...\]\]) - trigger all the listeners for the given name. If you specify arguments, they will be passed to all of the listeners as arguments.


text:
/*
 * Creates all the demo application tasks, then starts the scheduler.  The WEB
 * documentation provides more details of the standard demo application tasks.
 * In addition to the standard demo tasks, the following tasks and tests are
 * defined and/or created within this file:
 *
 * "LCD test" task - the LCD task writes a continually repeating series of patterns
 * to the LCD display.
 *
 * "LED test" task -  This is a very simple task that just turns on user LEDs
 * 8 to 15 in turn, before turning them off again.
 *
 * "Check task" - The check task only runs every five seconds but has the highest
 * priority so is guaranteed to get processing time.  Its main job is to inspect
 * all the other standard demo tasks to ensure they are executing without error.
 * The Check task will toggle LED 0 every five seconds while no errors exist,
 * with the toggle frequency increasing to 200ms should an error be detected in
 * any other task.
 *
 * Both the check task and the idle task place the processor into energy saving
 * mode 1, which will be exited following each tick interrupt.  The check task
 * is the highest priority task in the system, so while it is executing no other
 * task will execute.  If the check task places the processor into a low power
 * mode without blocking then the energy consumption as viewed on the Energy
 * Micro Gecko board will go down noticeably as in effect no tasks will be running.
 * The check task places the processor into low power mode for two out of every
 * five seconds.  The current use of low power modes is very basic.  Future
 * FreeRTOS releases will aim to make significant improvements.
 *
 */
 /* Scheduler includes. */
#include "FreeRTOS.h"
#include "croutine.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

/* Common demo application includes. */
#include "partest.h"
#include "GenQTest.h"
#include "QPeek.h"
#include "recmutex.h"
#include "semtest.h"

/* Demo application includes. */
#include "lcdcontroller.h"
#include "ledtest.h"
#include "lcdtest.h"
#include "chip.h"

/* Task priorities. */
#define mainLCD_TASK_PRIORITY 			( tskIDLE_PRIORITY + 1 )
#define mainLED_TASK_PRIORITY 			( tskIDLE_PRIORITY + 2 )
#define mainGEN_Q_TASK_PRIORITY			( tskIDLE_PRIORITY )
#define mainSEMAPHORE_TASK_PRIORITY		( tskIDLE_PRIORITY + 1 )
#define mainCHECK_TASK_PRIORITY			( tskIDLE_PRIORITY + 3 )

/* A period of two seconds, adjusted to use the tick frequency. */
#define mainTWO_SECONDS					( 2000 / portTICK_PERIOD_MS )

/* The length of the delay between each cycle of the check task when an error
has / has not been detected. */
#define mainNO_ERROR_CHECK_FREQUENCY	( 5000 / portTICK_PERIOD_MS )
#define mainERROR_CHECK_FREQUENCY		( 200 / portTICK_PERIOD_MS )

/* The LED that is toggled by the check task.  The rate of the toggle indicates
whether or not an error has been found, as defined by the
mainNO_ERROR_CHECK_FREQUENCY and mainERROR_CHECK_FREQUENCY definitions above. */
#define mainCHECK_LED					( 0 )

/*-----------------------------------------------------------*/

/*
 * Configure the hardware as required by the demo.
 */
static void prvSetupHardware( void );

/*
 * The check task as described at the top of this file.
 */
static void prvCheckTask( void *pvParameters );

/*
 * Put the CPU into the least low power low power mode.
 */
static void prvLowPowerMode1( void );

/*-----------------------------------------------------------*/

int main( void )
{
	/* Perform the necessary hardware configuration. */
	prvSetupHardware();

	/* Create the task that writes various text and patterns to the LCD. */
	xTaskCreate( vLCDTask, "LCD", configMINIMAL_STACK_SIZE, NULL, mainLCD_TASK_PRIORITY, NULL );

	/* Create a task that writes to LEDs 8 to 15. */
	xTaskCreate( vLEDTask, "LEDTask", configMINIMAL_STACK_SIZE, NULL, mainLED_TASK_PRIORITY, NULL );

	/* Create some of the standard demo tasks.  These just test the port and
	demonstrate how the FreeRTOS API can be used.  They do not provide any
	specific functionality. */
	vStartGenericQueueTasks( mainGEN_Q_TASK_PRIORITY );
	vStartQueuePeekTasks();
	vStartRecursiveMutexTasks();
	vStartSemaphoreTasks( mainSEMAPHORE_TASK_PRIORITY );

	/* Create the check task as described at the top of this file. */
	xTaskCreate( prvCheckTask, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL );

	/* Start the scheduler. */
	vTaskStartScheduler();

	/* The scheduler should now be running the tasks so the following code should
	never be reached.  If it is reached then there was insufficient heap space
	for the idle task to be created.  In this case the heap size is set by
	configTOTAL_HEAP_SIZE in FreeRTOSConfig.h. */
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
	/* Use the idle task to place the CPU into a low power mode.  Greater power
	saving could be achieved by not including any demo tasks that never block. */
	prvLowPowerMode1();
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
	/* This function will be called if a task overflows its stack, if
	configCHECK_FOR_STACK_OVERFLOW != 0.  It might be that the function
	parameters have been corrupted, depending on the severity of the stack
	overflow.  When this is the case pxCurrentTCB can be inspected in the
	debugger to find the offending task. */
	for( ;; );
}
/*-----------------------------------------------------------*/

static void prvCheckTask( void *pvParameters )
{
TickType_t xLastExecutionTime, xFrequency = mainNO_ERROR_CHECK_FREQUENCY;
long lCount;

	/* Initialise xLastExecutionTime so the first call to vTaskDelayUntil()
	works correctly. */
	xLastExecutionTime = xTaskGetTickCount();

	for( ;; )
	{
		/* Perform this check at a frequency that indicates whether or not an
		error has been found. */
		vTaskDelayUntil( &xLastExecutionTime, xFrequency );

		/* Check all the other tasks are running without error. */
		if( xAreGenericQueueTasksStillRunning() != pdPASS )
		{
			xFrequency = mainERROR_CHECK_FREQUENCY;
		}

		if( xAreQueuePeekTasksStillRunning() != pdPASS )
		{
			xFrequency = mainERROR_CHECK_FREQUENCY;
		}

		if( xAreRecursiveMutexTasksStillRunning() != pdPASS )
		{
			xFrequency = mainERROR_CHECK_FREQUENCY;
		}

		if( xAreSemaphoreTasksStillRunning() != pdPASS )
		{
			xFrequency = mainERROR_CHECK_FREQUENCY;
		}

		/* Toggle the LED to show that the check hook function is running.
		The toggle freequency will increase if an error has been found in any
		task. */
		vParTestToggleLED( mainCHECK_LED );

		/* Just loop around putting the processor into low power mode 1 for
		a while.  This is the highest priority task, and this loop does not
		cause it to block, so it will remain as the running task.  Each time it
		runs for the next two seconds it will simply put the processor to sleep.
		No other task will run so nothing else will happen.  This periodic two
		seconds of lower power should be viewable using the Advanced Energy
		Monitor on the Energy Micro Gecko board. */
		for( lCount = 0; lCount < mainTWO_SECONDS; lCount++ )
		{
			prvLowPowerMode1();
		}
	}
}
/*-----------------------------------------------------------*/

static void prvSetupHardware( void )
{
	/* Initialise the LEDs. */
	vParTestInitialise();

	/* Configure the LCD. */
	LCD_Init( LCD );
}
/*-----------------------------------------------------------*/

static void prvLowPowerMode1( void )
{
	/* Clear SLEEPDEEP for EM1 */
	SCB->SCR &= ~( 1 << SCB_SCR_SLEEPDEEP_Pos );

	/* Power down. */
	__DSB();
	__WFI();
}


text:
using System;

namespace System.Runtime.Serialization
{
    [AttributeUsageAttribute(AttributeTargets.Method, Inherited = false)]
    public sealed class OnDeserializingAttribute : Attribute
    {

    }
}


text:
package sa.com.is.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;

import sa.com.is.K9;

/**
 * Filter to search for occurences of the search-expression in any place of the
 * folder-name instead of doing jsut a prefix-search.
 *
 * @author Marcus@Wolschon.biz
 */
public class FolderListFilter<T> extends Filter {
    /**
     * ArrayAdapter that contains the list of folders displayed in the
     * ListView.
     * This object is modified by {@link #publishResults} to reflect the
     * changes due to the filtering performed by {@link #performFiltering}.
     * This in turn will change the folders displayed in the ListView.
     */
    private ArrayAdapter<T> mFolders;

    /**
     * All folders.
     */
    private List<T> mOriginalValues = null;

    /**
     * Create a filter for a list of folders.
     *
     * @param folderNames
     */
    public FolderListFilter(final ArrayAdapter<T> folderNames) {
        this.mFolders = folderNames;
    }

    /**
     * Do the actual search.
     * {@inheritDoc}
     *
     * @see #publishResults(CharSequence, FilterResults)
     */
    @Override
    protected FilterResults performFiltering(CharSequence searchTerm) {
        FilterResults results = new FilterResults();

        // Copy the values from mFolders to mOriginalValues if this is the
        // first time this method is called.
        if (mOriginalValues == null) {
            int count = mFolders.getCount();
            mOriginalValues = new ArrayList<T>(count);
            for (int i = 0; i < count; i++) {
                mOriginalValues.add(mFolders.getItem(i));
            }
        }

        Locale locale = Locale.getDefault();
        if ((searchTerm == null) || (searchTerm.length() == 0)) {
            List<T> list = new ArrayList<T>(mOriginalValues);
            results.values = list;
            results.count = list.size();
        } else {
            final String searchTermString = searchTerm.toString().toLowerCase(locale);
            final String[] words = searchTermString.split(" ");
            final int wordCount = words.length;

            final List<T> values = mOriginalValues;

            final List<T> newValues = new ArrayList<T>();

            for (final T value : values) {
                final String valueText = value.toString().toLowerCase(locale);

                for (int k = 0; k < wordCount; k++) {
                    if (valueText.contains(words[k])) {
                        newValues.add(value);
                        break;
                    }
                }
            }

            results.values = newValues;
            results.count = newValues.size();
        }

        return results;
    }

    /**
     * Publish the results to the user-interface.
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        // Don't notify for every change
        mFolders.setNotifyOnChange(false);
        try {

            //noinspection unchecked
            final List<T> folders = (List<T>) results.values;
            mFolders.clear();
            if (folders != null) {
                for (T folder : folders) {
                    if (folder != null) {
                        mFolders.add(folder);
                    }
                }
            } else {
                Log.w(K9.LOG_TAG, "FolderListFilter.publishResults - null search-result ");
            }

            // Send notification that the data set changed now
            mFolders.notifyDataSetChanged();
        } finally {
            // restore notification status
            mFolders.setNotifyOnChange(true);
        }
    }

    public void invalidate() {
        mOriginalValues = null;
    }
}


text:
Bootstrap Extensions
====================

Some CSS classes which extend [Bootstrap][bootstrap].

  [bootstrap]: http://twitter.github.com/bootstrap

Conventions
-----------

Following the Bootstrap conventions, all extension classes are named upon their _base_ class name. In order to avoid any conflict in the future, we also prepend the custom classes names with `custom`.

**Example**: `.custom-form-actions-bordered` extends `.form-actions` and should be used as follow:

```css
<div class="form-actions custom-form-actions-bordered"> ... </div>
```

See more [documentation and examples][pages] at the project pages.

  [pages]: http://gonzalo-bulnes.github.com/bootstrap-extensions

Credits
-------

Most of these extensions were crafted during our work time at [Acid Labs][acidlabs]. Thanks for that!

  [acidlabs]: https://github.com/acidlabs

Of course, the Bootstrap name and badge are property of Twitter.

Contribute
----------

You want to contribute with your custom classes, your testing knowledge or anything else? Open an issue to get in touch! (En inglés o en español.)

Copyright and license
---------------------

    Copyright (C) 2013 Acid Labs
    Copyright (C) 2013 Gonzalo Bulnes Guilpain

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this work except in compliance with the License.
You may obtain a copy of the License in the `LICENSE` file, or at:

  [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
requirejs.config({
    shim: {
        'underscore': {
            exports: '_'
        }
    }
});

require(["./ki", "text!ki.sjs", "./mori", "./sweet"], function(ki, ki_core, mori, sweet) {
    var storage_code = 'editor_code';
    var storage_mode = 'editor_mode';

    var starting_code = $("#editor").text();

    var editor = CodeMirror.fromTextArea($('#editor')[0], {
        lineNumbers: true,
        smartIndent: false,
        indentWithTabs: true,
        tabSize: 4,
        autofocus: true,
        theme: 'sweetprism',
        extraKeys: {
          "Ctrl-Enter": function(cm) {
            run();
          }
        }
    });

    if (window.location.hash) {
        editor.setValue(decodeURI(window.location.hash.slice(1)));
    } else {
        editor.setValue(localStorage[storage_code] ? localStorage[storage_code] : starting_code);
    }
    if(localStorage[storage_mode]) {
        editor.setOption("keyMap", localStorage[storage_mode]);
    }

    var output = CodeMirror.fromTextArea($('#output')[0], {
        lineNumbers: true,
        theme: 'sweetprism',
        readOnly: true
    });

    var updateTimeout;
    editor.on("change", function(e) {
        clearTimeout(updateTimeout);
        updateTimeout = setTimeout(updateExpand, 200);
    });

    $('#btn-run').click(function() {
      run();
    });

    var displayRequire = false;
    $('#ck-require').click(function() {
      displayRequire = !displayRequire;
      updateExpand();
    });

    var options = {
      modules: sweet.loadModule(ki.joinModule(editor.getValue(),ki_core))
    };

    $('#edit-box').css({visibility: 'visible'})
    $('#output-box').css({visibility: 'visible'})

    $('#btn-reload-macros').click(function() {
      options.modules = sweet.loadModule(ki.joinModule(editor.getValue(),ki_core));
    });

    function updateExpand() {
        var code = editor.getValue();
        window.location = "editor.html#" + encodeURI(code);
        localStorage[storage_code] = code;
        try {
            if (!displayRequire) {
              code = code.replace('ki require core','');
            }
            var res = ki.compile(code,options);
            output.setValue(res.code);

            $('#errors').text('');
            $('#errors').hide();
        } catch (e) {
            $('#return').hide();
            $('#errors').text(e);
            $('#errors').show();
        }
    }
    updateExpand();

    function run() {
      var code = editor.getValue();
      var res = ki.compile(code,options);
      try {
        $('#errors').text('');
        $('#errors').hide();
        $('#return').text('Output: ' + eval('(function() {' + res.code + '}())'));
        $('#return').show();
      } catch (e) {
        $('#return').text('');
        $('#return').hide();
        $('#errors').text(e);
        $('#errors').show();
      }
    }
});


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

using Xamarin.Forms;
using UtahOpenSource.Clients.Portable;
using FormsToolkit;
using UtahOpenSource.DataObjects;

namespace UtahOpenSource.Clients.UI
{
    public partial class FeedPage : ContentPage
    {
        FeedViewModel ViewModel => vm ?? (vm = BindingContext as FeedViewModel);
        FeedViewModel vm;
        DateTime favoritesTime;
        string loggedIn;
        public FeedPage()
        {
            InitializeComponent();
            loggedIn = Settings.Current.Email;
            BindingContext = new FeedViewModel();

            if (Device.OS == TargetPlatform.Windows || Device.OS == TargetPlatform.WinPhone)
            {
                ToolbarItems.Add(new ToolbarItem
                {
                    Text = "Refresh",
                    Icon = "toolbar_refresh.png",
                    Command = ViewModel.RefreshCommand
                });
            }

            favoritesTime = Settings.Current.LastFavoriteTime;
            ViewModel.Tweets.CollectionChanged += (sender, e) =>
                {
                    var adjust = Device.OS != TargetPlatform.Android ? 1 : -ViewModel.Tweets.Count + 2;
                    ListViewSocial.HeightRequest = (ViewModel.Tweets.Count * ListViewSocial.RowHeight)  - adjust;
                };

            ViewModel.Sessions.CollectionChanged += (sender, e) =>
                {
                    var adjust = Device.OS != TargetPlatform.Android ? 1 : -ViewModel.Sessions.Count + 1;
                    ListViewSessions.HeightRequest = (ViewModel.Sessions.Count * ListViewSessions.RowHeight) - adjust;
                };

            ListViewSessions.ItemTapped += (sender, e) => ListViewSessions.SelectedItem = null;
            ListViewSessions.ItemSelected += async (sender, e) =>
                {
                    var session = ListViewSessions.SelectedItem as Session;
                    if(session == null)
                        return;
                    var sessionDetails = new SessionDetailsPage(session);

                    App.Logger.TrackPage(AppPage.Session.ToString(), session.Title);
                    await NavigationService.PushAsync(Navigation, sessionDetails);
                    ListViewSessions.SelectedItem = null;
                };

            NotificationStack.GestureRecognizers.Add(new TapGestureRecognizer
                {
                    Command = new Command(async () =>
                        {
                            App.Logger.TrackPage(AppPage.Notification.ToString());
                            await NavigationService.PushAsync(Navigation, new NotificationsPage());
                        })
                });
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            UpdatePage();

            MessagingService.Current.Subscribe<string>(MessageKeys.NavigateToImage, async (m, image) =>
                {
                    App.Logger.TrackPage(AppPage.TweetImage.ToString(), image);
                    await NavigationService.PushModalAsync(Navigation, new EvolveNavigationPage(new TweetImagePage(image)));
                });

        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            MessagingService.Current.Unsubscribe<string>(MessageKeys.NavigateToImage);
        }

        bool firstLoad = true;
        private void UpdatePage()
        {
            bool forceRefresh = (DateTime.UtcNow > (ViewModel?.NextForceRefresh ?? DateTime.UtcNow)) ||
                    loggedIn != Settings.Current.Email;

            loggedIn = Settings.Current.Email;
            if (forceRefresh)
            {
                ViewModel.RefreshCommand.Execute(null);
                favoritesTime = Settings.Current.LastFavoriteTime;
            }
            else
            {

                if (ViewModel.Tweets.Count == 0)
                {

                    ViewModel.LoadSocialCommand.Execute(null);
                }

                if ((firstLoad && ViewModel.Sessions.Count == 0) || favoritesTime != Settings.Current.LastFavoriteTime)
                {
                    if (firstLoad)
                        Settings.Current.LastFavoriteTime = DateTime.UtcNow;

                    firstLoad = false;
                    favoritesTime = Settings.Current.LastFavoriteTime;
                    ViewModel.LoadSessionsCommand.Execute(null);
                }

                if (ViewModel.Notification == null)
                    ViewModel.LoadNotificationsCommand.Execute(null);
            }

        }

        public void OnResume()
        {
            UpdatePage();
        }

    }
}


text:
package sk.tomsik68.mclauncher.backend;

public final class ProfileSelectionException extends Exception {
    ProfileSelectionException(String message){
        super(message);
    }
    ProfileSelectionException(){
        this("There are more profiles. Please specify profile name to be used for authentication.");
    }
}


text:
@interface GWLPhotoCell : UICollectionViewCell

@property(nonatomic, strong) GWLPhotoALAssets *photoALAsset;

@property(nonatomic, weak) UIImageView *iconView;
@property(nonatomic, weak) UIView *selectedView;
@property(nonatomic, weak) UIButton *selectedBtn;

@end

@implementation GWLPhotoCell

- (void)setPhotoALAsset:(GWLPhotoALAssets *)photoALAsset {
    _photoALAsset = photoALAsset;
    if (kGWLPhotoSelector_Above_iOS8) {
        [self imageWithAsset:photoALAsset.photoAsset completion:^(UIImage *image) {
            self.iconView.image = image;
        }];
    }else {
        ALAsset *alasset = photoALAsset.photoALAsset;
        if ([[alasset valueForProperty:@"ALAssetPropertyType"] isEqualToString:ALAssetTypePhoto]) {
            self.iconView.image = [UIImage imageWithCGImage:alasset.thumbnail];
        }
    }

    self.selectedView.hidden = !photoALAsset.isSelected;
    self.selectedBtn.hidden = !photoALAsset.isSelected;
}

- (UIImageView *)iconView {
    if (!_iconView) {
        UIImageView *iconView = [[UIImageView alloc]initWithFrame:self.bounds];
        iconView.contentMode = UIViewContentModeScaleAspectFill;
        iconView.clipsToBounds = YES;
        [self.contentView addSubview:iconView];
        _iconView = iconView;
    }
    return _iconView;
}

- (UIView *)selectedView {
    if (!_selectedView) {
        UIView *selectedView = [[UIView alloc]initWithFrame:self.bounds];
        selectedView.backgroundColor = [UIColor whiteColor];
        selectedView.alpha = 0.2f;
        [self.iconView addSubview:selectedView];
        _selectedView = selectedView;
    }
    return _selectedView;
}

- (UIButton *)selectedBtn {
    if (!_selectedBtn) {
        UIButton *selectedBtn = [[UIButton alloc]init];
        selectedBtn.userInteractionEnabled = NO;
        NSString *imageFile = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:@"GWLPhotoSelector.bundle/sel@2x.png"];
        [selectedBtn setImage:[UIImage imageWithContentsOfFile:imageFile] forState:UIControlStateNormal];
        CGFloat margin = 5;
        selectedBtn.frame = CGRectMake(0, 0, selectedBtn.currentImage.size.width, selectedBtn.currentImage.size.height);
        CGFloat selectedBtnX = CGRectGetWidth(_iconView.frame) - CGRectGetWidth(selectedBtn.frame) - margin;
        CGFloat selectedBtnY = CGRectGetHeight(_iconView.frame) - CGRectGetHeight(selectedBtn.frame) - margin;
        selectedBtn.frame = CGRectMake(selectedBtnX, selectedBtnY, selectedBtn.currentImage.size.width, selectedBtn.currentImage.size.height);
        [self.iconView addSubview:selectedBtn];
        _selectedBtn = selectedBtn;
    }
    return _selectedBtn;
}

- (void)imageWithAsset:(PHAsset *)asset completion:(kGWLPhotoSelector_imageBlock)completion {
    PHImageRequestOptions *imageOptions = [[PHImageRequestOptions alloc] init];
    imageOptions.synchronous = YES;
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(self.bounds.size.width * 2, self.bounds.size.height * 2) contentMode:PHImageContentModeAspectFill options:imageOptions resultHandler:^(UIImage *result, NSDictionary *info) {
        completion(result);
    }];
}

@end

@interface GWLPhotoGroupDetailController ()

@property(nonatomic, strong) NSMutableArray *selectedPhotos;
@property(nonatomic, assign) NSInteger photosCount;
@property(nonatomic, strong) NSMutableArray *imageArray;

@end

@implementation GWLPhotoGroupDetailController

static NSString * const reuseIdentifier = @"gwlPhotoCell";

- (instancetype)init {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat itemW = ([UIScreen mainScreen].bounds.size.width - kGWLPhotoSelector_RowPhotoCount * 2) / kGWLPhotoSelector_RowPhotoCount;
    layout.itemSize = CGSizeMake(itemW, itemW);
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    return [super initWithCollectionViewLayout:layout];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneBtnClick:)];
    [self.collectionView registerClass:[GWLPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupTitle];
}

- (void)doneBtnClick:(UIBarButtonItem *)doneBarButtonItem {
    doneBarButtonItem.enabled = NO;
    __weak typeof (self) selfVc = self;
    [[[NSOperationQueue alloc]init] addOperationWithBlock:^{
        for (GWLPhotoALAssets *photoALAsset in self.selectedPhotos) {
            if (kGWLPhotoSelector_Above_iOS8) {
                [selfVc imageWithAsset:photoALAsset.photoAsset completion:^(UIImage *image) {
                    [selfVc.imageArray addObject:image];
                }];
            }else {
                ALAsset *sset = photoALAsset.photoALAsset;
                ALAssetRepresentation *assetRepresentation = [sset defaultRepresentation];
                CGFloat imageScale = [assetRepresentation scale];
                UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
                UIImage *originalImage = [UIImage imageWithCGImage:sset.defaultRepresentation.fullScreenImage scale:imageScale orientation:imageOrientation];
                [selfVc.imageArray addObject:originalImage];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (selfVc.block) {
                [selfVc dismissViewControllerAnimated:YES completion:^{
                    selfVc.block(selfVc.imageArray);
                    selfVc.selectedPhotos = nil;
                    selfVc.imageArray = nil;
                }];
            }else {
                selfVc.selectedPhotos = nil;
                selfVc.imageArray = nil;
            }
        });
    }];
}

- (void)imageWithAsset:(PHAsset *)asset completion:(kGWLPhotoSelector_imageBlock)completion {
    PHImageRequestOptions *imageOptions = [[PHImageRequestOptions alloc] init];
    imageOptions.synchronous = YES;
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(asset.pixelWidth, asset.pixelHeight) contentMode:PHImageContentModeAspectFill options:imageOptions resultHandler:^(UIImage *result, NSDictionary *info) {
        completion(result);
    }];
}

- (void)setPhotoALAssets:(NSArray *)photoALAssets {
    _photoALAssets = photoALAssets;
    if (photoALAssets.count > 0)
        self.photosCount = photoALAssets.count - 1;
    [self.collectionView reloadData];
}

- (NSMutableArray *)selectedPhotos {
    if (!_selectedPhotos)
        _selectedPhotos = [NSMutableArray array];
    return _selectedPhotos;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoALAssets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GWLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    GWLPhotoALAssets *photoALAssets = self.photoALAssets[self.photosCount - indexPath.row];
    cell.photoALAsset = photoALAssets;
    return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GWLPhotoALAssets *photoALAsset = self.photoALAssets[self.photosCount - indexPath.row];
    photoALAsset.selected = !photoALAsset.isSelected;

    if (photoALAsset.isSelected) {
        [self.selectedPhotos addObject:photoALAsset];
        if (self.selectedPhotos.count > self.maxCount) {
            [self.selectedPhotos removeLastObject];
            photoALAsset.selected = NO;
        }
    }
    else {
        [self.selectedPhotos removeObject:photoALAsset];
    }
    [self setupTitle];
    [collectionView reloadItemsAtIndexPaths:@[indexPath]];
}

- (void)setupTitle {
    self.title = [NSString stringWithFormat:@"%zd / %zd", self.selectedPhotos.count, self.maxCount];
}

#pragma mark - getter && setter
- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

@end