text:
// <copyright file="UserDefinedFunction.cs" company="Peter Ibbotson">
// (C) Copyright 2017 Peter Ibbotson
// </copyright>

namespace ClassicBasic.Interpreter
{
    /// <summary>
    /// Function definition.
    /// </summary>
    public class UserDefinedFunction
    {
        /// <summary>
        /// Gets or sets line contents the function executes.
        /// </summary>
        public ProgramLine Line { get; set; }

        /// <summary>
        /// Gets or sets line token the function starts on.
        /// </summary>
        public int LineToken { get; set; }

        /// <summary>
        /// Gets or sets the function name.
        /// </summary>
        public string FunctionName { get; set; }

        /// <summary>
        /// Gets or sets the variable name.
        /// </summary>
        public string VariableName { get; set; }

        /// <summary>
        /// Executes a user defined function.
        /// </summary>
        /// <param name="parameter">new parameter value.</param>
        /// <param name="runEnvironment">Run evironment.</param>
        /// <param name="expressionEvaluator">Expression evaluator.</param>
        /// <param name="variableRepository">Variable repository.</param>
        /// <returns>Value of function.</returns>
        public Accumulator Execute(
            Accumulator parameter,
            IRunEnvironment runEnvironment,
            IExpressionEvaluator expressionEvaluator,
            IVariableRepository variableRepository)
        {
            // Save the variable and program line.
            var savedVariable = variableRepository.GetOrCreateVariable(VariableName, new short[] { }).GetValue();
            var savedProgramLine = runEnvironment.CurrentLine;

            // Change the variable to be our parameter.
            variableRepository.GetOrCreateVariable(VariableName, new short[] { }).SetValue(parameter);
            runEnvironment.CurrentLine = Line;
            runEnvironment.CurrentLine.CurrentToken = LineToken;

            // Evaluate the expression.
            var returnValue = expressionEvaluator.GetExpression();

            // Restore the variable and program line.
            variableRepository.GetOrCreateVariable(VariableName, new short[] { }).SetValue(savedVariable);
            runEnvironment.CurrentLine = savedProgramLine;

            // return the value.
            return returnValue;
        }
    }
}


text:
package de.borellda.domain;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Timestamp;

/**
 * Created by borellda on 2/24/2016.
 */
@Entity
@Table(name = "tracking_raw", schema = "public", catalog = "ecodp")
public class TrackingRawEntity {
    /* The Logger */
    private static final Logger log = LoggerFactory.getLogger(TrackingRawEntity.class);
    private String userKey;
    private String url;
    private String trackingType;
    private Timestamp accessTimestamp;

    @Basic
    @Column(name = "user_key", nullable = false, length = 100)
    public String getUserKey() {
        return userKey;
    }

    public void setUserKey(String userKey) {
        this.userKey = userKey;
    }

    @Basic
    @Column(name = "url", nullable = false, length = -1)
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Basic
    @Column(name = "tracking_type", nullable = false, length = 10)
    public String getTrackingType() {
        return trackingType;
    }

    public void setTrackingType(String trackingType) {
        this.trackingType = trackingType;
    }

    @Basic
    @Column(name = "access_timestamp", nullable = true)
    public Timestamp getAccessTimestamp() {
        return accessTimestamp;
    }

    public void setAccessTimestamp(Timestamp accessTimestamp) {
        this.accessTimestamp = accessTimestamp;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TrackingRawEntity that = (TrackingRawEntity) o;

        if (userKey != null ? !userKey.equals(that.userKey) : that.userKey != null) return false;
        if (url != null ? !url.equals(that.url) : that.url != null) return false;
        if (trackingType != null ? !trackingType.equals(that.trackingType) : that.trackingType != null) return false;
        if (accessTimestamp != null ? !accessTimestamp.equals(that.accessTimestamp) : that.accessTimestamp != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = userKey != null ? userKey.hashCode() : 0;
        result = 31 * result + (url != null ? url.hashCode() : 0);
        result = 31 * result + (trackingType != null ? trackingType.hashCode() : 0);
        result = 31 * result + (accessTimestamp != null ? accessTimestamp.hashCode() : 0);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo;

import org.apache.hadoop.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueInfo;
import org.apache.hadoop.yarn.api.records.QueueState;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.SchedulingRequest;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ContainerUpdates;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppUtils;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerExpiredSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeResourceUpdateSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent;

import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ReleaseContainerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.PendingAsk;
import org.apache.hadoop.yarn.server.scheduler.SchedulerRequestKey;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.server.utils.Lock;
import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;

@LimitedPrivate("yarn")
@Evolving
@SuppressWarnings("unchecked")
public class FifoScheduler extends
    AbstractYarnScheduler<FifoAppAttempt, FiCaSchedulerNode> implements
    Configurable {

  private static final Logger LOG =
      LoggerFactory.getLogger(FifoScheduler.class);

  private static final RecordFactory recordFactory =
    RecordFactoryProvider.getRecordFactory(null);

  Configuration conf;

  private boolean usePortForNodeName;

  private ActiveUsersManager activeUsersManager;

  private static final String DEFAULT_QUEUE_NAME = "default";
  private QueueMetrics metrics;

  private final ResourceCalculator resourceCalculator = new DefaultResourceCalculator();

  private final Queue DEFAULT_QUEUE = new Queue() {
    @Override
    public String getQueueName() {
      return DEFAULT_QUEUE_NAME;
    }

    @Override
    public QueueMetrics getMetrics() {
      return metrics;
    }

    @Override
    public QueueInfo getQueueInfo(
        boolean includeChildQueues, boolean recursive) {
      QueueInfo queueInfo = recordFactory.newRecordInstance(QueueInfo.class);
      queueInfo.setQueueName(DEFAULT_QUEUE.getQueueName());
      queueInfo.setCapacity(1.0f);
      Resource clusterResource = getClusterResource();
      if (clusterResource.getMemorySize() == 0) {
        queueInfo.setCurrentCapacity(0.0f);
      } else {
        queueInfo.setCurrentCapacity((float) usedResource.getMemorySize()
            / clusterResource.getMemorySize());
      }
      queueInfo.setMaximumCapacity(1.0f);
      queueInfo.setChildQueues(new ArrayList<QueueInfo>());
      queueInfo.setQueueState(QueueState.RUNNING);
      return queueInfo;
    }

    public Map<QueueACL, AccessControlList> getQueueAcls() {
      Map<QueueACL, AccessControlList> acls =
        new HashMap<QueueACL, AccessControlList>();
      for (QueueACL acl : QueueACL.values()) {
        acls.put(acl, new AccessControlList("*"));
      }
      return acls;
    }

    @Override
    public List<QueueUserACLInfo> getQueueUserAclInfo(
        UserGroupInformation unused) {
      QueueUserACLInfo queueUserAclInfo =
        recordFactory.newRecordInstance(QueueUserACLInfo.class);
      queueUserAclInfo.setQueueName(DEFAULT_QUEUE_NAME);
      queueUserAclInfo.setUserAcls(Arrays.asList(QueueACL.values()));
      return Collections.singletonList(queueUserAclInfo);
    }

    @Override
    public boolean hasAccess(QueueACL acl, UserGroupInformation user) {
      return getQueueAcls().get(acl).isUserAllowed(user);
    }

    @Override
    public ActiveUsersManager getAbstractUsersManager() {
      return activeUsersManager;
    }

    @Override
    public void recoverContainer(Resource clusterResource,
        SchedulerApplicationAttempt schedulerAttempt, RMContainer rmContainer) {
      if (rmContainer.getState().equals(RMContainerState.COMPLETED)) {
        return;
      }
      increaseUsedResources(rmContainer);
      updateAppHeadRoom(schedulerAttempt);
      updateAvailableResourcesMetrics();
    }

    @Override
    public Set<String> getAccessibleNodeLabels() {
      // TODO add implementation for FIFO scheduler
      return null;
    }

    @Override
    public String getDefaultNodeLabelExpression() {
      // TODO add implementation for FIFO scheduler
      return null;
    }

    @Override
    public void incPendingResource(String nodeLabel, Resource resourceToInc) {
    }

    @Override
    public void decPendingResource(String nodeLabel, Resource resourceToDec) {
    }

    @Override
    public Priority getDefaultApplicationPriority() {
      // TODO add implementation for FIFO scheduler
      return null;
    }

    @Override
    public void incReservedResource(String partition, Resource reservedRes) {
      // TODO add implementation for FIFO scheduler

    }

    @Override
    public void decReservedResource(String partition, Resource reservedRes) {
      // TODO add implementation for FIFO scheduler

    }
  };

  public FifoScheduler() {
    super(FifoScheduler.class.getName());
  }

  private synchronized void initScheduler(Configuration conf) {
    validateConf(conf);
    //Use ConcurrentSkipListMap because applications need to be ordered
    this.applications =
        new ConcurrentSkipListMap<>();
    this.minimumAllocation = super.getMinimumAllocation();
    initMaximumResourceCapability(super.getMaximumAllocation());
    this.usePortForNodeName = conf.getBoolean(
        YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME,
        YarnConfiguration.DEFAULT_RM_SCHEDULER_USE_PORT_FOR_NODE_NAME);
    this.metrics = QueueMetrics.forQueue(DEFAULT_QUEUE_NAME, null, false,
        conf);
    this.activeUsersManager = new ActiveUsersManager(metrics);
  }

  @Override
  public void serviceInit(Configuration conf) throws Exception {
    initScheduler(conf);
    super.serviceInit(conf);

    // Initialize SchedulingMonitorManager
    schedulingMonitorManager.initialize(rmContext, conf);
  }

  @Override
  public void serviceStart() throws Exception {
    super.serviceStart();
  }

  @Override
  public void serviceStop() throws Exception {
    super.serviceStop();
  }

  @Override
  public synchronized void setConf(Configuration conf) {
    this.conf = conf;
  }

  private void validateConf(Configuration conf) {
    // validate scheduler memory allocation setting
    int minMem = conf.getInt(
      YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
      YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB);
    int maxMem = conf.getInt(
      YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
      YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB);

    if (minMem <= 0 || minMem > maxMem) {
      throw new YarnRuntimeException("Invalid resource scheduler memory"
        + " allocation configuration"
        + ", " + YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB
        + "=" + minMem
        + ", " + YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB
        + "=" + maxMem + ", min and max should be greater than 0"
        + ", max should be no smaller than min.");
    }
  }

  @Override
  public synchronized Configuration getConf() {
    return conf;
  }

  @Override
  public int getNumClusterNodes() {
    return nodeTracker.nodeCount();
  }

  @Override
  public synchronized void setRMContext(RMContext rmContext) {
    this.rmContext = rmContext;
  }

  @Override
  public synchronized void
      reinitialize(Configuration conf, RMContext rmContext) throws IOException
  {
    setConf(conf);
    super.reinitialize(conf, rmContext);
  }

  @Override
  public Allocation allocate(ApplicationAttemptId applicationAttemptId,
      List<ResourceRequest> ask, List<SchedulingRequest> schedulingRequests,
      List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals,
      ContainerUpdates updateRequests) {
    FifoAppAttempt application = getApplicationAttempt(applicationAttemptId);
    if (application == null) {
      LOG.error("Calling allocate on removed or non existent application " +
          applicationAttemptId.getApplicationId());
      return EMPTY_ALLOCATION;
    }

    // The allocate may be the leftover from previous attempt, and it will
    // impact current attempt, such as confuse the request and allocation for
    // current attempt's AM container.
    // Note outside precondition check for the attempt id may be
    // outdated here, so double check it here is necessary.
    if (!application.getApplicationAttemptId().equals(applicationAttemptId)) {
      LOG.error("Calling allocate on previous or removed " +
          "or non existent application attempt " + applicationAttemptId);
      return EMPTY_ALLOCATION;
    }

    // Sanity check
    normalizeResourceRequests(ask);

    // Release containers
    releaseContainers(release, application);

    synchronized (application) {

      // make sure we aren't stopping/removing the application
      // when the allocate comes in
      if (application.isStopped()) {
        LOG.info("Calling allocate on a stopped " +
            "application " + applicationAttemptId);
        return EMPTY_ALLOCATION;
      }

      if (!ask.isEmpty()) {
        LOG.debug("allocate: pre-update" +
            " applicationId=" + applicationAttemptId +
            " application=" + application);
        application.showRequests();

        // Update application requests
        application.updateResourceRequests(ask);

        LOG.debug("allocate: post-update" +
            " applicationId=" + applicationAttemptId +
            " application=" + application);
        application.showRequests();

        LOG.debug("allocate:" +
            " applicationId=" + applicationAttemptId +
            " #ask=" + ask.size());
      }

      application.updateBlacklist(blacklistAdditions, blacklistRemovals);

      Resource headroom = application.getHeadroom();
      application.setApplicationHeadroomForMetrics(headroom);
      return new Allocation(application.pullNewlyAllocatedContainers(),
          headroom, null, null, null, application.pullUpdatedNMTokens());
    }
  }

  @VisibleForTesting
  public synchronized void addApplication(ApplicationId applicationId,
      String queue, String user, boolean isAppRecovering,
      boolean unmanagedAM) {
    SchedulerApplication<FifoAppAttempt> application =
        new SchedulerApplication<>(DEFAULT_QUEUE, user, unmanagedAM);
    applications.put(applicationId, application);

    metrics.submitApp(user, unmanagedAM);
    LOG.info("Accepted application " + applicationId + " from user: " + user
        + ", currently num of applications: " + applications.size());
    if (isAppRecovering) {
      LOG.debug("{} is recovering. Skip notifying APP_ACCEPTED",
          applicationId);
    } else {
      rmContext.getDispatcher().getEventHandler()
        .handle(new RMAppEvent(applicationId, RMAppEventType.APP_ACCEPTED));
    }
  }

  @VisibleForTesting
  public synchronized void
      addApplicationAttempt(ApplicationAttemptId appAttemptId,
          boolean transferStateFromPreviousAttempt,
          boolean isAttemptRecovering) {
    SchedulerApplication<FifoAppAttempt> application =
        applications.get(appAttemptId.getApplicationId());
    String user = application.getUser();
    // TODO: Fix store
    FifoAppAttempt schedulerApp =
        new FifoAppAttempt(appAttemptId, user, DEFAULT_QUEUE,
          activeUsersManager, this.rmContext);

    if (transferStateFromPreviousAttempt) {
      schedulerApp.transferStateFromPreviousAttempt(application
        .getCurrentAppAttempt());
    }
    application.setCurrentAppAttempt(schedulerApp);

    metrics.submitAppAttempt(user, application.isUnmanagedAM());

    LOG.info("Added Application Attempt " + appAttemptId
        + " to scheduler from user " + application.getUser());
    if (isAttemptRecovering) {
      LOG.debug("{} is recovering. Skipping notifying ATTEMPT_ADDED",
          appAttemptId);
    } else {
      rmContext.getDispatcher().getEventHandler().handle(
        new RMAppAttemptEvent(appAttemptId,
            RMAppAttemptEventType.ATTEMPT_ADDED));
    }
  }

  private synchronized void doneApplication(ApplicationId applicationId,
      RMAppState finalState) {
    SchedulerApplication<FifoAppAttempt> application =
        applications.get(applicationId);
    if (application == null){
      LOG.warn("Couldn't find application " + applicationId);
      return;
    }

    // Inform the activeUsersManager
    activeUsersManager.deactivateApplication(application.getUser(),
      applicationId);
    application.stop(finalState);
    applications.remove(applicationId);
  }

  private synchronized void doneApplicationAttempt(
      ApplicationAttemptId applicationAttemptId,
      RMAppAttemptState rmAppAttemptFinalState, boolean keepContainers)
      throws IOException {
    FifoAppAttempt attempt = getApplicationAttempt(applicationAttemptId);
    SchedulerApplication<FifoAppAttempt> application =
        applications.get(applicationAttemptId.getApplicationId());
    if (application == null || attempt == null) {
      throw new IOException("Unknown application " + applicationAttemptId +
      " has completed!");
    }

    // Kill all 'live' containers
    for (RMContainer container : attempt.getLiveContainers()) {
      if (keepContainers
          && container.getState().equals(RMContainerState.RUNNING)) {
        // do not kill the running container in the case of work-preserving AM
        // restart.
        LOG.info("Skip killing " + container.getContainerId());
        continue;
      }
      super.completedContainer(container,
        SchedulerUtils.createAbnormalContainerStatus(
          container.getContainerId(), SchedulerUtils.COMPLETED_APPLICATION),
        RMContainerEventType.KILL);
    }

    // Clean up pending requests, metrics etc.
    attempt.stop(rmAppAttemptFinalState);
  }

  /**
   * Heart of the scheduler...
   *
   * @param node node on which resources are available to be allocated
   */
  private void assignContainers(FiCaSchedulerNode node) {
    LOG.debug("assignContainers:" +
        " node=" + node.getRMNode().getNodeAddress() +
        " #applications=" + applications.size());

    // Try to assign containers to applications in fifo order
    for (Map.Entry<ApplicationId, SchedulerApplication<FifoAppAttempt>> e : applications
        .entrySet()) {
      FifoAppAttempt application = e.getValue().getCurrentAppAttempt();
      if (application == null) {
        continue;
      }

      LOG.debug("pre-assignContainers");
      application.showRequests();
      synchronized (application) {
        // Check if this resource is on the blacklist
        if (SchedulerAppUtils.isPlaceBlacklisted(application, node, LOG)) {
          continue;
        }

        for (SchedulerRequestKey schedulerKey :
            application.getSchedulerKeys()) {
          int maxContainers =
              getMaxAllocatableContainers(application, schedulerKey, node,
                  NodeType.OFF_SWITCH);
          // Ensure the application needs containers of this priority
          if (maxContainers > 0) {
            int assignedContainers =
                assignContainersOnNode(node, application, schedulerKey);
            // Do not assign out of order w.r.t priorities
            if (assignedContainers == 0) {
              break;
            }
          }
        }
      }

      LOG.debug("post-assignContainers");
      application.showRequests();

      // Done
      if (Resources.lessThan(resourceCalculator, getClusterResource(),
              node.getUnallocatedResource(), minimumAllocation)) {
        break;
      }
    }

    // Update the applications' headroom to correctly take into
    // account the containers assigned in this update.
    for (SchedulerApplication<FifoAppAttempt> application : applications.values()) {
      FifoAppAttempt attempt =
          (FifoAppAttempt) application.getCurrentAppAttempt();
      if (attempt == null) {
        continue;
      }
      updateAppHeadRoom(attempt);
    }
  }

  private int getMaxAllocatableContainers(FifoAppAttempt application,
      SchedulerRequestKey schedulerKey, FiCaSchedulerNode node, NodeType type) {
    PendingAsk offswitchAsk = application.getPendingAsk(schedulerKey,
        ResourceRequest.ANY);
    int maxContainers = offswitchAsk.getCount();

    if (type == NodeType.OFF_SWITCH) {
      return maxContainers;
    }

    if (type == NodeType.RACK_LOCAL) {
      PendingAsk rackLocalAsk = application.getPendingAsk(schedulerKey,
          node.getRackName());
      if (rackLocalAsk.getCount() <= 0) {
        return maxContainers;
      }

      maxContainers = Math.min(maxContainers,
          rackLocalAsk.getCount());
    }

    if (type == NodeType.NODE_LOCAL) {
      PendingAsk nodeLocalAsk = application.getPendingAsk(schedulerKey,
          node.getRMNode().getHostName());

      if (nodeLocalAsk.getCount() > 0) {
        maxContainers = Math.min(maxContainers,
            nodeLocalAsk.getCount());
      }
    }

    return maxContainers;
  }

  private int assignContainersOnNode(FiCaSchedulerNode node,
      FifoAppAttempt application, SchedulerRequestKey schedulerKey
  ) {
    // Data-local
    int nodeLocalContainers =
        assignNodeLocalContainers(node, application, schedulerKey);

    // Rack-local
    int rackLocalContainers =
        assignRackLocalContainers(node, application, schedulerKey);

    // Off-switch
    int offSwitchContainers =
        assignOffSwitchContainers(node, application, schedulerKey);

    LOG.debug("assignContainersOnNode:" +
        " node=" + node.getRMNode().getNodeAddress() +
        " application=" + application.getApplicationId().getId() +
        " priority=" + schedulerKey.getPriority() +
        " #assigned=" +
        (nodeLocalContainers + rackLocalContainers + offSwitchContainers));

    return (nodeLocalContainers + rackLocalContainers + offSwitchContainers);
  }

  private int assignNodeLocalContainers(FiCaSchedulerNode node,
      FifoAppAttempt application, SchedulerRequestKey schedulerKey) {
    int assignedContainers = 0;
    PendingAsk nodeLocalAsk = application.getPendingAsk(schedulerKey,
        node.getNodeName());
    if (nodeLocalAsk.getCount() > 0) {
      // Don't allocate on this node if we don't need containers on this rack
      if (application.getOutstandingAsksCount(schedulerKey,
          node.getRackName()) <= 0) {
        return 0;
      }

      int assignableContainers = Math.min(
          getMaxAllocatableContainers(application, schedulerKey, node,
              NodeType.NODE_LOCAL), nodeLocalAsk.getCount());
      assignedContainers =
        assignContainer(node, application, schedulerKey, assignableContainers,
            nodeLocalAsk.getPerAllocationResource(), NodeType.NODE_LOCAL);
    }
    return assignedContainers;
  }

  private int assignRackLocalContainers(FiCaSchedulerNode node,
      FifoAppAttempt application, SchedulerRequestKey schedulerKey) {
    int assignedContainers = 0;
    PendingAsk rackAsk = application.getPendingAsk(schedulerKey,
        node.getRMNode().getRackName());
    if (rackAsk.getCount() > 0) {
      // Don't allocate on this rack if the application doens't need containers
      if (application.getOutstandingAsksCount(schedulerKey,
          ResourceRequest.ANY) <= 0) {
        return 0;
      }

      int assignableContainers =
          Math.min(getMaxAllocatableContainers(application, schedulerKey, node,
              NodeType.RACK_LOCAL), rackAsk.getCount());
      assignedContainers =
        assignContainer(node, application, schedulerKey, assignableContainers,
            rackAsk.getPerAllocationResource(), NodeType.RACK_LOCAL);
    }
    return assignedContainers;
  }

  private int assignOffSwitchContainers(FiCaSchedulerNode node,
      FifoAppAttempt application, SchedulerRequestKey schedulerKey) {
    int assignedContainers = 0;
    PendingAsk offswitchAsk = application.getPendingAsk(schedulerKey,
        ResourceRequest.ANY);
    if (offswitchAsk.getCount() > 0) {
      assignedContainers =
        assignContainer(node, application, schedulerKey,
            offswitchAsk.getCount(),
            offswitchAsk.getPerAllocationResource(), NodeType.OFF_SWITCH);
    }
    return assignedContainers;
  }

  private int assignContainer(FiCaSchedulerNode node, FifoAppAttempt application,
      SchedulerRequestKey schedulerKey, int assignableContainers,
      Resource capability, NodeType type) {
    LOG.debug("assignContainers:" +
        " node=" + node.getRMNode().getNodeAddress() +
        " application=" + application.getApplicationId().getId() +
        " priority=" + schedulerKey.getPriority().getPriority() +
        " assignableContainers=" + assignableContainers +
        " capability=" + capability + " type=" + type);

    // TODO: A buggy application with this zero would crash the scheduler.
    int availableContainers =
        (int) (node.getUnallocatedResource().getMemorySize() /
                capability.getMemorySize());
    int assignedContainers =
      Math.min(assignableContainers, availableContainers);

    if (assignedContainers > 0) {
      for (int i=0; i < assignedContainers; ++i) {

        NodeId nodeId = node.getRMNode().getNodeID();
        ContainerId containerId = BuilderUtils.newContainerId(application
            .getApplicationAttemptId(), application.getNewContainerId());

        // Create the container
        Container container = BuilderUtils.newContainer(containerId, nodeId,
            node.getRMNode().getHttpAddress(), capability,
            schedulerKey.getPriority(), null,
            schedulerKey.getAllocationRequestId());

        // Allocate!

        // Inform the application
        RMContainer rmContainer = application.allocate(type, node, schedulerKey,
            container);

        // Inform the node
        node.allocateContainer(rmContainer);

        // Update usage for this container
        increaseUsedResources(rmContainer);
      }

    }

    return assignedContainers;
  }

  private void increaseUsedResources(RMContainer rmContainer) {
    Resources.addTo(usedResource, rmContainer.getAllocatedResource());
  }

  private void updateAppHeadRoom(SchedulerApplicationAttempt schedulerAttempt) {
    schedulerAttempt.setHeadroom(Resources.subtract(getClusterResource(),
      usedResource));
  }

  private void updateAvailableResourcesMetrics() {
    metrics.setAvailableResourcesToQueue(
        Resources.subtract(getClusterResource(), usedResource));
  }

  @Override
  public void handle(SchedulerEvent event) {
    switch(event.getType()) {
    case NODE_ADDED:
    {
      NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent)event;
      addNode(nodeAddedEvent.getAddedRMNode());
      recoverContainersOnNode(nodeAddedEvent.getContainerReports(),
        nodeAddedEvent.getAddedRMNode());

    }
    break;
    case NODE_REMOVED:
    {
      NodeRemovedSchedulerEvent nodeRemovedEvent = (NodeRemovedSchedulerEvent)event;
      removeNode(nodeRemovedEvent.getRemovedRMNode());
    }
    break;
    case NODE_RESOURCE_UPDATE:
    {
      NodeResourceUpdateSchedulerEvent nodeResourceUpdatedEvent =
          (NodeResourceUpdateSchedulerEvent)event;
      updateNodeResource(nodeResourceUpdatedEvent.getRMNode(),
        nodeResourceUpdatedEvent.getResourceOption());
    }
    break;
    case NODE_UPDATE:
    {
      NodeUpdateSchedulerEvent nodeUpdatedEvent =
      (NodeUpdateSchedulerEvent)event;
      nodeUpdate(nodeUpdatedEvent.getRMNode());
    }
    break;
    case APP_ADDED:
    {
      AppAddedSchedulerEvent appAddedEvent = (AppAddedSchedulerEvent) event;
      addApplication(appAddedEvent.getApplicationId(),
          appAddedEvent.getQueue(), appAddedEvent.getUser(),
          appAddedEvent.getIsAppRecovering(), appAddedEvent.isUnmanagedAM());
    }
    break;
    case APP_REMOVED:
    {
      AppRemovedSchedulerEvent appRemovedEvent = (AppRemovedSchedulerEvent)event;
      doneApplication(appRemovedEvent.getApplicationID(),
        appRemovedEvent.getFinalState());
    }
    break;
    case APP_ATTEMPT_ADDED:
    {
      AppAttemptAddedSchedulerEvent appAttemptAddedEvent =
          (AppAttemptAddedSchedulerEvent) event;
      addApplicationAttempt(appAttemptAddedEvent.getApplicationAttemptId(),
        appAttemptAddedEvent.getTransferStateFromPreviousAttempt(),
        appAttemptAddedEvent.getIsAttemptRecovering());
    }
    break;
    case APP_ATTEMPT_REMOVED:
    {
      AppAttemptRemovedSchedulerEvent appAttemptRemovedEvent =
          (AppAttemptRemovedSchedulerEvent) event;
      try {
        doneApplicationAttempt(
          appAttemptRemovedEvent.getApplicationAttemptID(),
          appAttemptRemovedEvent.getFinalAttemptState(),
          appAttemptRemovedEvent.getKeepContainersAcrossAppAttempts());
      } catch(IOException ie) {
        LOG.error("Unable to remove application "
            + appAttemptRemovedEvent.getApplicationAttemptID(), ie);
      }
    }
    break;
    case CONTAINER_EXPIRED:
    {
      ContainerExpiredSchedulerEvent containerExpiredEvent =
          (ContainerExpiredSchedulerEvent) event;
      ContainerId containerid = containerExpiredEvent.getContainerId();
      super.completedContainer(getRMContainer(containerid),
          SchedulerUtils.createAbnormalContainerStatus(
              containerid,
              SchedulerUtils.EXPIRED_CONTAINER),
          RMContainerEventType.EXPIRE);
    }
    break;
    case RELEASE_CONTAINER: {
      if (!(event instanceof ReleaseContainerEvent)) {
        throw new RuntimeException("Unexpected event type: " + event);
      }
      RMContainer container = ((ReleaseContainerEvent) event).getContainer();
      completedContainer(container,
          SchedulerUtils.createAbnormalContainerStatus(
              container.getContainerId(),
              SchedulerUtils.RELEASED_CONTAINER),
          RMContainerEventType.RELEASED);
    }
    break;
    default:
      LOG.error("Invalid eventtype " + event.getType() + ". Ignoring!");
    }
  }

  @Lock(FifoScheduler.class)
  @Override
  protected synchronized void completedContainerInternal(
      RMContainer rmContainer, ContainerStatus containerStatus,
      RMContainerEventType event) {

    // Get the application for the finished container
    Container container = rmContainer.getContainer();
    FifoAppAttempt application =
        getCurrentAttemptForContainer(container.getId());
    ApplicationId appId =
        container.getId().getApplicationAttemptId().getApplicationId();

    // Get the node on which the container was allocated
    FiCaSchedulerNode node = (FiCaSchedulerNode) getNode(container.getNodeId());

    if (application == null) {
      LOG.info("Unknown application: " + appId +
          " released container " + container.getId() +
          " on node: " + node +
          " with event: " + event);
      return;
    }

    // Inform the application
    application.containerCompleted(rmContainer, containerStatus, event,
        RMNodeLabelsManager.NO_LABEL);

    // Inform the node
    node.releaseContainer(rmContainer.getContainerId(), false);

    // Update total usage
    Resources.subtractFrom(usedResource, container.getResource());

    LOG.info("Application attempt " + application.getApplicationAttemptId() +
        " released container " + container.getId() +
        " on node: " + node +
        " with event: " + event);

  }

  private Resource usedResource = recordFactory.newRecordInstance(Resource.class);

  private synchronized void removeNode(RMNode nodeInfo) {
    FiCaSchedulerNode node = nodeTracker.getNode(nodeInfo.getNodeID());
    if (node == null) {
      return;
    }
    // Kill running containers
    for(RMContainer container : node.getCopiedListOfRunningContainers()) {
      super.completedContainer(container,
          SchedulerUtils.createAbnormalContainerStatus(
              container.getContainerId(),
              SchedulerUtils.LOST_CONTAINER),
              RMContainerEventType.KILL);
    }
    nodeTracker.removeNode(nodeInfo.getNodeID());
  }

  @Override
  public QueueInfo getQueueInfo(String queueName,
      boolean includeChildQueues, boolean recursive) {
    return DEFAULT_QUEUE.getQueueInfo(false, false);
  }

  @Override
  public List<QueueUserACLInfo> getQueueUserAclInfo() {
    return DEFAULT_QUEUE.getQueueUserAclInfo(null);
  }

  @Override
  public ResourceCalculator getResourceCalculator() {
    return resourceCalculator;
  }

  private synchronized void addNode(RMNode nodeManager) {
    FiCaSchedulerNode schedulerNode = new FiCaSchedulerNode(nodeManager,
        usePortForNodeName);
    nodeTracker.addNode(schedulerNode);
  }

  @Override
  public void recover(RMState state) {
    // NOT IMPLEMENTED
  }

  @Override
  public RMContainer getRMContainer(ContainerId containerId) {
    FifoAppAttempt attempt = getCurrentAttemptForContainer(containerId);
    return (attempt == null) ? null : attempt.getRMContainer(containerId);
  }

  @Override
  public QueueMetrics getRootQueueMetrics() {
    return DEFAULT_QUEUE.getMetrics();
  }

  @Override
  public synchronized boolean checkAccess(UserGroupInformation callerUGI,
      QueueACL acl, String queueName) {
    return DEFAULT_QUEUE.hasAccess(acl, callerUGI);
  }

  @Override
  public synchronized List<ApplicationAttemptId>
      getAppsInQueue(String queueName) {
    if (queueName.equals(DEFAULT_QUEUE.getQueueName())) {
      List<ApplicationAttemptId> attempts =
          new ArrayList<ApplicationAttemptId>(applications.size());
      for (SchedulerApplication<FifoAppAttempt> app : applications.values()) {
        attempts.add(app.getCurrentAppAttempt().getApplicationAttemptId());
      }
      return attempts;
    } else {
      return null;
    }
  }

  public Resource getUsedResource() {
    return usedResource;
  }

  @Override
  protected synchronized void nodeUpdate(RMNode nm) {
    super.nodeUpdate(nm);

    FiCaSchedulerNode node = (FiCaSchedulerNode) getNode(nm.getNodeID());
    if (rmContext.isWorkPreservingRecoveryEnabled()
        && !rmContext.isSchedulerReadyForAllocatingContainers()) {
      return;
    }

    // A decommissioned node might be removed before we get here
    if (node != null &&
        Resources.greaterThanOrEqual(resourceCalculator, getClusterResource(),
            node.getUnallocatedResource(), minimumAllocation)) {
      LOG.debug("Node heartbeat " + nm.getNodeID() +
          " available resource = " + node.getUnallocatedResource());

      assignContainers(node);

      LOG.debug("Node after allocation " + nm.getNodeID() + " resource = "
          + node.getUnallocatedResource());
    }

    updateAvailableResourcesMetrics();
  }

  @VisibleForTesting
  @Override
  public void killContainer(RMContainer container) {
    ContainerStatus status = SchedulerUtils.createKilledContainerStatus(
        container.getContainerId(),
        "Killed by RM to simulate an AM container failure");
    LOG.info("Killing container " + container);
    completedContainer(container, status, RMContainerEventType.KILL);
  }

  @Override
  public synchronized void recoverContainersOnNode(
      List<NMContainerStatus> containerReports, RMNode nm) {
    super.recoverContainersOnNode(containerReports, nm);
  }
}


text:
typedef struct {
	uint8_t	li_vn_mode;	// peer leap indicator
	uint8_t	stratum;	// peer stratum
	uint8_t	ppoll;		// peer poll interval
	char 	precision;	// peer clock precision
	uint32_t	rootdelay;	// roundtrip delay to primary source */
	uint32_t	rootdisp;	// dispersion to primary source*/
	uint32_t	refid;		// reference id */
	uint32_t	reftime_s,reftime_f;	// last update time */
	uint32_t	org_s,org_f;		//originate time stamp */
	uint32_t	rec_s,rec_f;		// receive time stamp */
	uint32_t	xmt_s,xmt_f;		// transmit time stamp */
}ntp_pkt;

static int debugOn=0;

static void
print_help()
{
	printf("\n%s version %s\n",APP_NAME,APP_VERSION);
	printf("Usage: %s [-hvd] hostname\n",APP_NAME);
	printf("-h print this help message\n");
	printf("-v print version\n");
	printf("-r <rate> set poll rate (default 1/s)\n");
	printf("-t <time> set time to poll for (default forever)\n");
	printf("-d enable debugging\n");
}

static void
print_version()
{
	printf("\n %s version %s\n",APP_NAME,APP_VERSION);
	printf("Written by %s\n",APP_AUTHORS);
	printf("This ain't no stinkin' Perl script!\n");
}

static void
error_exit(
	char* msg)
{
	perror( msg );
	exit( EXIT_FAILURE );
}

int
get_int(char *str){
	char *endptr;

	errno =0;

	int val = strtol(str,&endptr,10);

	if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) {
		error_exit("strtol");
	}

	if (*endptr != '\0'){
		error_exit("Error! Bad parameter");
	}

	return val;

}

int main(
	int argc,
	char* argv[ ] )
{
	int c;
  int sockfd;
  int portno = 123;
	char *hostname;

	int rate=1; // packets per second to send
	int runtime=-1; // time to send packets for, negative means forever
	int totalpkts=rate*runtime; // total packets to send
	int runForever = (totalpkts < 0);
	int tusleep;
	struct timeval tvstart,tvstop,tvstartpoll,tvstoppoll;
	int tupoll;
	int pktsize;
	int nleft,nw;
	char *pbuf;
	int nsent;
	// Process the command line options
	while ((c=getopt(argc,argv,"dht:r:v")) != -1)
	{
		switch(c)
		{
			case 'd':	// enable debugging
				printf("Debugging is ON\n");
				debugOn=TRUE;
				break;
			case 'h': // print help
				print_help();
				exit(EXIT_SUCCESS);
				break;
			case 'r': // set poll rate
				rate = get_int(optarg);
				if (rate > 10000){
					error_exit("The rate is too high: 10 000 packets/s is the practical maximum");
				}
				break;
			case 't':
				runtime = get_int(optarg);
				break;
			case 'v':
				print_version();
				exit(EXIT_SUCCESS);
				break;
			default:
				print_help();
				exit(EXIT_FAILURE);
		}
	}

	if ((argc - optind != 1)){
		printf("\nError!: no hostname was specified\n");
		print_help();
		exit(EXIT_FAILURE);
	}

	totalpkts=rate*runtime;
	runForever = (totalpkts < 0);
	hostname = argv[argc-1];

	// Construct a minimal NTP request packet
  ntp_pkt packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  memset( &packet, 0, sizeof( ntp_pkt ) );
  *( ( char * ) &packet + 0 ) = 0x1b;

	// Open the socket
  struct sockaddr_in serv_addr;
  struct hostent *server;
  sockfd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
  if ( sockfd < 0 )
    error_exit( "ERROR opening socket" );

  server = gethostbyname( hostname );
  if ( server == NULL )
    error_exit( "ERROR, no such host" );
  bzero( ( char* ) &serv_addr, sizeof( serv_addr ) );

  serv_addr.sin_family = AF_INET;
  bcopy( ( char* )server->h_addr, ( char* ) &serv_addr.sin_addr.s_addr, server->h_length );
  serv_addr.sin_port = htons( portno );

  if ( connect( sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr) ) < 0 )
    error_exit( "ERROR connecting" );

	tusleep = rint(1000000.0/rate);
	gettimeofday(&tvstart,NULL); // takes a few microseconds

	pktsize = sizeof( ntp_pkt );
	nsent=0;
	while (totalpkts > 0 || runForever){
		gettimeofday(&tvstartpoll,NULL);
		nleft = pktsize;
		pbuf = (char *)(&packet);
		while (nleft > 0){
			if (( nw = write(sockfd,pbuf,nleft)) <= 0){
				fprintf(stderr,"write error\n");
				break;
			}
			nleft -=nw;
			pbuf += nw;
		}
		totalpkts--;
		gettimeofday(&tvstoppoll,NULL);
		tupoll = (tvstoppoll.tv_sec - tvstartpoll.tv_sec)*1000000+(tvstoppoll.tv_usec - tvstartpoll.tv_usec);
		if (tupoll >= tusleep)
			tupoll=tusleep;
		struct timespec ts;
		ts.tv_sec=0;
		ts.tv_nsec = (tusleep-tupoll)*1000;
		nanosleep(&ts,NULL);
		nsent++;
	}
	gettimeofday(&tvstop,NULL);
	printf("Sent %i packets in %g s %i\n",nsent,(tvstop.tv_sec - tvstart.tv_sec)+(tvstop.tv_usec - tvstart.tv_usec)/1.0E6,tupoll);
  return EXIT_SUCCESS;
}


text:
using BizHawk.Common;

namespace BizHawk.Emulation.Cores.Nintendo.NES
{
	// mapper036
	// Strike Wolf (MGC-014) [!].nes
	// like an oversize GxROM
	// information from fceux
	public sealed class Mapper036 : NES.NESBoardBase
	{
		int chr;
		int prg;
		int chr_mask;
		int prg_mask;

		public override bool Configure(NES.EDetectionOrigin origin)
		{
			switch (Cart.board_type)
			{
				case "MAPPER036":
					AssertVram(0);
					Cart.wram_size = 0; // AssertWram(0); // GoodNES good dump of Strike Wolf specifies 8kb of wram
					break;
				default:
					return false;
			}
			chr_mask = Cart.chr_size / 8 - 1;
			prg_mask = Cart.prg_size / 32 - 1;
			SetMirrorType(Cart.pad_h, Cart.pad_v);
			return true;
		}

		public override byte ReadPPU(int addr)
		{
			if (addr < 0x2000)
				return VROM[addr | chr << 13];
			else
				return base.ReadPPU(addr);
		}

		public override byte ReadPRG(int addr)
		{
			return ROM[addr | prg << 15];
		}

		public override void WritePRG(int addr, byte value)
		{
			// either hack emulation of a weird bus conflict, or crappy pirate safeguard
			if (addr >= 0x400 && addr <= 0x7ffe)
			{
				chr = value & 15 & chr_mask;
				prg = value >> 4 & 15 & prg_mask;
			}
		}

		public override void SyncState(Serializer ser)
		{
			base.SyncState(ser);
			ser.Sync("chr", ref chr);
			ser.Sync("prg", ref prg);
		}
	}
}


text:
<?php
declare(strict_types = 1);

namespace Nepada\Bridges\BustCacheLatte;

use Latte;
use Latte\Compiler\Tag;
use Latte\Engine;
use Nepada\Bridges\BustCacheLatte\Nodes\BustCacheNode;
use Nepada\BustCache\BustCachePathProcessor;

final class BustCacheLatteExtension extends Latte\Extension
{

    private BustCachePathProcessor $bustCachePathProcessor;

    private bool $strictMode;

    private bool $autoRefresh;

    public function __construct(BustCachePathProcessor $bustCachePathProcessor, bool $strictMode, bool $autoRefresh)
    {
        $this->bustCachePathProcessor = $bustCachePathProcessor;
        $this->strictMode = $strictMode;
        $this->autoRefresh = $autoRefresh;
    }

    /**
     * @return array<string, callable(Latte\Compiler\Tag, Latte\Compiler\TemplateParser): (Latte\Compiler\Node|\Generator|void)|\stdClass>
     */
    public function getTags(): array
    {
        return [
            'bustCache' => fn (Tag $tag): BustCacheNode => Nodes\BustCacheNode::create($tag, $this->strictMode, $this->autoRefresh, $this->bustCachePathProcessor),
        ];
    }

    /**
     * @return array<mixed>
     */
    public function getProviders(): array
    {
        return [
            'bustCachePathProcessor' => $this->bustCachePathProcessor,
        ];
    }

    public function getCacheKey(Engine $engine): mixed
    {
        return [
            'strictMode' => $this->strictMode,
            'autoRefresh' => $this->autoRefresh,
        ];
    }

}


text:
class PizaidNetwork:
    def __init__(self, client):
        self.client = client
    def get_ipv4(self):
        return self.client.network_get_ipv4()
    def get_ipv6(self):
        return self.client.network_get_ipv6()


text:
/**
 * Generic framework code included with
 * Expert One-On-One J2EE Design and Development
 * by Rod Johnson (Wrox, 2002).
 * This code is free to use and modify. However, please
 * acknowledge the source and include the above URL in each
 * class using or derived from this code.
 * Please contact rod.johnson@interface21.com
 * for commercial support.
 */

package com.interface21.jndi;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Helper class that simplifies JNDI operations. It provides methods to lookup
 * and bind, and allows implementations of the ContextCallback interface to
 * perform any operation they like with a JNDI naming context provided.
 *
 *
This is the central class in this package. It is analogous to the
 * JdbcTemplate class. This class performs all error handling.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see ContextCallback
 * @see com.interface21.jdbc.core.JdbcTemplate
 */
public class JndiTemplate {

	protected final Log logger = LogFactory.getLog(getClass());

	private Properties environment;

	/**
	 * Create a new JndiTemplate instance.
	 */
	public JndiTemplate() {
	}

	/**
	 * Create a new JndiTemplate instance, using the given environment.
	 */
	public JndiTemplate(Properties environment) {
		this.environment = environment;
	}

	/**
	 * Set the environment for the InitialContext.
	 */
	public void setEnvironment(Properties environment) {
		this.environment = environment;
	}

	public Properties getEnvironment() {
		return environment;
	}

	/**
	 * Lookup the object with the given name in the current JNDI context.
	 * @param name JNDI name of the object
	 * @return object found (cannot be null, if a not so well-behaved
	 * JNDI implementations returns null, a NamingException gets thrown)
	 * @throws NamingException if there is no object with the given
	 * name bound to JNDI
	 */
	public Object lookup(final String name) throws NamingException {
		return execute(new ContextCallback() {
			public Object doInContext(Context ctx) throws NamingException {
				logger.debug("Looking up JNDI object with name '" + name + "'");
				Object lookedUp = ctx.lookup(name);
				if (lookedUp == null) {
					throw new NamingException("JNDI object not found: JNDI implementation returned null");
				}
				return lookedUp;
			}
		});
	}

	/**
	 * Bind the given object to the current JNDI context, using the given name.
	 * @param name JNDI name of the object
	 * @param object object to bind
	 * @throws NamingException  thrown by JNDI, mostly name already bound
	 */
	public void bind(final String name, final Object object) throws NamingException {
		execute(new ContextCallback() {
			public Object doInContext(Context ctx) throws NamingException {
				logger.info("Binding JNDI object with name " + name);
				ctx.bind(name, object);
				return null;
			}
		});
	}

	/**
	 * Remove the binding for the given name from the current JNDI context.
	 * @param name  the JNDI name of the object
	 * @throws NamingException thrown by JNDI, mostly name not found
	 */
	public void unbind(final String name) throws NamingException {
		execute(new ContextCallback() {
			public Object doInContext(Context ctx) throws NamingException {
				logger.info("Unbinding JNDI object with name " + name);
				ctx.unbind(name);
				return null;
			}
		});
	}

	/**
	 * Execute the given callback implementation.
	 * @param contextCallback ContextCallback implementation
	 * @return a result object returned by the callback, or null
	 * @throws NamingException thrown by the callback implementation.
	 */
	public Object execute(ContextCallback contextCallback) throws NamingException {
		Context ctx = null;
		try {
			ctx = createInitialContext();
			return contextCallback.doInContext(ctx);
		}
		finally {
			try {
				if (ctx != null)
					ctx.close();
			}
			catch (NamingException ex) {
				logger.warn("InitialContext threw exception on close", ex);
			}
		}
	}

	/**
	 * Create a new initial context.
	 * The default implementation use this template's environment settings.
	 * Can be subclassed for custom contexts, e.g. for testing.
	 * @return the new InitialContext instance
	 * @throws NamingException in case of initialization errors
	 */
	protected Context createInitialContext() throws NamingException {
		return new InitialContext(getEnvironment());
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <parent>
    <artifactId>project</artifactId>
    <groupId>org.mortbay.jetty</groupId>
    <version>6.1.26</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-assembly</artifactId>
  <packaging>pom</packaging>
  <name>Jetty :: Jetty Assembly</name>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>exec-site</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>mvn</executable>
              <workingDirectory>../..</workingDirectory>
              <arguments>
                <argument>-Dmaven.test.skip=true</argument>
                <argument>-Daggregate=true</argument>
                <argument>-Pgenerate-site</argument>
                <argument>remote-resources:process</argument>
                <argument>jxr:jxr</argument>
                <argument>javadoc:javadoc</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/site-component.xml</descriptor>
          </descriptors>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <reporting/>
</project>


text:
module Scaler
  class Configurator

    # Most of this will be overwritten by config_thread
    def default_configuration
      {
        :client_key => nil,
        :client_secret => nil,
        :sleeper_host => 'http://sleeperapp.com',
        :update_time => 60, # in seconds
        :config_update_time => 600, # every ten minutes
        :debug => false,
        :benchmarking => true,
        :explaining => true,
        :traces => false,
				:trace_depth => 10,
				:max_update_size => 2000000, # in bytes. change this and your uploads may not work.
        :profiling => false,
        :peeking => false,
				:upload_timeout => 60, # Could take a while to stuff 2MB upstream ;)
				:compression => true, # TODO
				:verbose_statistics => false # TODO
      }
    end

    def initialize(manual_config=nil)
      @running = true

	 		if manual_config
		  	@config = default_configuration.merge(manual_config)
      else
				@config = default_configuration
				output = ERB.new(File.open("#{RAILS_ROOT}/config/sleeper.yml").read).result
				@config.merge!(YAML::load(output)) rescue nil

     		ENV['SLEEPER-CONFIG-THREAD'] = Thread.new {
            	sleep 5 # initial time before we rock and roll
            	config_thread
          	}.inspect

				end
    end

    def update_config
      uri = URI.parse(@config[:sleeper_host]+'/apps/'+@config[:client_key]+'/environments/'+Rails.env+'.js')
      result = Net::HTTP.get(uri) rescue nil
      new_config = Hash[*ActiveSupport::JSON.decode(result).collect{|k,v| {k.to_sym=>v} }.collect{|z| z.to_a }.flatten]
      @config.merge!(new_config) rescue nil
      # TODO: re analyze config, uninstall everything and reinstall what needs to be reinstalled

	  # there's a few second hole here where modules will flicker off & on
	  Scaler.unload_modules
	  Scaler.load_modules
    end

    def config_thread
      while @running
        begin
          Scaler.log(:config) { 'Updating configuration...' }
          update_config
		rescue ActiveSupport::JSON::ParseError
			Scaler.log(:config) { 'Unable to update configuration, we received some bad JSON. (Is Sleeper down?) We\'ll try again in a few minutes.' }
			sleep 600 # wait 10 minutes, we'll use default behavior for now
        rescue Exception => e
          Scaler.log(:error, Logger::ERROR) { e }
          Scaler.log(:error, Logger::ERROR) { e.backtrace }
        end
        sleep Scaler.config?(:config_update_time)
      end
    end

    def config(key);@config[key];end

  end
end


text:
using System;
using RegTesting.Contracts;

namespace RegTesting.Service.Mail
{

	/// <summary>
	///  A mail for longlife tests WorkerErrors
	/// </summary>
	public class WorkerLongLifeTestErrorMail : AbstractMail
	{
		private readonly WorkItem _workItem;
		private readonly string _testNode;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="workItem">The workItem causing the error </param>
		/// <param name="testNode">the corresponding testNode </param>
		public WorkerLongLifeTestErrorMail(WorkItem workItem, string testNode)
		{
			_workItem = workItem;
			_testNode = testNode;
		}

		/// <summary>
		/// Send the mail
		/// </summary>
		public void Send()
		{
			String subject = "WARNUNG! Longlife test detected!" + _testNode + ".";
			String body = "Der Test " + _workItem + " läuft seit mehr als " + RegtestingServerConfiguration.DefaultLongLifeTime + " Minuten. Möglicher Endlostest! Auf Node: " + _testNode + " .";

			SendMail(RegtestingServerConfiguration.Errormailadress, subject, body);
		}
	}
}


text:
/*! nextcss/util
 * Somewhat inspired by (and includes parts of):
 *   http://getbootstrap.com
 *   http://typeplate.com
 *   http://nicolasgallagher.com/micro-clearfix-hack/
 */

@custom-media --hidpi only screen and (-webkit-min-device-pixel-ratio: 1.5),
	only screen and (min--moz-device-pixel-ratio: 1.5),
	only screen and (-o-min-device-pixel-ratio: 1.5/1),
	only screen and (min-resolution: 144dpi),
	only screen and (min-resolution: 1.5dppx);

:root {
	--tera: 6.5rem;
	--giga: 5rem;
	--mega: 4rem;
	--alpha: 3.1875rem;
	--beta: 2.6875rem;
	--gamma: 2rem;
	--delta: 1.3333rem;
	--epsilon: 1.1667rem;
	--zeta: 1rem;
}

%clearfix:before, %clearfix:after {
	content: " ";
	display: table;
}

%clearfix:after {
	clear: both;
}

%small-caps {
	font-variant: small-caps;
	text-transform: uppercase;
}

/* Only for screenreaders */
%sr-only {
	position: absolute;
	width: 1px;
	height: 1px;
	padding: 0px;
	margin: -1px;
	overflow: hidden;
	clip: rect(0px,0px,0px,0px);
	border: 0px none;
}

%round {
	border-radius: 999em;
}

%heading {
	color: black;
	text-rendering: optimizeLegibility; /* voodoo to enable ligatures and kerning */
	line-height: 1; /* this fixes huge spaces when a heading wraps onto two lines */
	margin-bottom: calc(var(--n-line-em) / 2);
}

& small {
	font-size: 50%;
	color: gray;
}

%content {
	margin: 0 0 var(--n-line-em);
}


text:
namespace EspaceClient.BackOffice.Services.Contracts
{
    public partial interface IServiceZonePage
    {
    }
}


text:
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const log = console.log; // eslint-disable-line

const multi_entry = require('rollup-plugin-multi-entry');
const commonjs = require('rollup-plugin-commonjs');
const node_resolve = require('rollup-plugin-node-resolve');
const postcss = require('rollup-plugin-postcss');
const buble = require('rollup-plugin-buble');
const { terser } = require('rollup-plugin-terser');
const vue = require('rollup-plugin-vue');
const frappe_html = require('./frappe-html-plugin');
const less_loader = require('./less-loader');

const production = process.env.FRAPPE_ENV === 'production';

const {
	apps_list,
	assets_path,
	bench_path,
	get_public_path,
	get_app_path,
	get_build_json,
	get_options_for_scss
} = require('./rollup.utils');

function get_rollup_options(output_file, input_files) {
	if (output_file.endsWith('.js')) {
		return get_rollup_options_for_js(output_file, input_files);
	} else if(output_file.endsWith('.css')) {
		return get_rollup_options_for_css(output_file, input_files);
	}
}

function get_rollup_options_for_js(output_file, input_files) {

	const node_resolve_paths = [].concat(
		// node_modules of apps directly importable
		apps_list.map(app => path.resolve(get_app_path(app), '../node_modules')).filter(fs.existsSync),
		// import js file of any app if you provide the full path
		apps_list.map(app => path.resolve(get_app_path(app), '..')).filter(fs.existsSync)
	);

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// .html -> .js
		frappe_html(),
		// ignore css imports
		ignore_css(),
		// .vue -> .js
		vue.default(),
		// ES6 -> ES5
		buble({
			objectAssign: 'Object.assign',
			transforms: {
				dangerousForOf: true,
				classes: false
			},
			exclude: [path.resolve(bench_path, '**/*.css'), path.resolve(bench_path, '**/*.less')]
		}),
		commonjs(),
		node_resolve({
			customResolveOptions: {
				paths: node_resolve_paths
			}
		}),
		production && terser()
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			context: 'window',
			external: ['jquery'],
			onwarn({ code, message, loc, frame }) {
				// skip warnings
				if (['EVAL', 'SOURCEMAP_BROKEN', 'NAMESPACE_CONFLICT'].includes(code)) return;

				if ('UNRESOLVED_IMPORT' === code) {
					log(chalk.yellow.underline(code), ':', message);
					const command = chalk.yellow('bench setup requirements');
					log(`Cannot find some dependencies. You may have to run "${command}" to install them.`);
					log();
					return;
				}

				if (loc) {
					log(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
					if (frame) log(frame);
				} else {
					log(chalk.yellow.underline(code), ':', message);
				}
			}
		},
		outputOptions: {
			file: path.resolve(assets_path, output_file),
			format: 'iife',
			name: 'Rollup',
			globals: {
				'jquery': 'window.jQuery'
			},
			sourcemap: true
		}
	};
}

function get_rollup_options_for_css(output_file, input_files) {
	const output_path = path.resolve(assets_path, output_file);
	const starts_with_css = output_file.startsWith('css/');

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// less -> css
		postcss({
			plugins: [
				starts_with_css ? require('autoprefixer')() : null,
				starts_with_css && production ? require('cssnano')({ preset: 'default' }) : null
			].filter(Boolean),
			extract: output_path,
			loaders: [less_loader],
			use: [
				['less', {
					// import other less/css files starting from these folders
					paths: [
						path.resolve(get_public_path('frappe'), 'less')
					]
				}],
				['sass', {
					...get_options_for_scss(),
					outFile: output_path,
					sourceMapContents: true
				}]
			],
			include: [
				path.resolve(bench_path, '**/*.less'),
				path.resolve(bench_path, '**/*.scss'),
				path.resolve(bench_path, '**/*.css')
			],
			sourceMap: starts_with_css && !production
		})
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			onwarn(warning) {
				// skip warnings
				if (['EMPTY_BUNDLE'].includes(warning.code)) return;

				// console.warn everything else
				log(chalk.yellow.underline(warning.code), ':', warning.message);
				log(warning);
			}
		},
		outputOptions: {
			// this file is always empty, remove it later?
			file: path.resolve(assets_path, `css/rollup.manifest.css`),
			format: 'cjs'
		}
	};
}

function get_options(file, app="frappe") {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file === file) {
				if (output_file.startsWith('concat:')) return null;
				const input_files = build_json[output_file]
					.map(input_file => {
						let prefix = get_app_path(app);
						if (input_file.startsWith('node_modules/')) {
							prefix = path.resolve(get_app_path(app), '..');
						}
						return path.resolve(prefix, input_file);
					});
				return Object.assign(
					get_rollup_options(output_file, input_files), {
						output_file
					});
			}
		})
		.filter(Boolean);
}

function get_options_for(app) {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file.startsWith('concat:')) return null;

			let files = build_json[output_file];
			if (typeof files === 'string') {
				files = [files];
			}
			const input_files = files
				.map(input_file => {
					let prefix = get_app_path(app);
					if (input_file.startsWith('node_modules/')) {
						prefix = path.resolve(get_app_path(app), '..');
					}
					return path.resolve(prefix, input_file);
				});
			return Object.assign(
				get_rollup_options(output_file, input_files), {
					output_file
				});
		})
		.filter(Boolean);
}

function ignore_css() {
	return {
		name: 'ignore-css',
		transform(code, id) {
			if (!['.css', '.scss', '.sass', '.less'].some(ext => id.endsWith(ext))) {
				return null;
			}

			return `
				// ignored ${id}
			`;
		}
	};
};

module.exports = {
	get_options_for,
	get_options
};


text:
<?php declare(strict_types=1);

namespace DrdPlus\Codes\Armaments;

interface ProtectiveArmamentCode extends ArmamentCode
{
    /**
     * @return bool
     */
    public function isArmor(): bool;

    /**
     * @return bool
     */
    public function isShield(): bool;
}


text:
extern cmd_info_t gcd_info;
#endif // CMDGCD_H


text:
package gov.hhs.fha.nhinc.admingui.model.direct;

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

/**
 *
 * @author jasonasmith
 */
public class DirectDomain {

    private int position;
    private String domainStatus;
    private String domainName;
    private String domainPostMaster;
    private String domainCreated;
    private String domainUpdated;

    private List<DirectAddress> addresses = new ArrayList<DirectAddress>();
    private List<DirectAnchor> anchors = new ArrayList<DirectAnchor>();
    private List<DirectTrustBundle> trustBundles = new ArrayList<DirectTrustBundle>();

    /**
     *
     */
    public DirectDomain(){

    }

    /**
     *
     * @param position
     * @param domainStatus
     * @param domainName
     * @param domainPostMaster
     * @param domainCreated
     * @param domainUpdated
     */
    public DirectDomain(int position, String domainStatus, String domainName, String domainPostMaster, String domainCreated, String domainUpdated) {
        this.position = position;
        this.domainStatus = domainStatus;
        this.domainName = domainName;
        this.domainPostMaster = domainPostMaster;
        this.domainCreated = domainCreated;
        this.domainUpdated = domainUpdated;
    }

    /**
     *
     * @return
     */
    public int getPosition() {
        return position;
    }

    /**
     *
     * @param position
     */
    public void setPosition(int position) {
        this.position = position;
    }

    /**
     *
     * @return
     */
    public String getDomainStatus() {
        return domainStatus;
    }

    /**
     *
     * @param domainStatus
     */
    public void setDomainStatus(String domainStatus) {
        this.domainStatus = domainStatus;
    }

    /**
     *
     * @return
     */
    public String getDomainName() {
        return domainName;
    }

    /**
     *
     * @param domainName
     */
    public void setDomainName(String domainName) {
        this.domainName = domainName;
    }

    /**
     *
     * @return
     */
    public String getDomainPostMaster() {
        return domainPostMaster;
    }

    /**
     *
     * @param domainPostMaster
     */
    public void setDomainPostMaster(String domainPostMaster) {
        this.domainPostMaster = domainPostMaster;
    }

    /**
     *
     * @return
     */
    public String getDomainCreated() {
        return domainCreated;
    }

    /**
     *
     * @param domainCreated
     */
    public void setDomainCreated(String domainCreated) {
        this.domainCreated = domainCreated;
    }

    /**
     *
     * @return
     */
    public String getDomainUpdated() {
        return domainUpdated;
    }

    /**
     *
     * @param domainUpdated
     */
    public void setDomainUpdated(String domainUpdated) {
        this.domainUpdated = domainUpdated;
    }

    /**
     *
     * @return
     */
    public List<DirectAddress> getAddresses() {
        return addresses;
    }

    /**
     *
     * @param addresses
     */
    public void setAddresses(List<DirectAddress> addresses) {
        this.addresses = addresses;
    }

    /**
     *
     * @param address
     */
    public void addAddress(DirectAddress address){
        addresses.add(address);
    }

    /**
     *
     * @return
     */
    public List<DirectAnchor> getAnchors() {
        return anchors;
    }

    /**
     *
     * @param anchors
     */
    public void setAnchors(List<DirectAnchor> anchors) {
        this.anchors = anchors;
    }

    /**
     *
     * @param anchor
     */
    public void addAnchor(DirectAnchor anchor){
        anchors.add(anchor);
    }

    /**
     *
     * @return
     */
    public List<DirectTrustBundle> getTrustBundles() {
        return trustBundles;
    }

    /**
     *
     * @param trustBundles
     */
    public void setTrustBundles(List<DirectTrustBundle> trustBundles) {
        this.trustBundles = trustBundles;
    }

    /**
     *
     * @param tb
     */
    public void addTrustBundle(DirectTrustBundle tb){
        trustBundles.add(tb);
    }

    /**
     *
     * @param tbs
     */
    public void addTrustBundles(List<DirectTrustBundle> tbs){
        trustBundles.addAll(tbs);
    }
}


text:
package com.navercorp.pinpoint.test.junit4;

import org.junit.runners.model.Statement;

/**
 * @author emeroad
 */
public class BeforeCallbackStatement extends Statement {

    private final Statement before;
    private final Statement statement;

    public BeforeCallbackStatement(Statement statement, Statement before) {
        if (statement == null) {
            throw new NullPointerException("statement");
        }
        if (before == null) {
            throw new NullPointerException("BEFORE");
        }

        this.statement = statement;
        this.before = before;
    }

    @Override
    public void evaluate() throws Throwable {
        this.before.evaluate();
        this.statement.evaluate();
    }

}


text:
extern "C" {
#endif

typedef struct
    {
    CGPoint a,b;
    }
    ZLine;

static inline ZLine ZLineMake(CGPoint a1, CGPoint b1)
    {
    ZLine l;
    l.a = a1;
    l.b = b1;
    return l;
    }

extern ZLine const ZLineZero;
extern ZLine ZLineIntersectingArcWithCenter(CGPoint center, CGFloat centerAngle, CGFloat radius);
extern NSString* NSStringFromZLine(ZLine line);

//-----------------------------------------------------------------------------------------------
//
//                                                                              ZLineIntersection
//
//-----------------------------------------------------------------------------------------------

//  Use these functions to check for ZLineIntersection special values --

static inline bool ZLineIntersectionIsParallel(CGPoint p)           { return (!isnan(p.x) && isnan(p.y)); }
static inline bool ZLineIntersectionIsCoincidental(CGPoint p)       { return (isnan(p.x) && !isnan(p.y)); }
static inline bool ZLineIntersectionIsNone(CGPoint p)               { return (isnan(p.x) && isnan(p.y)); }
static inline bool ZLineIntersectionDoesIntersect(CGPoint p)        { return (!isnan(p.x) && !isnan(p.y)); }

extern CGPoint ZLineIntersectionPoint(ZLine l1, ZLine l2);

//-----------------------------------------------------------------------------------------------
//                                                                            Other Intersections
//-----------------------------------------------------------------------------------------------

extern BOOL ZLineIntersectsRect(ZLine line, CGRect rect);
extern BOOL ZLineIntersectsLine(ZLine line1, ZLine line2);

#ifdef __cplusplus
}
#endif


text:
<?php
/**
 * PackageTypeListResponse
 *
 * PHP version 5
 *
 * @category Class
 * @package  BumbalClient
 * @author   Swaagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * Bumbal Client Api
 *
 * Bumbal API documentation
 *
 * OpenAPI spec version: 2.0
 * Contact: gerb@bumbal.eu
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace BumbalClient\Model;

use \ArrayAccess;

/**
 * PackageTypeListResponse Class Doc Comment
 *
 * @category    Class
 * @package     BumbalClient
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class PackageTypeListResponse implements ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      * @var string
      */
    protected static $swaggerModelName = 'PackageTypeListResponse';

    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerTypes = [
        'items' => '\BumbalClient\Model\PackageTypeModel[]',
        'count_filtered' => 'int',
        'count_unfiltered' => 'int',
        'count_limited' => 'int'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerFormats = [
        'items' => null,
        'count_filtered' => null,
        'count_unfiltered' => null,
        'count_limited' => null
    ];

    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name, and the value is the original name
     * @var string[]
     */
    protected static $attributeMap = [
        'items' => 'items',
        'count_filtered' => 'count_filtered',
        'count_unfiltered' => 'count_unfiltered',
        'count_limited' => 'count_limited'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     * @var string[]
     */
    protected static $setters = [
        'items' => 'setItems',
        'count_filtered' => 'setCountFiltered',
        'count_unfiltered' => 'setCountUnfiltered',
        'count_limited' => 'setCountLimited'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     * @var string[]
     */
    protected static $getters = [
        'items' => 'getItems',
        'count_filtered' => 'getCountFiltered',
        'count_unfiltered' => 'getCountUnfiltered',
        'count_limited' => 'getCountLimited'
    ];

    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    public static function setters()
    {
        return self::$setters;
    }

    public static function getters()
    {
        return self::$getters;
    }

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     * @param mixed[] $data Associated array of property values initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['items'] = isset($data['items']) ? $data['items'] : null;
        $this->container['count_filtered'] = isset($data['count_filtered']) ? $data['count_filtered'] : null;
        $this->container['count_unfiltered'] = isset($data['count_unfiltered']) ? $data['count_unfiltered'] : null;
        $this->container['count_limited'] = isset($data['count_limited']) ? $data['count_limited'] : null;
    }

    /**
     * show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalid_properties = [];

        return $invalid_properties;
    }

    /**
     * validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {

        return true;
    }

    /**
     * Gets items
     * @return \BumbalClient\Model\PackageTypeModel[]
     */
    public function getItems()
    {
        return $this->container['items'];
    }

    /**
     * Sets items
     * @param \BumbalClient\Model\PackageTypeModel[] $items
     * @return $this
     */
    public function setItems($items)
    {
        $this->container['items'] = $items;

        return $this;
    }

    /**
     * Gets count_filtered
     * @return int
     */
    public function getCountFiltered()
    {
        return $this->container['count_filtered'];
    }

    /**
     * Sets count_filtered
     * @param int $count_filtered Count of total items with filters in place
     * @return $this
     */
    public function setCountFiltered($count_filtered)
    {
        $this->container['count_filtered'] = $count_filtered;

        return $this;
    }

    /**
     * Gets count_unfiltered
     * @return int
     */
    public function getCountUnfiltered()
    {
        return $this->container['count_unfiltered'];
    }

    /**
     * Sets count_unfiltered
     * @param int $count_unfiltered Count of total items without filters in place
     * @return $this
     */
    public function setCountUnfiltered($count_unfiltered)
    {
        $this->container['count_unfiltered'] = $count_unfiltered;

        return $this;
    }

    /**
     * Gets count_limited
     * @return int
     */
    public function getCountLimited()
    {
        return $this->container['count_limited'];
    }

    /**
     * Sets count_limited
     * @param int $count_limited Count of items with limit in place
     * @return $this
     */
    public function setCountLimited($count_limited)
    {
        $this->container['count_limited'] = $count_limited;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
        }

        return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
package org.ovirt.engine.ui.webadmin.binding;

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

import org.ovirt.engine.ui.webadmin.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.webadmin.idhandler.WithElementId;

import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JField;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.editor.rebind.model.ModelUtils;

/**
 * Walks through fields of an owner type for the given {@link ElementIdHandler} subinterface, generating DOM element IDs
 * and collecting corresponding field statements.
 *
 * @see ElementIdStatement
 */
public class ElementIdTypeParser {

    private static final String ID_ELEMENT_SEPARATOR = "_";

    private final TreeLogger logger;
    private final JClassType ownerType;

    final List<ElementIdStatement> statements = new ArrayList<ElementIdStatement>();

    public ElementIdTypeParser(TreeLogger logger, JClassType interfaceToImplement) throws UnableToCompleteException {
        assert logger != null : "logger was null";
        assert interfaceToImplement != null : "interfaceToImplement was null";

        this.logger = logger.branch(TreeLogger.DEBUG, "Creating ElementIdTypeParser for "
                + interfaceToImplement.getQualifiedSourceName());

        this.ownerType = resolveOwnerType(interfaceToImplement);
    }

    JClassType resolveOwnerType(JClassType interfaceToImplement) throws UnableToCompleteException {
        TypeOracle oracle = interfaceToImplement.getOracle();

        JClassType handlerInterface = oracle.findType(ElementIdHandler.class.getName()).isInterface();
        assert handlerInterface != null : "No ElementIdHandler type";

        if (!handlerInterface.isAssignableFrom(interfaceToImplement)) {
            die(String.format("Unexpected input type: %s is not assignable from %s",
                    handlerInterface.getQualifiedSourceName(), interfaceToImplement.getQualifiedSourceName()));
        } else if (interfaceToImplement.equals(handlerInterface)) {
            die(String.format("You must declare an interface that extends the %s type",
                    handlerInterface.getSimpleSourceName()));
        }

        JClassType[] interfaces = interfaceToImplement.getImplementedInterfaces();
        if (interfaces.length != 1) {
            die(String.format("The type %s extends more than one interface",
                    interfaceToImplement.getQualifiedSourceName()));
        }

        JClassType[] parameters = ModelUtils.findParameterizationOf(handlerInterface, interfaceToImplement);
        if (parameters.length != 1) {
            die(String.format("The type %s has unexpected number of type parameters",
                    interfaceToImplement.getQualifiedSourceName()));
        }

        return parameters[0];
    }

    public JClassType getOwnerType() {
        return ownerType;
    }

    public ElementIdStatement[] parseStatements() throws UnableToCompleteException {
        statements.clear();

        doParse(ownerType, new ArrayList<JClassType>(), ".", ownerTypeId());

        statements.add(new ElementIdStatement(
                ElementIdHandlerGenerator.ElementIdHandler_generateAndSetIds_owner,
                ownerTypeId()));

        return statements.toArray(new ElementIdStatement[0]);
    }

    void doParse(JClassType parentType, List<JClassType> grandParents, String parentFieldExpression,
            String idPrefix) throws UnableToCompleteException {
        for (JClassType type : parentType.getFlattenedSupertypeHierarchy()) {
            for (JField field : type.getFields()) {
                if (!processField(field)) {
                    continue;
                }

                JClassType fieldType = field.getType().isClass();
                String fieldName = field.getName();

                if (grandParents.contains(fieldType)) {
                    die(String.format("Field %s of type %s is already present on path from the owner type %s: %s",
                            fieldName, fieldType.getQualifiedSourceName(), ownerType.getQualifiedSourceName(),
                            grandParents.toString()));
                }

                WithElementId idAnnotation = field.getAnnotation(WithElementId.class);
                String fieldId = idAnnotation.value();
                if ("".equals(fieldId)) {
                    fieldId = fieldName;
                }

                String elementId = idPrefix + ID_ELEMENT_SEPARATOR + fieldId;
                String fieldExpression = ElementIdHandlerGenerator.ElementIdHandler_generateAndSetIds_owner
                        + parentFieldExpression + fieldName;
                ElementIdStatement statement = new ElementIdStatement(fieldExpression, elementId);

                if (statements.contains(statement)) {
                    die(String.format("Duplicate element ID %s for field %s of type %s",
                            elementId, fieldName, fieldType.getQualifiedSourceName()));
                }

                statements.add(statement);

                if (idAnnotation.processType()) {
                    List<JClassType> newGrandParents = new ArrayList<JClassType>(grandParents);
                    newGrandParents.add(fieldType);

                    doParse(fieldType, newGrandParents, parentFieldExpression + fieldName + ".", elementId);
                }
            }
        }
    }

    String ownerTypeId() {
        return ownerType.getName().replace(".", ID_ELEMENT_SEPARATOR);
    }

    boolean processField(JField field) {
        return !field.isPrivate() && !field.isStatic()
                && field.getType().isClass() != null
                && field.getAnnotation(WithElementId.class) != null;
    }

    void die(String lastWords) throws UnableToCompleteException {
        logger.log(TreeLogger.ERROR, lastWords);
        throw new UnableToCompleteException();
    }

}


text:
<?php

defined('ARI_FRAMEWORK_LOADED') or die('Direct Access to this location is not allowed.');

AriKernel::import('Web.LangListPageBase');

class lang_backendAriPage extends AriLangListPageBase
{
	function _init()
	{
		$this->_fileGroup = ARI_QUIZ_FILE_LANGBACKEND;
		$this->_defaultFileKey = ARI_QUIZ_CONFIG_BLANG;
		$this->_task = 'lang_backend';
		$this->_addTask = 'blang_add';

		parent::_init();
	}
}
?>


text:
![Alt text](./imgs/site-map.png)

## What are the 6 Phases of Web Design?

The 6 phases of web design are:
 - Information Gathering
 - Planning
 - Design
 - Development
 - Testing and Delivery
 - Maintenance

## What is your site's primary goal or purpose? What kind of content will your site feature?

The primary goal/purpose of my site is to be a professional website where i can show my work history, background, passion and projects along with a blog. The content will be updated with my projects and personal thoughts.

## What is your target audience's interests and how do you see your site addressing them?

My target audience is employers/people in the developing industry. My site will present employers with my portfolio along with some background about me and other information. For people in the tech industry, my blog show others a different perspective to a concept or something along those lines.

## What is the primary "action" the user should take when coming to your site? Do you want them to search for information, contact you, or see your portfolio? It's ok to have several actions at once, or different actions for different kinds of visitors.

The primary action would be to check out my blog/portfolio for all visitors. For potential employers, I want them to see my portfolio, background and contact information. For everyone else, I would like them to see my background, portfolio and blog. If they would like, they can contact me as well.

## What are the main things someone should know about design and user experience?

Design and User experience helps websites create a good experience for a visitor. User experience is how a person feels when they're interacting with the system (website, web app, software). The design aspect is how the website should look and feel. A website for teenagers and a website for financial institutions will look different. There are a lot of planning and research done with design and user experience. Small changes to a website could possibly lead to major profits.

## What is user experience design and why is it valuable?

User experience design is, like mentioned in the previous question, helps create a good experience for a person visiting the website. User experience designers evaluate how users will feel, ease of use, efficiency in performing tasks, etc. User experience design is valuable becasue it helps deal with the users' needs. If the users were unhappy, then the service being provided may not be running for long.

## Which parts of the challenge did you find tedious?

None. I felt like all the challenges were fair.

## Reflection

This challenge was interesting. I've never really thought about UX Design and how it worked. It's cool to see and learn about how it has changed from back then. There used to be no research and just create designs based on what looked aesthetic. Now, it's more of accessibility and all about the user. It makes a lot of sense though and obvious.