text:
package org.mitre.provenance.capture.linux;

/**
 * Small utility class representing the various flags that can be attached to a file descriptor.
 * See http://man7.org/linux/man-pages/man2/open.2.html for more information on flags.
 *
This comes from /proc/XX/fdinfo/YY where XX is a process PID, and YY is a file descriptor.
 *
 *
Some flag definitions, taken from fnctl.h on linux:
 *

 * # define O_CREAT           0100
 * # define O_APPEND         02000
 * #define O_ACCMODE          0003
 * #define O_RDONLY             00
 * #define O_WRONLY             01
 * #define O_RDWR               02
 * # define O_CREAT           0100
 * # define O_TRUNC          01000
 * # define __O_DIRECTORY  0200000
 * # define O_DIRECTORY    __O_DIRECTORY
 * # define O_NONBLOCK       04000
 * # define __O_CLOEXEC   02000000
 *

 *
 * @author moxious
 *
 */
public class ProcFDInfo {
	protected char [] flags = null;
	protected long pos = -1;

	protected static final Character C_0 = new Character('0');
	protected static final Character C_1 = new Character('1');
	protected static final Character C_2 = new Character('2');
	protected static final Character C_3 = new Character('3');
	protected static final Character C_4 = new Character('4');

	public ProcFDInfo(String pos, String flags) {
		// Flags strings look like for example 02004002.
		// We reverse the string and split it into characters, so it's easy to look up the nth
		// position, regardless of how long the string is.
		this.flags = new StringBuilder(flags).reverse().toString().toCharArray();
		this.pos = Long.parseLong(pos);
	}

	/**
	 * Get the original set of flags (in normal order) provided to this object.
	 */
	public String getFlags() { return new StringBuilder(new String(flags)).reverse().toString(); }
	public long getPos() { return pos; }

	/**
	 * Return the nth character flag in flags, or null if it doesn't exist/is out of range.
	 */
	protected Character nth(int n) { if(flags.length <= n) return null; return flags[n]; }

	public boolean O_WRONLY() { return C_1.equals(nth(0)); }
	public boolean O_RDWR() { return C_2.equals(nth(0)); }
	public boolean O_RDONLY() { return C_0.equals(nth(0)); }
	public boolean O_APPEND() { return C_2.equals(nth(3)); }
	public boolean O_TRUNC() { return C_1.equals(nth(4)); }
	public boolean O_DIRECTORY() { return C_2.equals(nth(5)); }
	public boolean O_CREAT() { return C_1.equals(nth(2)); }
	public boolean O_NONBLOCK() { return C_4.equals(nth(3)); }
} // End ProcFDInfo


text:
package org.kaazing.k3po.control.internal.event;

import static org.kaazing.k3po.control.internal.event.CommandEvent.Kind.NOTIFIED;

import java.util.Objects;

public class NotifiedEvent extends CommandEvent {

    private String barrier;

    @Override
    public Kind getKind() {
        return NOTIFIED;
    }

    @Override
    public int hashCode() {
        return Objects.hash(getKind(), getBarrier());
    }

    @Override
    public boolean equals(Object o) {
        return o == this || o instanceof NotifiedEvent && equalTo((NotifiedEvent) o);
    }

    protected boolean equalTo(NotifiedEvent that) {
        return super.equalTo(that) && Objects.equals(this.getBarrier(), that.getBarrier());
    }

    public String getBarrier() {
        return barrier;
    }

    public void setBarrier(String barrier) {
        this.barrier = barrier;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Commun\Table;

/**
 * @author Antarus
 * @project Raid-TracKer
 */
class ZoneHasModeDiffculteTable extends \Core\Table\AbstractServiceTable
{

    /**
     * Nom de la  table.
     *
     * @var string
     */
    protected $table = 'zone_has_mode_diffculte';

    /**
     * Objet référent.
     *
     * @var \Commun\Model\ZoneHasModeDiffculte
     */
    protected $arrayObjectPrototypeClass = '\\Commun\\Model\\ZoneHasModeDiffculte';

    /**
     * Clé primaire de la table.
     *
     * @var int
     */
    protected $nomCle = 'idZone';

}


text:
package org.openuap.cms.node.permission.manager.impl;

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

import org.openuap.cms.CmsPlugin;
import org.openuap.cms.node.manager.NodeManager;
import org.openuap.cms.node.model.Node;
import org.openuap.cms.node.permission.manager.NodePermissionManager;
import org.openuap.cms.node.security.NodePermissionConstant;
import org.openuap.cms.publish.security.PublishPermissionConstant;
import org.openuap.cms.resource.security.ResourcePermissionConstant;
import org.openuap.cms.user.manager.IPermissionManager;
import org.openuap.cms.user.manager.IRoleManager;
import org.openuap.cms.user.model.IRole;
import org.openuap.cms.user.model.IUser;
import org.openuap.passport.sso.UnauthorizedException;
import org.openuap.runtime.util.ObjectLocator;

/**
 *

 * 缺省结点权限管理实现
 *

 *
 *

 * $Id: DefaultNodePermissionManager.java 3964 2010-12-09 15:23:48Z orangeforjava $
 *

 *
 * @author Joseph
 * @version 1.0
 */
public class DefaultNodePermissionManager implements NodePermissionManager {
	private IPermissionManager permissionManager;
	private IRoleManager roleManager;

	private NodeManager nodeManager;

	public List<IUser> getInheritUsers(Long nodeId) {
		Node node = getNodeManager().getNode(nodeId);
		List<IUser> rs = new ArrayList<IUser>();
		if (node != null) {
			Long pid = node.getParentId();
			if (pid != 0L) {
				rs.addAll(getNodeUsers(pid));
				rs.addAll(getInheritUsers(pid));
			}
		}
		return rs;
	}

	public List<IRole> getNodeRoles(Long nodeId) {
		return getPermissionManager().getObjRoles(nodeId.toString(),
				NodePermissionConstant.OBJECT_TYPE);
	}

	public List<IUser> getNodeUsers(Long nodeId) {
		return getPermissionManager().getObjUsers(nodeId.toString(),
				NodePermissionConstant.OBJECT_TYPE);
	}

	public void initNodeRole(Long nodeId) {
		// 建立角色
		createAllRole(nodeId);

	}

	public void reinitNodeRole(Long nodeId) {
		initNodeRole(nodeId);
	}

	protected void createAllRole(Long nodeId) {
		createRole(nodeId, ROLE_ANONYMOUS, ROLE_ANONYMOUS_NAME);
		createRole(nodeId, ROLE_MEMBER, ROLE_MEMBER_NAME);
		createRole(nodeId, ROLE_INPUT, ROLE_INPUT_NAME);
		createRole(nodeId, ROLE_EDITOR, ROLE_EDITOR_NAME);
		createRole(nodeId, ROLE_SUPER_EDITOR, ROLE_SUPER_EDITOR_NAME);
		createRole(nodeId, ROLE_MAINTAIN, ROLE_MAINTAIN_NAME);
		createRole(nodeId, ROLE_ADMIN, ROLE_ADMIN_NAME);
	}

	protected void createRole(Long nodeId, String name, String title) {
		String guid = nodeId + "-" + name;
		IRole role = getRoleManager().getRoleByGuid(nodeId + "-" + name);
		if (role == null) {
			role = getRoleManager().createRole();
			long now = System.currentTimeMillis();
			role.setGuid(guid);
			role.setTitle(title);
			role.setName(name);
			role.setCreationDate(now);
			role.setDescription(title);
			role.setModificationDate(now);
			role.setStatus(0);
			role.setPos(0);
			try {
				Long roleId = getRoleManager().addRole(role);
				role.setRoleId(roleId);
			} catch (UnauthorizedException e) {
				e.printStackTrace();
			}
		}
		//
		Long roleId = role.getRoleId();
		if (name.equals(ROLE_ANONYMOUS)) {
			// 匿名用户暂不设置权限
			getPermissionManager()
					.setRolePermission(roleId,
							PublishPermissionConstant.OBJECT_TYPE,
							nodeId.toString(), 0);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_ANONYMOUS);
		} else if (name.equals(ROLE_MEMBER)) {
			// 会员用户暂时给予查看权限
			getPermissionManager().setRolePermission(roleId,
					PublishPermissionConstant.OBJECT_TYPE, nodeId.toString(),
					PublishPermissionConstant.ROLE_MEMBER);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_MEMBER);
		} else if (name.equals(ROLE_INPUT)) {
			// 撰稿人赋予写作权限
			getPermissionManager().setRolePermission(roleId,
					PublishPermissionConstant.OBJECT_TYPE, nodeId.toString(),
					PublishPermissionConstant.ROLE_INPUT);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_INPUT);
		} else if (name.equals(ROLE_EDITOR)) {
			// 编辑给予写作、发布权限
			getPermissionManager().setRolePermission(roleId,
					PublishPermissionConstant.OBJECT_TYPE, nodeId.toString(),
					PublishPermissionConstant.ROLE_EDITOR);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_EDITOR);
			getPermissionManager().setRolePermission(roleId,
					ResourcePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					ResourcePermissionConstant.Admin);
		} else if (name.equals(ROLE_SUPER_EDITOR)) {
			// 总编赋予写作、发布、编辑模板、编辑结点权限
			getPermissionManager().setRolePermission(
					roleId,
					PublishPermissionConstant.OBJECT_TYPE,
					nodeId.toString(),
					PublishPermissionConstant.ROLE_EDITOR
							| PublishPermissionConstant.ROLE_MAINTAIN);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_SUPER_EDITOR);
			//资源权限
			getPermissionManager().setRolePermission(roleId,
					ResourcePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					ResourcePermissionConstant.Admin);

		} else if (name.equals(ROLE_MAINTAIN)) {
			// 站点维护员,编辑结点设置,编辑模板,如果有必要的话
			getPermissionManager().setRolePermission(roleId,
					PublishPermissionConstant.OBJECT_TYPE, nodeId.toString(),
					PublishPermissionConstant.ROLE_MAINTAIN);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_MAINTAIN);
		} else if (name.equals(ROLE_ADMIN)) {
			// 站点管理员,所有权限
			getPermissionManager().setRolePermission(roleId,
					PublishPermissionConstant.OBJECT_TYPE, nodeId.toString(),
					PublishPermissionConstant.ROLE_ADMIN);
			getPermissionManager().setRolePermission(roleId,
					NodePermissionConstant.OBJECT_TYPE, nodeId.toString(),
					NodePermissionConstant.ROLE_ADMIN);

		}

	}

	protected void createRolePermission(Long nodeId, String name) {
		//
		String guid = nodeId + "-" + name;
		IRole role = getRoleManager().getRoleByGuid(guid);
		if (role != null) {

		}

	}

	public NodeManager getNodeManager() {
		if (nodeManager == null) {
			nodeManager = (NodeManager) ObjectLocator.lookup("nodeManager",
					CmsPlugin.PLUGIN_ID);
		}
		return nodeManager;
	}

	public void setNodeManager(NodeManager nodeManager) {
		this.nodeManager = nodeManager;
	}

	public IPermissionManager getPermissionManager() {
		if (permissionManager == null) {
			permissionManager = (IPermissionManager) ObjectLocator.lookup(
					"permissionManager", CmsPlugin.PLUGIN_ID);
		}
		return permissionManager;
	}

	public void setPermissionManager(IPermissionManager permissionManager) {
		this.permissionManager = permissionManager;
	}

	public IRoleManager getRoleManager() {
		if (roleManager == null) {
			roleManager = (IRoleManager) ObjectLocator.lookup(
					"baseRoleManager",  CmsPlugin.PLUGIN_ID);
		}
		return roleManager;
	}

	public void setRoleManager(IRoleManager roleManager) {
		this.roleManager = roleManager;
	}

}


text:
/*
 * Licensed 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.
 */
package com.facebook.presto.execution.scheduler.nodeSelection;

import com.facebook.airlift.log.Logger;
import com.facebook.presto.execution.NodeTaskMap;
import com.facebook.presto.execution.RemoteTask;
import com.facebook.presto.execution.scheduler.BucketNodeMap;
import com.facebook.presto.execution.scheduler.InternalNodeInfo;
import com.facebook.presto.execution.scheduler.ModularHashingNodeProvider;
import com.facebook.presto.execution.scheduler.NodeAssignmentStats;
import com.facebook.presto.execution.scheduler.NodeMap;
import com.facebook.presto.execution.scheduler.NodeSelectionHashStrategy;
import com.facebook.presto.execution.scheduler.SplitPlacementResult;
import com.facebook.presto.metadata.InternalNode;
import com.facebook.presto.metadata.InternalNodeManager;
import com.facebook.presto.metadata.Split;
import com.facebook.presto.spi.NodeProvider;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.SplitContext;
import com.facebook.presto.spi.SplitWeight;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.ToLongFunction;

import static com.facebook.presto.execution.scheduler.NodeScheduler.calculateLowWatermark;
import static com.facebook.presto.execution.scheduler.NodeScheduler.canAssignSplitBasedOnWeight;
import static com.facebook.presto.execution.scheduler.NodeScheduler.randomizedNodes;
import static com.facebook.presto.execution.scheduler.NodeScheduler.selectDistributionNodes;
import static com.facebook.presto.execution.scheduler.NodeScheduler.selectExactNodes;
import static com.facebook.presto.execution.scheduler.NodeScheduler.selectNodes;
import static com.facebook.presto.execution.scheduler.NodeScheduler.toWhenHasSplitQueueSpaceFuture;
import static com.facebook.presto.execution.scheduler.NodeSelectionHashStrategy.MODULAR_HASHING;
import static com.facebook.presto.metadata.InternalNode.NodeStatus.DEAD;
import static com.facebook.presto.spi.StandardErrorCode.NODE_SELECTION_NOT_SUPPORTED;
import static com.facebook.presto.spi.StandardErrorCode.NO_NODES_AVAILABLE;
import static com.facebook.presto.spi.schedule.NodeSelectionStrategy.HARD_AFFINITY;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class SimpleNodeSelector
        implements NodeSelector
{
    private static final Logger log = Logger.get(SimpleNodeSelector.class);

    private final InternalNodeManager nodeManager;
    private final NodeSelectionStats nodeSelectionStats;
    private final NodeTaskMap nodeTaskMap;
    private final boolean includeCoordinator;
    private final AtomicReference<Supplier<NodeMap>> nodeMap;
    private final int minCandidates;
    private final long maxSplitsWeightPerNode;
    private final long maxPendingSplitsWeightPerTask;
    private final int maxUnacknowledgedSplitsPerTask;
    private final int maxTasksPerStage;
    private final NodeSelectionHashStrategy nodeSelectionHashStrategy;

    public SimpleNodeSelector(
            InternalNodeManager nodeManager,
            NodeSelectionStats nodeSelectionStats,
            NodeTaskMap nodeTaskMap,
            boolean includeCoordinator,
            Supplier<NodeMap> nodeMap,
            int minCandidates,
            long maxSplitsWeightPerNode,
            long maxPendingSplitsWeightPerTask,
            int maxUnacknowledgedSplitsPerTask,
            int maxTasksPerStage,
            NodeSelectionHashStrategy nodeSelectionHashStrategy)
    {
        this.nodeManager = requireNonNull(nodeManager, "nodeManager is null");
        this.nodeSelectionStats = requireNonNull(nodeSelectionStats, "nodeSelectionStats is null");
        this.nodeTaskMap = requireNonNull(nodeTaskMap, "nodeTaskMap is null");
        this.includeCoordinator = includeCoordinator;
        this.nodeMap = new AtomicReference<>(nodeMap);
        this.minCandidates = minCandidates;
        this.maxSplitsWeightPerNode = maxSplitsWeightPerNode;
        this.maxPendingSplitsWeightPerTask = maxPendingSplitsWeightPerTask;
        this.maxUnacknowledgedSplitsPerTask = maxUnacknowledgedSplitsPerTask;
        checkArgument(maxUnacknowledgedSplitsPerTask > 0, "maxUnacknowledgedSplitsPerTask must be > 0, found: %s", maxUnacknowledgedSplitsPerTask);
        this.maxTasksPerStage = maxTasksPerStage;
        this.nodeSelectionHashStrategy = requireNonNull(nodeSelectionHashStrategy, "nodeSelectionHashStrategy is null");
    }

    @Override
    public void lockDownNodes()
    {
        nodeMap.set(Suppliers.ofInstance(nodeMap.get().get()));
    }

    @Override
    public List<InternalNode> getActiveNodes()
    {
        return ImmutableList.copyOf(nodeMap.get().get().getActiveNodes());
    }

    @Override
    public List<InternalNode> getAllNodes()
    {
        return ImmutableList.copyOf(nodeMap.get().get().getAllNodes());
    }

    @Override
    public InternalNode selectCurrentNode()
    {
        // TODO: this is a hack to force scheduling on the coordinator
        return nodeManager.getCurrentNode();
    }

    @Override
    public List<InternalNode> selectRandomNodes(int limit, Set<InternalNode> excludedNodes)
    {
        return selectNodes(limit, randomizedNodes(nodeMap.get().get(), includeCoordinator, excludedNodes));
    }

    @Override
    public SplitPlacementResult computeAssignments(Set<Split> splits, List<RemoteTask> existingTasks)
    {
        Multimap<InternalNode, Split> assignment = HashMultimap.create();
        NodeMap nodeMap = this.nodeMap.get().get();
        NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks);

        List<InternalNode> eligibleNodes = getEligibleNodes(maxTasksPerStage, nodeMap, existingTasks);
        NodeSelection randomNodeSelection = new RandomNodeSelection(eligibleNodes, minCandidates);
        Set<InternalNode> blockedExactNodes = new HashSet<>();
        boolean splitWaitingForAnyNode = false;

        NodeProvider nodeProvider = nodeMap.getActiveNodeProvider(nodeSelectionHashStrategy);

        OptionalInt preferredNodeCount = OptionalInt.empty();
        for (Split split : splits) {
            List<InternalNode> candidateNodes;
            switch (split.getNodeSelectionStrategy()) {
                case HARD_AFFINITY:
                    candidateNodes = selectExactNodes(nodeMap, split.getPreferredNodes(nodeProvider), includeCoordinator);
                    preferredNodeCount = OptionalInt.of(candidateNodes.size());
                    break;
                case SOFT_AFFINITY:
                    // Using all nodes for soft affinity scheduling with modular hashing because otherwise temporarily down nodes would trigger too much rehashing
                    if (nodeSelectionHashStrategy == MODULAR_HASHING) {
                        nodeProvider = new ModularHashingNodeProvider(nodeMap.getAllNodes());
                    }
                    candidateNodes = selectExactNodes(nodeMap, split.getPreferredNodes(nodeProvider), includeCoordinator);
                    preferredNodeCount = OptionalInt.of(candidateNodes.size());
                    candidateNodes = ImmutableList.<InternalNode>builder()
                            .addAll(candidateNodes)
                            .addAll(randomNodeSelection.pickNodes(split))
                            .build();
                    break;
                case NO_PREFERENCE:
                    candidateNodes = randomNodeSelection.pickNodes(split);
                    break;
                default:
                    throw new PrestoException(NODE_SELECTION_NOT_SUPPORTED, format("Unsupported node selection strategy %s", split.getNodeSelectionStrategy()));
            }

            if (candidateNodes.isEmpty()) {
                log.debug("No nodes available to schedule %s. Available nodes %s", split, nodeMap.getActiveNodes());
                throw new PrestoException(NO_NODES_AVAILABLE, "No nodes available to run query");
            }

            SplitWeight splitWeight = split.getSplitWeight();
            Optional<InternalNodeInfo> chosenNodeInfo = chooseLeastBusyNode(splitWeight, candidateNodes, assignmentStats::getTotalSplitsWeight, preferredNodeCount, maxSplitsWeightPerNode, assignmentStats);
            if (!chosenNodeInfo.isPresent()) {
                chosenNodeInfo = chooseLeastBusyNode(splitWeight, candidateNodes, assignmentStats::getQueuedSplitsWeightForStage, preferredNodeCount, maxPendingSplitsWeightPerTask, assignmentStats);
            }

            if (chosenNodeInfo.isPresent()) {
                split = new Split(
                        split.getConnectorId(),
                        split.getTransactionHandle(),
                        split.getConnectorSplit(),
                        split.getLifespan(),
                        new SplitContext(chosenNodeInfo.get().isCacheable()));

                InternalNode chosenNode = chosenNodeInfo.get().getInternalNode();
                assignment.put(chosenNode, split);
                assignmentStats.addAssignedSplit(chosenNode, splitWeight);
            }
            else {
                if (split.getNodeSelectionStrategy() != HARD_AFFINITY) {
                    splitWaitingForAnyNode = true;
                }
                // Exact node set won't matter, if a split is waiting for any node
                else if (!splitWaitingForAnyNode) {
                    blockedExactNodes.addAll(candidateNodes);
                }
            }
        }

        ListenableFuture<?> blocked;
        if (splitWaitingForAnyNode) {
            blocked = toWhenHasSplitQueueSpaceFuture(existingTasks, calculateLowWatermark(maxPendingSplitsWeightPerTask));
        }
        else {
            blocked = toWhenHasSplitQueueSpaceFuture(blockedExactNodes, existingTasks, calculateLowWatermark(maxPendingSplitsWeightPerTask));
        }
        return new SplitPlacementResult(blocked, assignment);
    }

    @Override
    public SplitPlacementResult computeAssignments(Set<Split> splits, List<RemoteTask> existingTasks, BucketNodeMap bucketNodeMap)
    {
        return selectDistributionNodes(nodeMap.get().get(), nodeTaskMap, maxSplitsWeightPerNode, maxPendingSplitsWeightPerTask, maxUnacknowledgedSplitsPerTask, splits, existingTasks, bucketNodeMap, nodeSelectionStats);
    }

    protected Optional<InternalNodeInfo> chooseLeastBusyNode(SplitWeight splitWeight, List<InternalNode> candidateNodes, ToLongFunction<InternalNode> splitWeightProvider, OptionalInt preferredNodeCount, long maxSplitsWeight, NodeAssignmentStats assignmentStats)
    {
        long minWeight = Long.MAX_VALUE;
        InternalNode chosenNode = null;
        for (int i = 0; i < candidateNodes.size(); i++) {
            InternalNode node = candidateNodes.get(i);
            if (node.getNodeStatus() == DEAD) {
                // Node is down. Do not schedule split. Skip it.
                if (preferredNodeCount.isPresent() && i < preferredNodeCount.getAsInt()) {
                    nodeSelectionStats.incrementPreferredNonAliveNodeSkippedCount();
                }
                continue;
            }

            if (assignmentStats.getUnacknowledgedSplitCountForStage(node) >= maxUnacknowledgedSplitsPerTask) {
                continue;
            }
            long currentWeight = splitWeightProvider.applyAsLong(node);
            boolean canAssignToNode = canAssignSplitBasedOnWeight(currentWeight, maxSplitsWeight, splitWeight);

            // choose the preferred node first as long as they're not busy
            if (preferredNodeCount.isPresent() && i < preferredNodeCount.getAsInt() && canAssignToNode) {
                if (i == 0) {
                    nodeSelectionStats.incrementPrimaryPreferredNodeSelectedCount();
                }
                else {
                    nodeSelectionStats.incrementNonPrimaryPreferredNodeSelectedCount();
                }
                return Optional.of(new InternalNodeInfo(node, true));
            }
            // fallback to choosing the least busy nodes
            if (canAssignToNode && currentWeight < minWeight) {
                chosenNode = node;
                minWeight = currentWeight;
            }
        }
        if (chosenNode == null) {
            return Optional.empty();
        }
        nodeSelectionStats.incrementNonPreferredNodeSelectedCount();
        return Optional.of(new InternalNodeInfo(chosenNode, false));
    }

    private List<InternalNode> getEligibleNodes(int limit, NodeMap nodeMap, List<RemoteTask> existingTasks)
    {
        List<InternalNode> existingNodes = existingTasks.stream()
                .map(remoteTask -> nodeMap.getActiveNodesByNodeId().get(remoteTask.getNodeId()))
                // nodes may sporadically disappear from the nodeMap if the announcement is delayed
                .filter(Objects::nonNull)
                .collect(toList());

        int alreadySelectedNodeCount = existingNodes.size();
        int nodeCount = nodeMap.getActiveNodesByNodeId().size();

        if (alreadySelectedNodeCount < limit && alreadySelectedNodeCount < nodeCount) {
            List<InternalNode> moreNodes = selectNodes(limit - alreadySelectedNodeCount, randomizedNodes(nodeMap, includeCoordinator, newHashSet(existingNodes)));
            existingNodes.addAll(moreNodes);
        }
        verify(existingNodes.stream().allMatch(Objects::nonNull), "existingNodes list must not contain any nulls");
        return existingNodes;
    }
}


text:
#Region "License"

' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.

#End Region

Imports System.Threading.Tasks

Friend NotInheritable Class HistoricalDataUpdateParser
    Inherits ParserBase
    Implements IParser

    Private Const ModuleName As String = NameOf(HistoricalDataUpdateParser)

    Friend Overrides Async Function ParseAsync(pVersion As Integer, timestamp As Date) As Task(Of Boolean)
        Dim reqId = Await _Reader.GetIntAsync("Request id")
        Dim requestId = IdManager.GetCallerId(reqId, IdType.HistoricalData)

        Dim bar As New Bar With {
                .TickVolume = Await _Reader.GetLongAsync("Tick Volume"),
                .TimeStamp = IBAPI.TwsDateStringToDate(Await _Reader.GetStringAsync("Bar date")).theDate,
                .OpenValue = Await _Reader.GetDoubleAsync("Open"),
                .CloseValue = Await _Reader.GetDoubleAsync("Close"),
                .HighValue = Await _Reader.GetDoubleAsync("High"),
                .LowValue = Await _Reader.GetDoubleAsync("Low"),
                .WAP = Await _Reader.GetDoubleAsync("WAP"),
                .Volume = Await _Reader.GetLongAsync("Volume")
            }

        LogSocketInputMessage(ModuleName, "ParseAsync")

        Try
            _EventConsumers.HistoricalDataConsumer?.UpdateHistoricalBar(New HistoricalBarEventArgs(timestamp, requestId, bar))
            Return True
        Catch e As Exception
            Throw New ApiApplicationException("UpdateHistoricalData", e)
        End Try
    End Function

    Friend Overrides ReadOnly Property MessageType As ApiSocketInMsgType
        Get
            Return ApiSocketInMsgType.HistoricalDataUpdate
        End Get
    End Property

End Class


text:
<?php

/**
 * @see Zend_Paginator_ScrollingStyle_Elastic
 */
require_once 'Zend/Paginator/ScrollingStyle/Elastic.php';

/**
 * @see PHPUnit_Framework_TestCase
 */

/**
 * @see Zend_Paginator
 */
require_once 'Zend/Paginator.php';

/**
 * @category   Zend
 * @package    Zend_Paginator
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Paginator
 */
class Zend_Paginator_ScrollingStyle_ElasticTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var Zend_Paginator_ScrollingStyle_Elastic
     */
    private $_scrollingStyle;
    /**
     * @var Zend_Paginator
     */
    private $_paginator;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->_scrollingStyle = new Zend_Paginator_ScrollingStyle_Elastic();
        $this->_paginator = Zend_Paginator::factory(range(1, 101));
        $this->_paginator->setItemCountPerPage(5);
        $this->_paginator->setPageRange(5);
    }
    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->_scrollingStyle = null;
        $this->_paginator = null;
        parent::tearDown();
    }

    public function testGetsPagesInRangeForFirstPage()
    {
        $this->_paginator->setCurrentPageNumber(1);
        $actual = $this->_scrollingStyle->getPages($this->_paginator);
        $expected = array_combine(range(1, 5), range(1, 5));
        $this->assertEquals($expected, $actual);
    }

    public function testGetsPagesInRangeForSecondPage()
    {
        $this->_paginator->setCurrentPageNumber(2);
        $actual = $this->_scrollingStyle->getPages($this->_paginator);
        $expected = array_combine(range(1, 6), range(1, 6));
        $this->assertEquals($expected, $actual);
    }

    public function testGetsPagesInRangeForTenthPage()
    {
        $this->_paginator->setCurrentPageNumber(10);
        $actual = $this->_scrollingStyle->getPages($this->_paginator);
        $expected = array_combine(range(6, 14), range(6, 14));
        $this->assertEquals($expected, $actual);
    }

    public function testGetsPagesInRangeForLastPage()
    {
        $this->_paginator->setCurrentPageNumber(21);
        $actual = $this->_scrollingStyle->getPages($this->_paginator);
        $expected = array_combine(range(17, 21), range(17, 21));
        $this->assertEquals($expected, $actual);
    }

    public function testGetsNextAndPreviousPageForFirstPage()
    {
        $this->_paginator->setCurrentPageNumber(1);
        $pages = $this->_paginator->getPages('Elastic');

        $this->assertEquals(2, $pages->next);
    }

    public function testGetsNextAndPreviousPageForSecondPage()
    {
        $this->_paginator->setCurrentPageNumber(2);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(1, $pages->previous);
        $this->assertEquals(3, $pages->next);
    }

    public function testGetsNextAndPreviousPageForMiddlePage()
    {
        $this->_paginator->setCurrentPageNumber(10);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(9, $pages->previous);
        $this->assertEquals(11, $pages->next);
    }

    public function testGetsNextAndPreviousPageForSecondLastPage()
    {
        $this->_paginator->setCurrentPageNumber(20);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(19, $pages->previous);
        $this->assertEquals(21, $pages->next);
    }

    public function testGetsNextAndPreviousPageForLastPage()
    {
        $this->_paginator->setCurrentPageNumber(21);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(20, $pages->previous);
    }

    public function testNoPagesOnLastPageEqualsPageRange()
    {
        $this->_paginator->setPageRange(3);
        $this->_paginator->setCurrentPageNumber(21);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(3, count($pages->pagesInRange));
    }

    public function testNoPagesOnSecondLastPageEqualsPageRangeMinOne()
    {
        $this->_paginator->setPageRange(3);
        $this->_paginator->setCurrentPageNumber(20);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(4, count($pages->pagesInRange));
    }

    public function testNoPagesBeforeSecondLastPageEqualsPageRangeMinTwo()
    {
        $this->_paginator->setPageRange(3);
        $this->_paginator->setCurrentPageNumber(19);
        $pages = $this->_paginator->getPages('Elastic');
        $this->assertEquals(5, count($pages->pagesInRange));
    }
}


text:
<?php

/**
 * Represents a bid of a certain amount.
 * @package    Google_Api_Ads_AdWords_v201605
 * @subpackage v201605
 */
class Bid
{

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
    const XSI_TYPE = "Bid";

    /**
     * @access public
     * @var Money
     */
    public $amount;

    /**
     * Gets the namesapce of this class
     * @return string the namespace of this class
     */
    public function getNamespace()
    {
        return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return string the xsi:type name of this class
     */
    public function getXsiTypeName()
    {
        return self::XSI_TYPE;
    }

    public function __construct($amount = null)
    {
        $this->amount = $amount;
    }

}


text:
from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper

class Application:

    def __init__(self):
        # контруктор, который инициализирует ссылку на драйвер и на помощников
        self.wd = WebDriver()
        self.session = SessionHelper(self)
        self.group = GroupHelper(self)
        self.contact = ContactHelper(self)

    def is_valid(self):
        try:
            #какой адрес страницы
            self.wd.current_url
            return True
        except:
            return False

    def open_home_page(self):
        # навигация
        wd = self.wd
        wd.get("http://localhost/addressbook/")

    def destroy(self):
        # метод разрушает фикстуру
        self.wd.quit()


text:
package org.sirix.diff.export;

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.sirix.diff.DiffFactory.DiffType;
import org.sirix.diff.DiffTuple;

/**
 * Builds an edit script.
 *
 * @author Johannes Lichtenberger, University of Konstanz
 *
 */
public final class EditScript implements Iterator<DiffTuple>, Iterable<DiffTuple> {

  /** Preserves the order of changes and is used to iterate over all changes. */
  private final List<DiffTuple> mChanges;

  /** To do a lookup; we use node/object identities. */
  private final IdentityHashMap<Long, DiffTuple> mChangeByNode;

  /** Index in the {@link List} of {@link DiffTuple}s. */
  private transient int mIndex;

  /**
   * Constructor.
   */
  public EditScript() {
    mChanges = new ArrayList<DiffTuple>();
    mChangeByNode = new IdentityHashMap<Long, DiffTuple>();
    mIndex = 0;
  }

  /**
   * Calculates the size of the edit script. This can be used to estimate the amicability of an
   * algorithm.
   *
   * @return number of changes
   */
  public int size() {
    return mChanges.size();
  }

  /**
   * Checks if the edit script is empty.
   *
   * @return true if empty
   */
  public boolean isEmpty() {
    return mChanges.isEmpty();
  }

  /**
   * Checks if a node has been added(changed).
   *
   * @param key key of node
   * @return true if the changes {@link List} already contains the nodeKey, false otherwise
   */
  public boolean containsNode(final long key) {
    if (key < 0) {
      throw new IllegalArgumentException("paramKey may not be < 0!");
    }
    return mChangeByNode.containsKey(key);
  }

  /**
   * Clears the edit script.
   */
  public void clear() {
    mChanges.clear();
    mChangeByNode.clear();
  }

  /**
   * Look up a change for the given nodeKey.
   *
   * @param paramKey (not) changed key of node
   * @return the change assigned to the node or null
   */
  public DiffTuple get(final long paramKey) {
    return mChangeByNode.get(paramKey);
  }

  /**
   * Adds a change to the edit script.
   *
   * @param change {@link DiffTuple} reference
   * @return the change
   */
  public DiffTuple add(final DiffTuple change) {
    assert change != null;
    final long nodeKey =
        change.getDiff() == DiffType.DELETED ? change.getOldNodeKey() : change.getNewNodeKey();
    if (mChangeByNode.containsKey(nodeKey)) {
      return change;
    }

    mChanges.add(change);
    return mChangeByNode.put(nodeKey, change);
  }

  @Override
  public Iterator<DiffTuple> iterator() {
    return mChanges.iterator();
  }

  @Override
  public boolean hasNext() {
    if (mIndex < mChanges.size() - 1) {
      return true;
    }
    return false;
  }

  @Override
  public DiffTuple next() {
    if (mIndex < mChanges.size()) {
      return mChanges.get(mIndex++);
    } else {
      throw new NoSuchElementException("No more elements in the change list!");
    }
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException("Remove is not supported!");
  }

}


text:
package eml.studio.client.ui.widget.command;

import java.util.logging.Logger;

public class ValueCheck {
  private static Logger logger = Logger.getLogger(ValueCheck.class.getName());

  /**
   * Validate the value
   * @param type The value type
   * @param value The string value
   * @return The real object of the value
   */
  public static Object validate(String type, String value) {

    Object res = null;
    try {
      if ("int".equals(type.toLowerCase())) {
        res = Integer.parseInt(value.trim());
      } else if ("double".equals(type.toLowerCase()) || "float".equals(type.toLowerCase())) {
        res = Double.parseDouble(value.trim());
      } else if ("bool".equals(type.toLowerCase())
          || "boolean".equals(type.toLowerCase())) {
        value = value.trim();

        if (!("false".equals(value) || "False".equals(value)
            || "True".equals(value) || "true".equals(value)))
          return null;

        res = Boolean.parseBoolean(value);
      } else if( "string".equals(type.toLowerCase())){
        res = value;
      }
    } catch (Exception ex) {
      return null;
    }
    return res;

  }

  public static void validate(Parameter param, String value)
      throws ValueInvalidException {
    Object res = validate(param.getParamType(), value);
    if (res == null) {
      throw new ValueInvalidException("Parameter [" + param.getParaName() + "] value \""
          + value + "\" is invalide");
    }

    if ("int".equals(param.getParamType().toLowerCase())
        || "double".equals(param.getParamType().toLowerCase())) {
      double val;
      if ("int".equals(param.getParamType().toLowerCase()))
        val = (Integer) res;
      else
        val = (Double) res;

      String minStr = param.getMinValue();
      String maxStr = param.getMaxValue();

      if (minStr != null && !minStr.equals("")) {

        Double min = Double.parseDouble(minStr);

        if (min > val) {
          throw new ValueInvalidException("Parameter [" + param.getParaName()
              + "] should not small than " + minStr);
        }
      }

      if (maxStr != null && !maxStr.equals("")) {
        Double max = Double.parseDouble(maxStr);
        if (max < val) {
          throw new ValueInvalidException("Parameter [" + param.getParaName()
              + "] should not bigger than " + maxStr);
        }
      }

    }
  }
}


text:
<?php

namespace NextrasTests\Orm;

use Nextras\Orm\Repository\Repository;

/**
 * @method Publisher|NULL getById($id)
 */
final class PublishersRepository extends Repository
{
}


text:
@rem Copyright 2009 Ramnivas Laddad
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem     http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.

call ..\..\..\setHomes.bat
call ..\..\..\setEnvironment.bat
@echo off
cd src\main\java
mkdir classes
mkdir aspects
@echo on
javac -d classes ajia\messaging\MessageCommunicator.java ajia\main\Main.java ajia\security\AuthenticationException.java ajia\security\Authenticator.java
call javac -d aspects ajia\security\SecurityAspect.java
@rem Adding ..\resources to the classpath, since META-INF/aop.xml is in src/main/resources
call java -classpath classes;aspects;..\resources -javaagent:"%HOMEDRIVE%%HOMEPATH%\.m2\repository\org\aspectj\aspectjweaver\1.6.5\aspectjweaver-1.6.5.jar" ajia.main.Main
@echo off
cd ..\..\..\
@echo on


text:
boost::shared_mutex m;

#if defined BOOST_THREAD_USES_CHRONO
typedef boost::chrono::system_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef boost::chrono::milliseconds ms;
typedef boost::chrono::nanoseconds ns;
#else
#endif

void f()
{
#if defined BOOST_THREAD_USES_CHRONO
  boost::shared_lock < boost::shared_mutex > lk(m, boost::defer_lock);
  time_point t0 = Clock::now();
  lk.lock();
  time_point t1 = Clock::now();
  BOOST_TEST(lk.owns_lock() == true);
  ns d = t1 - t0 - ms(250);
  // This test is spurious as it depends on the time the thread system switches the threads
  BOOST_TEST(d < ns(2500000)+ms(1000)); // within 2.5ms
  try
  {
    lk.lock();
    BOOST_TEST(false);
  }
  catch (boost::system::system_error& e)
  {
    BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
  }
  lk.unlock();
  lk.release();
  try
  {
    lk.lock();
    BOOST_TEST(false);
  }
  catch (boost::system::system_error& e)
  {
    BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
  }
#else
  boost::shared_lock < boost::shared_mutex > lk(m, boost::defer_lock);
  //time_point t0 = Clock::now();
  lk.lock();
  //time_point t1 = Clock::now();
  BOOST_TEST(lk.owns_lock() == true);
  //ns d = t1 - t0 - ms(250);
  // This test is spurious as it depends on the time the thread system switches the threads
  //BOOST_TEST(d < ns(2500000)+ms(1000)); // within 2.5ms
  try
  {
    lk.lock();
    BOOST_TEST(false);
  }
  catch (boost::system::system_error& e)
  {
    BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
  }
  lk.unlock();
  lk.release();
  try
  {
    lk.lock();
    BOOST_TEST(false);
  }
  catch (boost::system::system_error& e)
  {
    BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
  }
#endif
}

int main()
{
  m.lock();
  boost::thread t(f);
#if defined BOOST_THREAD_USES_CHRONO
  boost::this_thread::sleep_for(ms(250));
#else
#endif
  m.unlock();
  t.join();

  return boost::report_errors();
}


text:
require "test/unit"
require "mime"

class TestMailbox < Test::Unit::TestCase #:nodoc:

  include Mime

  def test_mailbox
    # nil
    mailbox = Mailbox.new(nil)
    assert_equal(mailbox.to_s, "")

    # empty string
    mailbox = Mailbox.new("")
    assert_equal(mailbox.to_s, "")

    # addr spec
    mailbox = Mailbox.new("a.smith@foo.bar")
    assert_equal(mailbox.to_s, "a.smith@foo.bar")

    # addr spec enclosed in angle brackets
    mailbox = Mailbox.new("<a.smith@foo.bar>")
    assert_equal(mailbox.to_s, "<a.smith@foo.bar>")

    # display name
    mailbox = Mailbox.new("a.smith@foo.bar", "Allison Smith")
    assert_equal(mailbox.to_s, "Allison Smith <a.smith@foo.bar>")
    assert_equal(mailbox.to_s(true), "Allison Smith <a.smith@foo.bar>")

    # non-ascii characters
    mailbox = Mailbox.new("t.mueller@foo.bar", "Thomas Müller")
    assert_equal(mailbox.to_s, "Thomas Müller <t.mueller@foo.bar>")
    assert_equal(mailbox.to_s(true), "=?utf-8?Q?Thomas=20M=C3=BCller?= <t.mueller@foo.bar>")
  end
end


text:
package org.wso2.carbon.identity.mgt.store.connector.jdbc.connector.factory;

import org.wso2.carbon.identity.mgt.connector.IdentityStoreConnector;
import org.wso2.carbon.identity.mgt.connector.IdentityStoreConnectorFactory;
import org.wso2.carbon.identity.mgt.store.connector.jdbc.connector.JDBCIdentityStoreConnector;

/**
 * JDBC based identity store connector factory.
 */
public class JDBCIdentityStoreConnectorFactory implements IdentityStoreConnectorFactory {

    @Override
    public IdentityStoreConnector getInstance() {
        return new JDBCIdentityStoreConnector();
    }
}


text:
/**
* A standard byte (unsigned char)
* datatype. A byte is 8 bits.
* Can store values from 0 to 256
* There are no negative numbers in a byte (unsigned)
*/

#ifndef BYTE_H_
#define	BYTE_H_

#define	BYTE_MAX	0xFF
#define	BYTE_MIN	0x00

#define	byte	byte_t

typedef	unsigned char	byte_t;

#endif // BYTE_H_


text:
package xyz.jmullin.drifter

import xyz.jmullin.drifter.enrich.RichColor._
import xyz.jmullin.drifter.enrich.RichGeometry._

import scala.util.Random

/**
 * Convenience methods for getting simple randomized results. Random functions require an implicit
 * [[scala.util.Random]] instance. This allows for a fixed seed if repeatable random behavior is desirable.
 * A global [[Random]] instance with a nanotime seed is available at RandomUtil.Implicits.global if you prefer
 * not to supply your own.
 */
object RandomUtil {
  object Implicits {
    val global = new Random()
  }

  def probability(p: Double)(implicit r: Random) = r.nextDouble() <= p
  def rInt(n: Int)(implicit r: Random) = r.nextInt(n)
  def rInt(n:Int, m:Int)(implicit r: Random) = if(n == m) n else n+r.nextInt(m-n)
  def rFloat(n: Float)(implicit r: Random) = r.nextFloat()*n
  def rFloat(n: Float, m: Float)(implicit r: Random) = n+r.nextFloat()*(m-n)
  def rElement[T](s: Iterable[T])(implicit r: Random) = r.shuffle(s).head

  def rV(v: V2)(implicit r: Random) = V2(rFloat(v.x)(r), rFloat(v.y)(r))
  def rV(a: V2, b: V2)(implicit r: Random) = V2(rFloat(a.x, b.x)(r), rFloat(a.y, b.y)(r))
  def rV(r: Rect)(implicit ra: Random): V2 = rV(r.v, r.size)(ra)
  def rV(v: V3)(implicit r: Random) = V3(rFloat(v.x)(r), rFloat(v.y)(r), rFloat(v.z)(r))
  def rV(a: V3, b: V3)(implicit r: Random) = V3(rFloat(a.x, b.x)(r), rFloat(a.y, b.y)(r), rFloat(a.z, b.z)(r))
  def rColor(n: Float, m: Float)(implicit r: Random) = C(rFloat(n, m)(r), rFloat(n, m)(r), rFloat(n, m)(r))

  def shuffle[T](seq: Seq[T])(implicit r: Random) = r.shuffle(seq)
}


text:
title: Half Angle Formulas
localeTitle: Формулы полуугольника
---
## Формулы полуугольника

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/half-angle-formulas/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Дополнительная информация:


text:
<!DOCTYPE html>
<title>CSS Test: circle clip-path on svg graphics element with offset</title>
<link rel="help" href="https://crbug.com/1286412">
<link rel="help" href="https://drafts.fxtf.org/css-masking/#the-clip-path">
<link rel="match" href="svg-clip-path-circle-offset-ref.html">
<!-- Allow antialised pixel differences along the edge of the circle -->
<meta name="fuzzy" content="maxDifference=0-60; totalPixels=0-394">
<svg>
  <rect x="30" y="30" width="100" height="100" fill="green" style="clip-path: circle(50%)"/>
</svg>


text:
/**
  @file         integer.h
  @brief        utility for builtin integer types.
  @author       HRYKY
  @version      $Id: integer.h 324 2014-02-09 04:38:38Z hryky.private@gmail.com $
 */
#ifndef INTEGER_H_20120818200257502
#define INTEGER_H_20120818200257502
#include "hryky/integer/bits_enough_signed.h"
#include "hryky/integer/signed_enough.h"
#include "hryky/integer/bits_enough_unsigned.h"
#include "hryky/integer/unsigned_enough.h"
#include "hryky/integer/max_of.h"
#include "hryky/integer/min_of.h"
//------------------------------------------------------------------------------
// defines macros
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares types
//------------------------------------------------------------------------------
namespace hryky
{

} // namespace hryky
//------------------------------------------------------------------------------
// struct declaration
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares classes
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares global functions
//------------------------------------------------------------------------------
namespace hryky
{
} // namespace hryky
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
#endif // INTEGER_H_20120818200257502
// end of file


text:
=======
Credits
=======

Development Lead
----------------

* Engines-screaming <24savagefl@gmail.com>
* mcalsop

Contributors
------------

None yet. Why not be the first?


text:
@interface GLMerchat_CommentModel : NSObject

@property (nonatomic, assign)NSInteger index;

@property (nonatomic, copy)NSString *comment;

@property (nonatomic, copy)NSString *addtime;

@property (nonatomic, copy)NSString *reply_time;

@property (nonatomic, copy)NSString *reply;

@property (nonatomic, copy)NSString *mark;

@property (nonatomic, copy)NSString *pic;

@property (nonatomic, copy)NSString *user_name;

@property (nonatomic, copy)NSString *is_comment;

@property (nonatomic, copy)NSString *comment_id;

@end


text:
@interface AgoraChatCustomTableViewController ()

@end

@implementation AgoraChatCustomTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = UIColor.whiteColor;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return 0;
}

@end


text:
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

/** @file

    @version	$Id: simuconfig.cpp,v 1.4.2.3 2011/12/29 16:14:20 berniw Exp $
*/

#include <stdio.h>
#include <stdlib.h>
#include <tgfclient.h>
#include <raceinit.h>

#include "simuconfig.h"
#include <portability.h>

static float LabelColor[] = {1.0, 0.0, 1.0, 1.0};

/* list of available simulation engine */
static const char *simuVersionList[] = {"simuv2", "simuv3"};
static const int nbVersions = sizeof(simuVersionList) / sizeof(simuVersionList[0]);
static int curVersion = 0;

/* gui label id */
static int SimuVersionId;

/* gui screen handles */
static void	*scrHandle = NULL;
static void	*prevHandle = NULL;

static void ReadSimuCfg(void)
{
	const char *versionName;
	int i;

	const int BUFSIZE = 1024;
	char buf[BUFSIZE];
	snprintf(buf, BUFSIZE, "%s%s", GetLocalDir(), RACE_ENG_CFG);

	void *paramHandle = GfParmReadFile(buf, GFPARM_RMODE_REREAD | GFPARM_RMODE_CREAT);
	versionName = GfParmGetStr(paramHandle, "Modules", "simu", simuVersionList[0]);

	for (i = 0; i < nbVersions; i++) {
		if (strcmp(versionName, simuVersionList[i]) == 0) {
			curVersion = i;
			break;
		}
	}

	GfParmReleaseHandle(paramHandle);

	GfuiLabelSetText(scrHandle, SimuVersionId, simuVersionList[curVersion]);
}

/* Save the choosen values in the corresponding parameter file */
static void SaveSimuVersion(void * /* dummy */)
{
	const int BUFSIZE = 1024;
	char buf[BUFSIZE];
	snprintf(buf, BUFSIZE, "%s%s", GetLocalDir(), RACE_ENG_CFG);

	void *paramHandle = GfParmReadFile(buf, GFPARM_RMODE_REREAD | GFPARM_RMODE_CREAT);
	GfParmSetStr(paramHandle, "Modules", "simu", simuVersionList[curVersion]);
	GfParmWriteFile(NULL, paramHandle, "raceengine");
	GfParmReleaseHandle(paramHandle);

	/* return to previous screen */
	GfuiScreenActivate(prevHandle);
	return;
}

/* change the simulation version */
static void
ChangeSimuVersion(void *vp)
{
    if (vp == 0) {
	curVersion--;
	if (curVersion < 0) {
	    curVersion = nbVersions - 1;
	}
    } else {
	curVersion++;
	if (curVersion == nbVersions) {
	    curVersion = 0;
	}
    }
    GfuiLabelSetText(scrHandle, SimuVersionId, simuVersionList[curVersion]);
}

static void onActivate(void * /* dummy */)
{
        ReadSimuCfg();
}

/* Menu creation */
void *
SimuMenuInit(void *prevMenu)
{
    int		x, y, x2, x3, x4, dy;

    /* screen already created */
    if (scrHandle) {
	return scrHandle;
    }
    prevHandle = prevMenu;

    scrHandle = GfuiScreenCreateEx((float*)NULL, NULL, onActivate, NULL, (tfuiCallback)NULL, 1);
    GfuiTitleCreate(scrHandle, "Simulation Configuration", 0);
    GfuiScreenAddBgImg(scrHandle, "data/img/splash-simucfg.png");

    x = 20;
    x2 = 240;
    x3 = x2 + 100;
    x4 = x2 + 200;
    y = 370;
    dy = 30;

    y -= dy;
    GfuiLabelCreate(scrHandle, "Simulation version:", GFUI_FONT_MEDIUM, x, y, GFUI_ALIGN_HL_VB, 0);
    GfuiGrButtonCreate(scrHandle, "data/img/arrow-left.png", "data/img/arrow-left.png",
		       "data/img/arrow-left.png", "data/img/arrow-left-pushed.png",
		       x2, y, GFUI_ALIGN_HL_VB, 1,
		       (void*)-1, ChangeSimuVersion,
		       NULL, (tfuiCallback)NULL, (tfuiCallback)NULL);
    GfuiGrButtonCreate(scrHandle, "data/img/arrow-right.png", "data/img/arrow-right.png",
		       "data/img/arrow-right.png", "data/img/arrow-right-pushed.png",
		       x4, y, GFUI_ALIGN_HR_VB, 1,
		       (void*)1, ChangeSimuVersion,
		       NULL, (tfuiCallback)NULL, (tfuiCallback)NULL);
    SimuVersionId = GfuiLabelCreate(scrHandle, "", GFUI_FONT_MEDIUM_C, x3, y, GFUI_ALIGN_HC_VB, 32);
    GfuiLabelSetColor(scrHandle, SimuVersionId, LabelColor);

    GfuiButtonCreate(scrHandle, "Accept", GFUI_FONT_LARGE, 210, 40, 150, GFUI_ALIGN_HC_VB, GFUI_MOUSE_UP,
     NULL, SaveSimuVersion, NULL, (tfuiCallback)NULL, (tfuiCallback)NULL);

    GfuiButtonCreate(scrHandle, "Cancel", GFUI_FONT_LARGE, 430, 40, 150, GFUI_ALIGN_HC_VB, GFUI_MOUSE_UP,
     prevMenu, GfuiScreenActivate, NULL, (tfuiCallback)NULL, (tfuiCallback)NULL);

    GfuiAddKey(scrHandle, 13, "Save", NULL, SaveSimuVersion, NULL);
    GfuiAddKey(scrHandle, 27, "Cancel Selection", prevMenu, GfuiScreenActivate, NULL);
    GfuiAddSKey(scrHandle, GLUT_KEY_F12, "Screen-Shot", NULL, GfuiScreenShot, NULL);
    GfuiAddSKey(scrHandle, GLUT_KEY_LEFT, "Previous Version in list", (void*)0, ChangeSimuVersion, NULL);
    GfuiAddSKey(scrHandle, GLUT_KEY_RIGHT, "Next Version in list", (void*)1, ChangeSimuVersion, NULL);

    ReadSimuCfg();

    return scrHandle;
}


text:
package org.apache.ignite.internal.util;

import java.util.*;

/**
 * Hash table and linked list implementation of the {@code Set} interface,
 * with predictable iteration order. This implementation differs from
 * {@code HashSet} in that it maintains a doubly-linked list running through
 * all of its entries. This linked list defines the iteration ordering,
 * which is the order in which elements were inserted into the set
 * (insertion-order). Note that insertion order is not affected
 * if an element is re-inserted into the set. (An element {@code e}
 * is reinserted into a set {@code s} if {@code s.add(e)} is invoked when
 * {@code s.contains(e)} would return {@code true} immediately prior to
 * the invocation.)
 *

 * HashSet is also has maximum capacity. When it is reached the
 * newest elements supersede eldest ones.
 *
 * @param <E> Set element.
 *
 */
public class GridBoundedLinkedHashSet<E> extends GridSerializableSet<E> implements Cloneable {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    private static final Object FAKE = Boolean.TRUE;

    /** */
    @SuppressWarnings({"TransientFieldNotInitialized", "CollectionDeclaredAsConcreteClass"})
    private transient HashMap<E, Object> map;

    /**
     * Constructs a new, empty set; the backing {@code LinkedHashMap}
     * instance has default initial capacity (16) and load factor (0.75).
     *
     * @param maxCap Maximum set capacity.
     */
    public GridBoundedLinkedHashSet(int maxCap) {
        assert maxCap > 0;

        map = new GridBoundedLinkedHashMap<>(maxCap);
    }

    /**
     * Constructs a new set containing the elements in the specified collection.
     * The {@code LinkedHashMap} is created with default load factor (0.75)
     * and an initial capacity sufficient to contain the elements in the specified
     * collection.
     *
     * @param c The collection whose elements are to be placed into this set.
     * @param maxCap Maximum set capacity.
     */
    public GridBoundedLinkedHashSet(Collection<? extends E> c, int maxCap) {
        assert maxCap > 0;

        map = new GridBoundedLinkedHashMap<>(Math.max((int) (c.size() / 0.75f) + 1, 16), maxCap);

        addAll(c);
    }

    /**
     * Constructs a new, empty set; the backing {@code LinkedHashMap}
     * instance has the specified initial capacity and the specified load factor.
     *
     * @param initCap The initial capacity of the hash map.
     * @param maxCap Maximum set capacity.
     * @param loadFactor the Load factor of the hash map.
     */
    public GridBoundedLinkedHashSet(int initCap, int maxCap, float loadFactor) {
        assert maxCap > 0;

        map = new GridBoundedLinkedHashMap<>(initCap, maxCap, loadFactor);
    }

    /**
     * Constructs a new, empty set; the backing {@code LinkedHashMap}
     * instance has the specified initial capacity and the specified load factor.
     *
     * @param initCap The initial capacity of the hash map.
     * @param maxCap Maximum set capacity.
     * @param loadFactor the Load factor of the hash map.
     * @param accessOrder {@code True} for access order, {@code false} for insertion order.
     */
    public GridBoundedLinkedHashSet(int initCap, int maxCap, float loadFactor, boolean accessOrder) {
        assert maxCap > 0;

        map = new GridBoundedLinkedHashMap<>(initCap, maxCap, loadFactor, accessOrder);
    }

    /**
     * Constructs a new, empty set; the backing {@code LinkedHashHashMap}
     * instance has the specified initial capacity and default load factor, which
     * is {@code 0.75}.
     *
     * @param initCap The initial capacity of the hash table.
     * @param maxCap Maximum capacity.
     */
    public GridBoundedLinkedHashSet(int initCap, int maxCap) {
        assert maxCap > 0;

        map = new GridBoundedLinkedHashMap<>(initCap, maxCap);
    }

    /**
     * Returns an iterator over the elements in this set. The elements are
     * returned in no particular order.
     *
     * @return An iterator over the elements in this set.
     * @see ConcurrentModificationException
     */
    @Override public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    /**
     * Returns the number of elements in this set (its cardinality).
     *
     * @return The number of elements in this set (its cardinality).
     */
    @Override public int size() {
        return map.size();
    }

    /**
     * Returns {@code true} if this set contains no elements.
     *
     * @return {@code True} if this set contains no elements.
     */
    @Override public boolean isEmpty() {
        return map.isEmpty();
    }

    /**
     * Returns {@code true} if this set contains the specified element.
     *
     * @param o Element whose presence in this set is to be tested.
     * @return {@code true} if this set contains the specified element.
     */
    @SuppressWarnings({"SuspiciousMethodCalls"})
    @Override public boolean contains(Object o) {
        return map.containsKey(o);
    }

    /**
     * Adds the specified element to this set if it is not already present.
     *
     * @param o Element to be added to this set.
     * @return {@code True} if the set did not already contain the specified
     *      element.
     */
    @Override public boolean add(E o) {
        return map.put(o, FAKE) == null;
    }

    /**
     * Removes the specified element from this set if it is present.
     *
     * @param o Object to be removed from this set, if present.
     * @return {@code True} if the set contained the specified element.
     */
    @SuppressWarnings({"ObjectEquality"})
    @Override public boolean remove(Object o) {
        return map.remove(o) == FAKE;
    }

    /**
     * Removes all of the elements from this set.
     */
    @Override public void clear() {
        map.clear();
    }

    /**
     * Returns a shallow copy of this {@code GridBoundedLinkedHashSet}
     * instance: the elements themselves are not cloned.
     *
     * @return a shallow copy of this set.
     * @throws CloneNotSupportedException Thrown if cloning is not supported.
     */
    @SuppressWarnings("unchecked")
    @Override public Object clone() throws CloneNotSupportedException {
        GridBoundedLinkedHashSet<E> newSet = (GridBoundedLinkedHashSet<E>)super.clone();

        newSet.map = (HashMap<E, Object>)map.clone();

        return newSet;
    }
}


text:
Moved dimension calculations to its own library

Cleaned up build files for NPMCDN

### 0.4.2
Removed old code from `lib` folder

Make sure `package.json` cleans `lib` folder on each build

### 0.4.1
Fixed dist build

Updated to latest element-resize-detector

### 0.4.0

Moved away from MutationObserver's in favor of [element-resize-detector](https://github.com/wnr/element-resize-detector)

Added a more convenient API by allowing child functions [#11](https://github.com/souporserious/react-measure/issues/11)

`measure` is now a public method available on the Measure component

`accurate` prop now returns both cloned element width and height

`shouldMeasure` now accepts only a boolean

Removed `lodash.debounce` dependency

### 0.3.5

Fixed bug in IE with accurate height calculation when checking for children nodes.

Fixed [deprecation notice](https://www.chromestatus.com/features/5724912467574784) when calculating SVG dimensions.

Removed `react-addons-shallow-compare` dependency.

Moved `react` and `react-dom` packages into peer dependencies.

### 0.3.4

Fix server-side rendering

### 0.3.3

Added public method `getDimensions`

Clone nodes without any children

Fixed calculating measurements on resize

### 0.3.2

Patch to fix `shallowCompare` so bower works.

Added a resize handler to measure component changes on window resize.

### 0.3.1

Renamed `onChange` prop to `onMeasure`

Added `shouldMeasure` prop, similar to componentShouldUpdate. It determines whether or not the `onMeasure` callback will fire, useful for perf and not performing measurements if you don't need to.

Fixed updating of `config` prop to disconnect and reconnect a new MutationObserver with the new configuration

Fixed updaing of `whitelist` & `blacklist` props to use new values

### 0.3.0

Rebuilt from the ground up

No more cloning of elements!

Optimized to touch the DOM as least as possible

`clone`, `forceAutoHeight`, `collection` props removed

`config` prop added, accepts a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) configuration

`accurate` prop added, use to get an accurate measurement, only height supported right now

### 0.2.0

Upgraded to React 0.14.0

### 0.1.3

Added `forceAutoHeight` prop to help with proper height calculation when children heights are animating

### 0.1.2

Clone prop now exposed to allow optional cloning of component

Defaults to false which could potentially break components relying on cloned calculations

### 0.1.1

Set width/height to auto on clone no matter what to get a true dimension

Append clone directly after original instead of the end of its parent

Portal now gets destroyed after measurements have been calculated

### 0.1.0

Rewritten to be more React friendly

Measure component no longer accepts a child function, instead get dimensions by setting state in onChange callback


text:
/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */
/*
  Independent implementation of MD5 (RFC 1321).

  This code implements the MD5 Algorithm defined in RFC 1321, whose
  text is available at
	http://www.ietf.org/rfc/rfc1321.txt
  The code is derived from the text of the RFC, including the test suite
  (section A.5) but excluding the rest of Appendix A.  It does not include
  any code or documentation that is identified in the RFC as being
  copyrighted.

  The original and principal author of md5.h is L. Peter Deutsch
  <ghost@aladdin.com>.  Other authors are noted in the change history
  that follows (in reverse chronological order):

  2002-04-13 lpd Removed support for non-ANSI compilers; removed
	references to Ghostscript; clarified derivation from RFC 1321;
	now handles byte order either statically or dynamically.
  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
	added conditionalization for C++ compilation from Martin
	Purschke <purschke@bnl.gov>.
  1999-05-03 lpd Original version.
 */

#ifndef MD5_H__
#define MD5_H__

#include "macros.h"

#include <string>

namespace gloox
{

  /**
   * @brief An MD% implementation.
   *
   * This is an implementation of the Message Digest Algorithm as decribed in RFC 1321.
   * The original code has been taken from an implementation by L. Peter Deutsch.
   *
   * @author Jakob Schroeter <js@camaya.net>
   * @since 0.9
   */
  class GLOOX_API MD5
  {
    public:
      /**
       * Constructs a new MD5 object.
       */
      MD5();

      /**
       * Virtual Destructor.
       */
      virtual ~MD5();

      /**
       * Use this function to feed the hash.
       * @param data The data to hash.
       * @param bytes The size of @c data in bytes.
       */
      void feed( const unsigned char* data, int bytes );

      /**
       * Use this function to feed the hash.
       * @param data The data to hash.
       */
      void feed( const std::string& data );

      /**
       * This function is used to finalize the hash operation. Use it after the last feed() and
       * before calling hex().
       */
      void finalize();

      /**
       * Use this function to retrieve the hash value in hex.
       * @return The hash in hex notation.
       */
      const std::string hex();

      /**
       * Use this function to retrieve the raw binary hash.
       * @return The raw binary hash.
       */
      const std::string binary();

      /**
       * Use this function to reset the hash.
       */
      void reset();

    private:
      struct MD5State
      {
          unsigned int count[2]; /* message length in bits, lsw first */
          unsigned int abcd[4]; /* digest buffer */
          unsigned char buf[64]; /* accumulate block */
      } m_state;

      void init();
      void process( const unsigned char* data );

      static const unsigned char pad[64];

      bool m_finished;

  };

}

#endif // MD5_H__


text:
using Foundation.TestHelpers;
using Foundation.Web.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Foundation.Tests.TestHelpers
{
    [TestClass]
    public class MvcTestHelpersTests
    {
        public void Can_access_request_object()
        {
            var httpContextBase = MvcTestHelpers.GetHttpContextBase();
        }

        [TestMethod]
        public void Can_get_mocked_HttpContextBase()
        {
            var httpContextBase = MvcTestHelpers.GetHttpContextBase();
            Assert.IsNotNull(httpContextBase);
        }
    }
}


text:
__author__ = "Mari Wahl"
__copyright__ = "Copyright 2014"
__credits__ = ["Mari Wahl"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"

import pylab as plt
import os
import json
import numpy as np
from sklearn.svm import SVC
from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
from sklearn.metrics import zero_one_loss
from constants import  INPUT_FOLDER, OUTPUT_FOLDER, TYPE_NOR

def get_input_path(number, typen):
    return INPUT_FOLDER + 'together' + str(number) + '_train_0.8_' + typen +'.data'

def get_output_path(typen):
    if not os.path.exists(OUTPUT_FOLDER):
        os.makedirs(OUTPUT_FOLDER)
    outfolder = OUTPUT_FOLDER +  'feature_CV/'
    if not os.path.exists(outfolder):
        os.makedirs(outfolder)
    return outfolder + 'FEATURE_CV_set'  +  '_0.8_' + typen  +'.png'

def get_data_here(inputfile):
    data = np.loadtxt(inputfile, delimiter = ',')
    X = data[:,:-1]
    Y = data[:,-1]
    return X, Y

def main():
    color = ['r', 'b', 'y', 'g', 'c', 'm']
    # plot config
    with open("conf.json") as json_file:
       s = json.load(json_file)
    plt.rcParams.update(s)

    # for each type norm
    for typen in TYPE_NOR:
        print('\nStarting to plot for ' + typen)
        plt.cla()
        plt.clf()
        plt.figure()
        # for each set
        for number in range(1, 6):

            outputfile = get_output_path(typen)
            inputfile = get_input_path(number, typen)

            X, Y  = get_data_here(inputfile)
            svc = SVC()
            rfecv = RFECV(estimator=svc,  cv=StratifiedKFold(Y, 2), step=0.3,
                      scoring='accuracy', estimator_params={'kernel': 'linear'})
            rfecv.fit(X, Y)
            print("Optimal number of features : %d" % rfecv.n_features_)

            plt.ylim(0, 3)
            plt.xlim(1, 5.5)
            plt.xlabel("Number of features selected")
            plt.ylabel("Cross validation score (nb of misclassifications)")
            plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_, c=color[number-1], label="Set " +str(number))

        plt.legend(loc='best', fontsize=10)
        plt.savefig(outputfile, orientation='landscape')

    print('Done!\n')

if __name__ == '__main__':
    main()


text:
* fix(listeners): do not leak listeners on response end

# 5.0.0 (2016-02-20)

* fix(nodejs): emit end after ending response, not before fixes #11
* fix(XHR spec): handle sync XHRS
* fix(XHR spec): new request event is now only on send call, always async if no sync flag

# 4.2.1 (2015-12-08)

  * fix(0.10): fix gzip option in node 0.10

# 4.2.0 (2015-12-06)

  * feat(res): provide gzip option in install({gzip:true})

# 4.1.0 (2015-09-01)

  * fix: iojs fix by upgrading mitm

# 4.0.0 (2015-05-24)

  * event driven and nodejs support out of beta: it works
  * handle https: protocol in node.js

# 4.0.0-beta.2 (2015-04-07)

  * keep the event loop alive in Node.js

# 4.0.0-beta.1 (2015-04-02)

  * BREAKING CHANGE: faux-jax is now asyncrhonous by default, there's no more `.requests` property on the `fauxJax` object
    Now you need to: fauxJax.on('request', function(err, request) {})
    This was done while adding the Node.js compatibility and also because asynchronous requests (XHRS, Node.js http) ARE A-S-Y-N-C-H-R-O-N-O-U-S
  * FEATURE: Node.js compatibility, you can now intercept both on the browser and the server

# 3.0.1 (2015-03-10)

  * upgrade lodash to 3.5.0
  * upgrade writable-window-method to 1.0.3

# 3.0.0 (2015-03-07)

  * fix `getAllResponseHeaders()` implementation, returns a string, not an array

# 2.0.0 (2015-03-06)

  * tune XDomainRequest mock. No eventObject for IE8 in event listeners
  * no eventObject in progress events on all browsers when XDomainRequest

# 1.7.1 (2015-03-04)

  * throw when calling `fauxJax.install()` twice

# 1.7.0 (2015-03-04)

  * do not allow `.respond()` `.setResponseHeaders()` `.setResponseBody` when request timeout or error

# 1.6.0 (2015-02-26)

  * enhance XDomainRequest implem
  * use writable-window-method

# 1.5.1 (2015-02-25)

  * no more modifying the environment before any call to `fauxJax.install()`

# 1.5.0 (2015-02-25)

  * expose support flags through `fauxJax.support`

# 1.4.0 (2015-02-23)

  * do not force a Content-Type if body is null
  * do not force a charset if none set

# 1.3.0 (2015-02-16)

  * do not duplicate content-type header if case does not matches
  * setRequestHeader() compare header names in a case insensitive
  * setRequestHeader() appends header values

# 1.2.0 (2015-02-14)

  * better progress events
  * more feature detection, closer to native environment

# 1.1.0 (2015-02-13)

  * add IE7/8 compatiblity
  * add more feature detection (events, like onload not on IE7)
  * remove IE6 testing, there will be no compatibility
  * do not use deepEqual from tape on IE7/8, fails

# 1.0.2 (2015-02-12)

  * fix .install() when using XDomainRequest
  * tests ok on IE9
  * ISC => MIT

# 1.0.1 (2015-02-12)

  * [XDomainRequest](https://msdn.microsoft.com/en-us/library/ie/cc288060(v=vs.85).aspx) implementation

# 1.0.0 (2015-02-11)

  * initial


text:
macro_rules! add_macro_expanded_things_to_macro_prelude {() => {
    #[macro_use]
    extern crate macro_in_other_crate;
}}

add_macro_expanded_things_to_macro_prelude!();

mod m1 {
    fn check() {
        inline!(); // OK. Theoretically ambiguous, but we do not consider built-in attributes
                   // as candidates for non-attribute macro invocations to avoid regressions
                   // on stable channel
    }
}

mod m2 {
    pub mod std {
        pub macro panic() {}
    }
}

mod m3 {
    use m2::*; // glob-import user-defined `std`
    fn check() {
        std::panic!(); //~ ERROR `std` is ambiguous
    }
}

fn main() {}


text:
package com.antonjohansson.elasticsearchshell.index;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.MethodTarget;
import org.springframework.stereotype.Component;

import com.antonjohansson.elasticsearchshell.client.ClientFactory;

/**
 * Converts {@link String strings} to {@link IndexKey index keys}.
 */
@Component
class IndexKeyConverter implements Converter<IndexKey>
{
    private final ClientFactory clientFactory;

    @Autowired
    IndexKeyConverter(ClientFactory clientFactory)
    {
        this.clientFactory = clientFactory;
    }

    @Override
    public boolean supports(Class<?> type, String optionContext)
    {
        return IndexKey.class.isAssignableFrom(type);
    }

    @Override
    public IndexKey convertFromText(String value, Class<?> targetType, String optionContext)
    {
        return new IndexKey(value);
    }

    @Override
    public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData, String optionContext, MethodTarget target)
    {
        clientFactory.getClient()
                .getMappings()
                .keySet()
                .stream()
                .filter(name -> name.startsWith(existingData))
                .sorted()
                .forEach(name ->
                {
                    completions.add(new Completion(name));
                });

        return true;
    }
}


text:
FROM python:alpine

ADD app.py /

CMD ["python", "/app.py"]


text:
package com.invivoo.satisfaction.tests;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SatisfactionTestApplication {

}


text:
// +build windows

package containerd

import (
	"context"
	"strconv"

	"github.com/containerd/containerd/containers"
	"github.com/containerd/containerd/oci"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

const newLine = "\r\n"

func withExitStatus(es int) oci.SpecOpts {
	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
		s.Process.Args = []string{"powershell", "-noprofile", "exit", strconv.Itoa(es)}
		return nil
	}
}

func withProcessArgs(args ...string) oci.SpecOpts {
	return oci.WithProcessArgs(append([]string{"powershell", "-noprofile"}, args...)...)
}

func withCat() oci.SpecOpts {
	return oci.WithProcessArgs("cmd", "/c", "more")
}

func withTrue() oci.SpecOpts {
	return oci.WithProcessArgs("cmd", "/c")
}

func withExecExitStatus(s *specs.Process, es int) {
	s.Args = []string{"powershell", "-noprofile", "exit", strconv.Itoa(es)}
}

func withExecArgs(s *specs.Process, args ...string) {
	s.Args = append([]string{"powershell", "-noprofile"}, args...)
}


text:
package com.github.phajduk.rxvalidator.validators;

import android.text.TextUtils;
import android.widget.EditText;
import com.github.phajduk.rxvalidator.RxValidationResult;
import com.github.phajduk.rxvalidator.Validator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import rx.Observable;

import static java.util.Calendar.DATE;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;

public class AgeValidator implements Validator<EditText> {

  private static final int DEFAULT_AGE = 18;
  private static final String DEFAULT_MESSAGE = "At least " + DEFAULT_AGE + "y old";
  private final String message;
  private final DateFormat sdf;
  private final int age;

  public AgeValidator() {
    message = DEFAULT_MESSAGE;
    age = DEFAULT_AGE;
    sdf = SimpleDateFormat.getDateInstance();
  }

  public AgeValidator(String message, SimpleDateFormat sdf, int age) {
    this.message = message;
    this.sdf = sdf;
    this.age = age;
  }

  @Override public Observable<RxValidationResult<EditText>> validate(String text, EditText item) {
    if(TextUtils.isEmpty(text)){
      return Observable.just(RxValidationResult.createImproper(item, message));
    }
    try {
      Date date = sdf.parse(text);
      if (ageIsValid(date)) {
        return Observable.just(RxValidationResult.createSuccess(item));
      }
      return Observable.just(RxValidationResult.createImproper(item, message));
    } catch (ParseException e) {
      return Observable.error(e);
    }
  }

  private int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(
        DATE))) {
      diff--;
    }
    return diff;
  }

  private Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal;
  }

  private boolean ageIsValid(Date dateOfBirth) {
    return getDiffYears(dateOfBirth, new Date()) >= age;
  }
}


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('task', 'Unit | Serializer | Task', {
  needs: [
    'serializer:task',
    'model:identifier',
    'model:reference',
    'model:codeable-concept',
    'model:period',
    'model:task-requester',
    'model:annotation',
    'model:task-restriction',
    'model:task-input',
    'model:task-output',
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension'
  ]
});

test('it serializes records', function(assert) {
  const record = this.subject(),
    serializeRecord = record.serialize();

  assert.ok(serializeRecord);
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bingeterest</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/simplex/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">
    <link rel="stylesheet" href="/css/bingeboard.css">

Add Binge

              Title
              <input type="text" class="form-control" id="add-binge-title" aria-describedby="basic-addon3">

              Image URL
              <input type="text" class="form-control" id="add-binge-url" aria-describedby="basic-addon3">

            <button type="button" class="btn btn-default" onclick="cancelAddBinge()" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="addBinge()" data-dismiss="modal">Add Binge</button>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Bingeterest

Recent

Your Bingeboard

Add Binge

Sign out

Sign in with Twitter

Recent binges by this user.


text:
    {{ swagger.info.title }}

    <swagger-path path="operations.$key"
                  parameters="operations[0].parameters">
    </swagger-path>

  <accordion close-others="false">
    <accordion-group ng-repeat="operation in operations"
                     is-open="operation_open">
      <accordion-heading>

            <swagger-method method="operation.method"></swagger-method>

            {{ operation.title }}

            {{ operation.summary }}

      </accordion-heading>

          <tabset>
            <tab heading="Description">

              <ng-include ng-if="isEmpty(operation.description)"
                          src="'browser/undocumented-operation.html'">
              </ng-include>
            </tab>
            <tab heading="Details">

Headers

{{parameter.name}}

URL Parameters

{{parameter.name}}

Request Schema

                <swagger-schema swagger="swagger" parameters="parameters.body"></swagger-schema>

            </tab>
          </tabset>

Request

          <swagger-example ng-if="!isEmpty(operation.examples)"
                           swagger="swagger"
                           src="operation.examples"
                           trigger-load="operation_open">
          </swagger-example>

            No request recorded.

Responses

          <accordion close-others="true">
            <accordion-group ng-repeat="(status_code, response) in operation.responses"
                             is-disabled="isEmpty(response.examples)"
                             is-open="status.open">
              <accordion-heading>
                {{ status_code }}: {{ response.description }}

              </accordion-heading>
              <swagger-example swagger="swagger"
                               src="response.examples"
                               trigger-load="status.open">
              </swagger-example>
            </accordion-group>
          </accordion>

    </accordion-group>
  </accordion>


text:
package cogx.compiler.codegenerator.opencl.hyperkernels.domaintransform

import cogx.platform.types.{VirtualFieldRegister, Opcode, FieldType}
import cogx.compiler.codegenerator.opencl.fragments._
import cogx.compiler.parser.op.NaryOpcode
import cogx.cogmath.algebra.real.Logarithm
import cogx.platform.opencl.WorkGroupParameters
import cogx.compiler.codegenerator.common.FieldPolicies._

/** Implements the domain transform on the rows of a small tensor field,
  * where "small" means either a scalar field or a vector field with length 2
  * vectors.
  *
  * See the paper
  * "Domain transform for edge-aware image and video processing," Gastal and
  * Oliveira, 2011, for a description.
  *
  * @param in An array of three fields: (1) The small tensor field to be filtered;
   *       (2) The domain transform field for the image which will be used to
   *       "warp" the domain; (3) A 0-D field which holds the box filter
   *       radius.
  * @param operation The binary opcode for this operation.
  * @param resultType The FieldType of the result of this kernel.
  * @param addressMode Addressing mode for this kernel (must be small tensor).
  *
  * @author Greg Snider
  */
private[cogx]
class TensorDomainFilterRowsHyperKernel private[hyperkernels] (
                                       in: Array[VirtualFieldRegister],
                                       operation: Opcode,
                                       resultType: FieldType,
                                       addressMode: AddressingMode)
        extends HyperKernel(operation, in, resultType, addressMode, ClampToEdge)
        with Logarithm
{
  require(addressMode == BigTensorAddressing)

  /** Max threads per workgroup, which is hardware dependent. We need a better
    * way of finding this out for a given target.
    */
  val MaxThreadsPerWorkGroup = 1024
  private val rows = in(0).fieldType.rows
  private val columns = in(0).fieldType.columns
  require(rows <= MaxThreadsPerWorkGroup, "image too big for this operator")
  require(columns <= MaxThreadsPerWorkGroup, "image too big for this operator")

  // Work group computation.
  // Our strategy is for each work group to work on a single row of the
  // of the input, with one thread for each pixel in the row.
  override lazy val workGroup =
    new WorkGroupParameters(2,
      globalLayers  = 1,
      globalRows    = rows,
      globalColumns = columns,
      localLayers  = 1,
      localRows    = 1,
      localColumns = columns
    )

  // Parameters for kernel.
  val lineLength = columns
  val doublingIterations = log2(roundUpPowerOf2(lineLength)).toInt

  // NOTE: The image to be filtered, in(0), may be any tensor field. But the
  // guiding domain transform, in(1), may either be a scalar field or tensor
  // field that exactly matches the tensor shape of in(0). If the guide is a
  // scalar field, all tensor slices are filtered using the guide, otherwise
  // the in(0) slices are filtered one-to-one with the guide, in(1), slices.
  // We determine here which case we have.
  val input = in(0)
  val guide = in(1)
  val inputIsScalar = input.fieldType.tensorShape.dimensions == 0
  val guideIsScalar = guide.fieldType.tensorShape.dimensions == 0
  if (!inputIsScalar && !guideIsScalar)
    require(input.fieldType.tensorShape == guide.fieldType.tensorShape,
      "illegal guide tensor shape for input")

  // The kernel code.
  var code = ""

  // Code to read in the guide.
  val readDomainTransform =
    """
      |   // Read in the domain transform.
      |   __local float domainTransform[%lineLength%];
      |   domainTransform[_column] = readElement(@in1);
      |
    """.stripMargin

  if (guideIsScalar)
    // Only need to read the guide in once.
    code += readDomainTransform
  if (!inputIsScalar) {
    // Must iterate over multiple tensor elements
    code +=
       """
         | // Outer loop, over all tensor elements.
         | for (tensorElement = 0; tensorElement < _tensorElements; tensorElement++) {
       """.stripMargin
    if (!guideIsScalar)
      // Must read in a different guide for each tensor element
      code += readDomainTransform
  }
  code +=
    """
      |   // Read in a row of the image (or tensor slice)
      |   __local float line_A[%lineLength%];
      |   line_A[_column] = readElement(@in0);
      |   barrier(CLK_LOCAL_MEM_FENCE);
      |
      |   // Integrate using recursive doubling to get the integral image.
      |   // We alternate between the A buffers and a second set of
      |   // B buffers that we create here. For a description of
      |   // recursive doubling, see "Fast summed-area table generation and its
      |   // applications," Hensley et al, 2005.
      |
      |   __local float line_B[%lineLength%];
      |   __local float* line_1 = line_A;
      |   __local float* line_2 = line_B;
      |
      |   int stride = 1;
      |   for (int i = 0; i < %doublingIterations%; i++) {
      |     float center = line_1[_column];
      |     float left;
      |     int leftIndex = _column - stride;
      |     if (leftIndex >= 0)
      |       left = line_1[leftIndex];
      |     else
      |       left = 0.0f;
      |     line_2[_column] = center + left;
      |     barrier(CLK_LOCAL_MEM_FENCE);
      |
      |     // Double the stride each iteration.
      |     stride = stride << 1;
      |
      |     // Swap buffers
      |     __local float* temp = line_1;
      |     line_1 = line_2;
      |     line_2 = temp;
      |   }
      |   barrier(CLK_LOCAL_MEM_FENCE);
      |
      |   // Now that we have the integral image and the domain transform,
      |   // we need to do a binary search around each pixel to find the
      |   // upper and lower indices for the box filter. To simplify, we use
      |   // the same stride for all threads at a given step, starting with a
      |   // large stride, shrinking by a factor of 2 on each step. Note that
      |   // we clamp the index at the boundaries to stay inside of local
      |   // memory. Also note that the upper and lower indices are inclusive.
      |
      |   float center = domainTransform[_column];
      |   float radius = readScalar(@in2);
      |   float lower = center - radius;
      |   float upper = center + radius;
      |   int lowerIndex = _column;
      |   int upperIndex = _column;
      |   for (int level = %doublingIterations%; level >= 0; level--) {
      |     int stride = 1 << level;
      |
      |     // Try expanding lower index down.
      |     int trialLowerIndex = max(lowerIndex - stride, 0);
      |     int inBounds = domainTransform[trialLowerIndex] >= lower;
      |     lowerIndex = mul24(inBounds, trialLowerIndex) +
      |       mul24(1 - inBounds, lowerIndex);
      |
      |     // Try expanding upper index up.
      |     int trialUpperIndex = min(upperIndex + stride, %lineLength% - 1);
      |     inBounds = domainTransform[trialUpperIndex] <= upper;
      |     upperIndex = mul24(inBounds, trialUpperIndex) +
      |       mul24(1 - inBounds, upperIndex);
      |   }
      |
      |   // Bump lower index down so it's exclusive to make summed area
      |   // calculation easier
      |   lowerIndex -= 1;
      |
      |   // Compute the box filter from result. If the lower index is less than
      |   // 0, we must correct for that.
      |
      |   float span = upperIndex - lowerIndex;
      |   int lowerInBounds = lowerIndex >= 0;
      |   float pixel = (line_1[upperIndex] -
      |     lowerInBounds * line_1[lowerIndex * lowerInBounds]) / span;
      |   barrier(CLK_LOCAL_MEM_FENCE);
      |
      |   // Write out result
      |   @outElement0 = pixel;
      |
    """.stripMargin

  if (!inputIsScalar)
    // Must terminate loop over all tensor elements.
    code += "}\n"

  val codeString = code.
          replaceAll("%lineLength%", lineLength.toString).
          replaceAll("%doublingIterations%", doublingIterations.toString)
  addCode(codeString)
  //debugCompile
}

/** Factory for creating hyper kernels that implement domain transform filtering
  * on rows of a tensor field.
  *
  * @author Greg Snider
  */
private[cogx]
object TensorDomainFilterRowsHyperKernel {

  /** Create a hyperkernel that implements the domain transform for the rows
    * of an input color field.
    *
    * @param in The input virtual field register driving this kernel.
    * @param operation The binary opcode for this operation.
    * @param resultType The FieldType of the result of this kernel.
    * @return Synthesized hyperkernel for the operation.
    */
  def apply(in: Array[VirtualFieldRegister],
            operation: NaryOpcode,
            resultType: FieldType): HyperKernel =
  {
    require(in.length == 3)
    require(in(0).fieldType.dimensions == 2)
    val expectedResultType = in(0).fieldType
    require(resultType == expectedResultType)
    val addressing = BigTensorAddressing
    require(!isColorField(in(0).fieldType))
    new TensorDomainFilterRowsHyperKernel(in, operation, resultType, addressing)
  }
}


text:
"""Command used to prevent pods from failing over until
databases are in sync. This just delegates to other
mgmt commands and returns a non-zero exit code if
any of them error.
"""

from django.core.management.base import BaseCommand
from django.core.management import call_command

CHECKS = [
    ['checkmigrations'],
    ['check_metrics'],
]

class Command(BaseCommand):

    def handle(self, *args, **options):
        for check in CHECKS:
            call_command(*check)


text:
from . import AWSObject
from . import AWSProperty

class Admins(AWSProperty):
    props = {
    }

class DataLakeSettings(AWSObject):
    resource_type = "AWS::LakeFormation::DataLakeSettings"

    props = {
        'Admins': (Admins, False),
    }

class DataLakePrincipal(AWSProperty):
    props = {
        'DataLakePrincipalIdentifier': (basestring, False),
    }

class DatabaseResource(AWSProperty):
    props = {
        'Name': (basestring, False),
    }

class TableResource(AWSProperty):
    props = {
        'DatabaseName': (basestring, False),
        'Name': (basestring, False),
    }

class DataLocationResource(AWSProperty):
    props = {
        'S3Resource': (basestring, False),
    }

class ColumnWildcard(AWSProperty):
    props = {
        'ExcludedColumnNames': ([basestring], False),
    }

class TableWithColumnsResource(AWSProperty):
    props = {
        'ColumnNames': ([basestring], False),
        'ColumnWildcard': (ColumnWildcard, False),
        'DatabaseName': (basestring, False),
        'Name': (basestring, False),
    }

class Resource(AWSProperty):
    props = {
        'DatabaseResource': (DatabaseResource, False),
        'DataLocationResource': (DataLocationResource, False),
        'TableResource': (TableResource, False),
        'TableWithColumnsResource': (TableWithColumnsResource, False),
    }

class Permissions(AWSObject):
    resource_type = "AWS::LakeFormation::Permissions"

    props = {
        'DataLakePrincipal': (DataLakePrincipal, True),
        'Permissions': ([basestring], False),
        'PermissionsWithGrantOption': ([basestring], False),
        'Resource': (Resource, True),
    }


text:
<?php

namespace TypiCMS\Modules\Pages\Shells\Models;

use TypiCMS\Modules\Pages\Models\PageTranslation as BaseClass;

class PageTranslation extends BaseClass
{

}


text:
package com.creditease.dbus.stream.common.appender.utils;

import java.io.Serializable;

/**
 * 键值对存储数据结构
 * Created by zhangyf on 16/5/20.
 */
public class Pair<K, V> implements Serializable {
    private K key;
    private V value;

    public Pair() {
    }

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }
}


text:
<?php
namespace Scalr\Upgrade\Updates;

use Scalr\Upgrade\SequenceInterface;
use Scalr\Upgrade\AbstractUpdate;

class Update20140222231138 extends AbstractUpdate implements SequenceInterface
{
    protected $uuid = 'fe638b60-64cf-4967-84bd-1740dd2088c0';

    protected $depends = array();

    protected $description = 'Updating aws.instance_name_format content';

    protected $ignoreChanges = true;

    /**
     * {@inheritdoc}
     * @see Scalr\Upgrade.SequenceInterface::getNumberStages()
     */
    public function getNumberStages()
    {
        return 1;
    }

    /**
     * Checks whether the update of the stage ONE is applied.
     *
     * Verifies whether current update has already been applied to this install.
     * This ensures avoiding the duplications. Implementation of this method should give
     * the definite answer to question "has been this update applied or not?".
     *
     * @param   int  $stage  optional The stage number
     * @return  bool Returns true if the update has already been applied.
     */
    protected function isApplied1($stage)
    {
        return false;
    }

    /**
     * Validates an environment before it will try to apply the update of the stage ONE.
     *
     * Validates current environment or inspects circumstances that is expected to be in the certain state
     * before the update is applied. This method may not be overridden from AbstractUpdate class
     * which means current update is always valid.
     *
     * @param   int  $stage  optional The stage number
     * @return  bool Returns true if the environment meets the requirements.
     */
    protected function validateBefore1($stage)
    {
        return true;
    }

    /**
     * Performs upgrade literally for the stage ONE.
     *
     * Implementation of this method performs update steps needs to be taken
     * to accomplish upgrade successfully.
     *
     * If there are any error during an execution of this scenario it must
     * throw an exception.
     *
     * @param   int  $stage  optional The stage number
     * @throws  \Exception
     */
    protected function run1($stage)
    {
        $records = $this->db->Execute("
            SELECT * FROM farm_role_settings
            WHERE name = 'aws.instance_name_format'
        ");
        while ($record = $records->FetchRow()) {
            $record['value'] = str_replace(array(
                '%farm_name%',
                '%instance_index%',
                '%role_name%',
                '%avail_zone%'
            ), array(
                '{SCALR_FARM_NAME}',
                '{SCALR_INSTANCE_INDEX}',
                '{SCALR_ROLE_NAME}',
                '{SCALR_CLOUD_LOCATION_ZONE}'
            ), $record['value']);

            $this->db->Execute("UPDATE farm_role_settings SET value=? WHERE farm_roleid = ? AND name = ?", array(
                $record['value'], $record['farm_roleid'], $record['name']
            ));
        }
    }
}