text:
/**
 * Autogenerated by Thrift Compiler (0.9.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.thriftfs.jobtracker.api;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description of a job queue
 */
public class ThriftJobQueueInfo implements org.apache.thrift.TBase<ThriftJobQueueInfo, ThriftJobQueueInfo._Fields>, java.io.Serializable, Cloneable {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ThriftJobQueueInfo");

  private static final org.apache.thrift.protocol.TField QUEUE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("queueName", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField SCHEDULING_INFO_FIELD_DESC = new org.apache.thrift.protocol.TField("schedulingInfo", org.apache.thrift.protocol.TType.STRING, (short)2);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new ThriftJobQueueInfoStandardSchemeFactory());
    schemes.put(TupleScheme.class, new ThriftJobQueueInfoTupleSchemeFactory());
  }

  public String queueName; // required
  public String schedulingInfo; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    QUEUE_NAME((short)1, "queueName"),
    SCHEDULING_INFO((short)2, "schedulingInfo");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // QUEUE_NAME
          return QUEUE_NAME;
        case 2: // SCHEDULING_INFO
          return SCHEDULING_INFO;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.QUEUE_NAME, new org.apache.thrift.meta_data.FieldMetaData("queueName", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.SCHEDULING_INFO, new org.apache.thrift.meta_data.FieldMetaData("schedulingInfo", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ThriftJobQueueInfo.class, metaDataMap);
  }

  public ThriftJobQueueInfo() {
  }

  public ThriftJobQueueInfo(
    String queueName,
    String schedulingInfo)
  {
    this();
    this.queueName = queueName;
    this.schedulingInfo = schedulingInfo;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ThriftJobQueueInfo(ThriftJobQueueInfo other) {
    if (other.isSetQueueName()) {
      this.queueName = other.queueName;
    }
    if (other.isSetSchedulingInfo()) {
      this.schedulingInfo = other.schedulingInfo;
    }
  }

  public ThriftJobQueueInfo deepCopy() {
    return new ThriftJobQueueInfo(this);
  }

  @Override
  public void clear() {
    this.queueName = null;
    this.schedulingInfo = null;
  }

  public String getQueueName() {
    return this.queueName;
  }

  public ThriftJobQueueInfo setQueueName(String queueName) {
    this.queueName = queueName;
    return this;
  }

  public void unsetQueueName() {
    this.queueName = null;
  }

  /** Returns true if field queueName is set (has been assigned a value) and false otherwise */
  public boolean isSetQueueName() {
    return this.queueName != null;
  }

  public void setQueueNameIsSet(boolean value) {
    if (!value) {
      this.queueName = null;
    }
  }

  public String getSchedulingInfo() {
    return this.schedulingInfo;
  }

  public ThriftJobQueueInfo setSchedulingInfo(String schedulingInfo) {
    this.schedulingInfo = schedulingInfo;
    return this;
  }

  public void unsetSchedulingInfo() {
    this.schedulingInfo = null;
  }

  /** Returns true if field schedulingInfo is set (has been assigned a value) and false otherwise */
  public boolean isSetSchedulingInfo() {
    return this.schedulingInfo != null;
  }

  public void setSchedulingInfoIsSet(boolean value) {
    if (!value) {
      this.schedulingInfo = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case QUEUE_NAME:
      if (value == null) {
        unsetQueueName();
      } else {
        setQueueName((String)value);
      }
      break;

    case SCHEDULING_INFO:
      if (value == null) {
        unsetSchedulingInfo();
      } else {
        setSchedulingInfo((String)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case QUEUE_NAME:
      return getQueueName();

    case SCHEDULING_INFO:
      return getSchedulingInfo();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case QUEUE_NAME:
      return isSetQueueName();
    case SCHEDULING_INFO:
      return isSetSchedulingInfo();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof ThriftJobQueueInfo)
      return this.equals((ThriftJobQueueInfo)that);
    return false;
  }

  public boolean equals(ThriftJobQueueInfo that) {
    if (that == null)
      return false;

    boolean this_present_queueName = true && this.isSetQueueName();
    boolean that_present_queueName = true && that.isSetQueueName();
    if (this_present_queueName || that_present_queueName) {
      if (!(this_present_queueName && that_present_queueName))
        return false;
      if (!this.queueName.equals(that.queueName))
        return false;
    }

    boolean this_present_schedulingInfo = true && this.isSetSchedulingInfo();
    boolean that_present_schedulingInfo = true && that.isSetSchedulingInfo();
    if (this_present_schedulingInfo || that_present_schedulingInfo) {
      if (!(this_present_schedulingInfo && that_present_schedulingInfo))
        return false;
      if (!this.schedulingInfo.equals(that.schedulingInfo))
        return false;
    }

    return true;
  }

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

  public int compareTo(ThriftJobQueueInfo other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;
    ThriftJobQueueInfo typedOther = (ThriftJobQueueInfo)other;

    lastComparison = Boolean.valueOf(isSetQueueName()).compareTo(typedOther.isSetQueueName());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetQueueName()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.queueName, typedOther.queueName);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetSchedulingInfo()).compareTo(typedOther.isSetSchedulingInfo());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetSchedulingInfo()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.schedulingInfo, typedOther.schedulingInfo);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("ThriftJobQueueInfo(");
    boolean first = true;

    sb.append("queueName:");
    if (this.queueName == null) {
      sb.append("null");
    } else {
      sb.append(this.queueName);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("schedulingInfo:");
    if (this.schedulingInfo == null) {
      sb.append("null");
    } else {
      sb.append(this.schedulingInfo);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class ThriftJobQueueInfoStandardSchemeFactory implements SchemeFactory {
    public ThriftJobQueueInfoStandardScheme getScheme() {
      return new ThriftJobQueueInfoStandardScheme();
    }
  }

  private static class ThriftJobQueueInfoStandardScheme extends StandardScheme<ThriftJobQueueInfo> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, ThriftJobQueueInfo struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // QUEUE_NAME
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.queueName = iprot.readString();
              struct.setQueueNameIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // SCHEDULING_INFO
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.schedulingInfo = iprot.readString();
              struct.setSchedulingInfoIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, ThriftJobQueueInfo struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.queueName != null) {
        oprot.writeFieldBegin(QUEUE_NAME_FIELD_DESC);
        oprot.writeString(struct.queueName);
        oprot.writeFieldEnd();
      }
      if (struct.schedulingInfo != null) {
        oprot.writeFieldBegin(SCHEDULING_INFO_FIELD_DESC);
        oprot.writeString(struct.schedulingInfo);
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class ThriftJobQueueInfoTupleSchemeFactory implements SchemeFactory {
    public ThriftJobQueueInfoTupleScheme getScheme() {
      return new ThriftJobQueueInfoTupleScheme();
    }
  }

  private static class ThriftJobQueueInfoTupleScheme extends TupleScheme<ThriftJobQueueInfo> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, ThriftJobQueueInfo struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.isSetQueueName()) {
        optionals.set(0);
      }
      if (struct.isSetSchedulingInfo()) {
        optionals.set(1);
      }
      oprot.writeBitSet(optionals, 2);
      if (struct.isSetQueueName()) {
        oprot.writeString(struct.queueName);
      }
      if (struct.isSetSchedulingInfo()) {
        oprot.writeString(struct.schedulingInfo);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, ThriftJobQueueInfo struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(2);
      if (incoming.get(0)) {
        struct.queueName = iprot.readString();
        struct.setQueueNameIsSet(true);
      }
      if (incoming.get(1)) {
        struct.schedulingInfo = iprot.readString();
        struct.setSchedulingInfoIsSet(true);
      }
    }
  }

}


text:
var delmodalConfig = {
    appid:0,
    head:"提示",
    content:"",
    callback:"clickSureCallback()"
};

function clickSureCallback(){
	deleteApp_RESTClient(delmodalConfig.appid);
}

function userDelete(id,trObj){
    delmodalConfig.appid=id;
    delmodalConfig.content="是否确定删除["+trObj.getElementsByTagName("td")[0].id+"]";
    showConfirm(delmodalConfig);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>node-pm Index</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			node-pm

					Modules

							clusterEvents

							Logger

							main

							master

							processEvents

					Events

							shutdown

	Index

node-pm

Run your nodejs service in style (think php-fpm for nodejs)

Installation

Install node-pm

    npm install -g node-pm

Usage

Run application

    node-pm app.js

List node-pm options

    node-pm

Run Tests

    npm test

Generate Docs

Install jsdoc

    npm install -g jsdoc

Generate Docs

    npm run-script docs

====================

Contributors:

[Craig Thayer](https://github.com/sazze)
[Kevin Smithson](https://github.com/sazze)

License: MIT

See LICENSE for the full license text.

		Sazze, Inc Copyright © 2012-2013

		Documentation generated by JSDoc 3.3.0-alpha9
		on Thu Sep 11 2014 11:45:56 GMT-0700 (PDT) using the DocStrap template.


text:
package org.mockserver.stop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jamesdbloom
 */
public class Stop {

    private static final Logger logger = LoggerFactory.getLogger(Stop.class);

    public static void stopQuietly(Stoppable lifeCycle) {
        if (lifeCycle != null) {
            try {
                lifeCycle.stop();
            } catch (Throwable throwable) {
                logger.debug("Exception stopping " + lifeCycle, throwable);
            }
        }
    }
}


text:
CREATE USER sec1 WITH
  LOGIN
  SUPERUSER
  NOINHERIT
  CREATEDB
  CREATEROLE
  NOREPLICATION;

CREATE DATABASE app_security1
    WITH
    OWNER = sec1
    ENCODING = 'UTF8'
    LC_COLLATE = 'English_United States.1252'
    LC_CTYPE = 'English_United States.1252'
    TABLESPACE = pg_default
    CONNECTION LIMIT = -1;

	-- DROP SCHEMA security1 ;

CREATE SCHEMA security1
    AUTHORIZATION sec1;

GRANT ALL ON SCHEMA security1 TO sec1;

ALTER USER sec1 SET search_path TO security1;


text:
import axios from 'axios';

import getCheerio from '../getCheerio';
import retryAxios from '../utils/retryAxios';

export default class IndexAV {
  constructor() {
    this.baseURL = 'https://indexav.com';
    this.http = axios.create({
      baseURL: this.baseURL,
    });
  }

  searchCode = (code) =>
    retryAxios(() => this.http.get(`/search?keyword=${code}`));

  getCodeInfo = async (code) => {
    let $;
    try {
      const { data } = await this.searchCode(code);
      $ = getCheerio(data);
    } catch (err) {
      console.error(`err message: ${err.message}`);
      console.error(`error at indexav axios.get code info`);
      return undefined;
    }

    let title = '';
    let models = [];
    let imgUrl = '';

    $('div.bs-callout')
      .children()
      .filter(
        (i, elem) =>
          $(elem)
            .children()
            .children()
            .children()
            .find('span.video_id')
            .text() === code
      )
      .children()
      .each((idx, elem) => {
        if ($(elem).hasClass('col-sm-7')) {
          title = $(elem).find('span.video_title').text();

          models = $(elem)
            .children()
            .children()
            .find('span.video_actor')
            .map((i, e) => $(e).text())
            .get();

          imgUrl = $(elem).find('span.preview_btn').attr('rel');
        }
      });

    return {
      title,
      models,
      imgUrl,
    };
  };
}


text:
package org.simpleframework.xml.core;

import java.lang.annotation.Annotation;

import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.strategy.Type;

/**
 * The Introspector object is used to determine the details
 * to use for an annotated field or method using both the field an
 * annotation details. This allows defaults to be picked up from the
 * method or field type if that have not been explicitly overridden
 * in the annotation.
 *
 * @author Niall Gallagher
 */
class Introspector {

   /**
    * This is the actual annotation from the specified contact.
    */
   private Annotation marker;

   /**
    * This is the field or method contact that has been annotated.
    */
   private Contact contact;

   /**
    * This is the label used to expose the annotation details.
    */
   private Label label;

   /**
    * Constructor for the Introspector object. This is
    * used to create an object that will use information available
    * within the field and annotation to determine exactly what
    * the name of the XML element is to be and the type to use.
    *
    * @param contact this is the method or field contact used
    * @param label this is the annotation on the contact object
    */
   public Introspector(Contact contact, Label label) {
      this.marker = contact.getAnnotation();
      this.contact = contact;
      this.label = label;
   }

   /**
    * This is used to acquire the Contact for this. The
    * contact is the actual method or field that has been annotated
    * and is used to set or get information from the object instance.
    *
    * @return the method or field that this signature represents
    */
   public Contact getContact() {
      return contact;
   }

   /**
    * This returns the dependent type for the annotation. This type
    * is the type other than the annotated field or method type that
    * the label depends on. For the ElementList this
    * can be the generic parameter to an annotated collection type.
    *
    * @return this is the type that the annotation depends on
    */
   public Type getDependent() throws Exception {
      return label.getDependent();
   }

   /**
    * This method is used to get the entry name of a label using
    * the type of the label. This ensures that if there is no
    * entry XML element name declared by the annotation that a
    * suitable name can be calculated from the annotated type.
    *
    * @return this returns a suitable XML entry element name
    */
   public String getEntry() throws Exception {
      Type depend = getDependent();
      Class type = depend.getType();

      if(type.isArray()) {
         type = type.getComponentType();
      }
      String name = getName(type);

      if(name == null) {
         return null;
      }
      return name.intern();
   }

   /**
    * This is used to acquire the name of the specified type using
    * the Root annotation for the class. This will
    * use either the name explicitly provided by the annotation or
    * it will use the name of the class that the annotation was
    * placed on if there is no explicit name for the root.
    *
    * @param type this is the type to acquire the root name for
    *
    * @return this returns the name of the type from the root
    *
    * @throws Exception if the class contains an illegal schema
    */
   private String getName(Class type) throws Exception {
      String name = getRoot(type);

      if(name != null) {
         return name;
      } else {
         name = type.getSimpleName();
      }
      return Reflector.getName(name);
   }

   /**
    * This will acquire the name of the Root annotation
    * for the specified class. This will traverse the inheritance
    * hierarchy looking for the root annotation, when it is found it
    * is used to acquire a name for the XML element it represents.
    *
    * @param type this is the type to acquire the root name with
    *
    * @return the root name for the specified type if it exists
    */
   private String getRoot(Class type) {
      Class real = type;

      while(type != null) {
         String name = getRoot(real, type);

         if(name != null) {
           return name;
         }
         type = type.getSuperclass();
      }
      return null;
   }

   /**
    * This will acquire the name of the Root annotation
    * for the specified class. This will traverse the inheritance
    * hierarchy looking for the root annotation, when it is found it
    * is used to acquire a name for the XML element it represents.
    *
    * @param real the actual type of the object being searched
    * @param type this is the type to acquire the root name with
    *
    * @return the root name for the specified type if it exists
    */
   private String getRoot(Class<?> real, Class<?> type) {
      String name = type.getSimpleName();

      if(type.isAnnotationPresent(Root.class)) {
         Root root = type.getAnnotation(Root.class);
         String text = root.name();

         if(!isEmpty(text)) {
            return text;
         }
         return Reflector.getName(name);
      }
      return null;
   }

   /**
    * This is used to determine the name of the XML element that the
    * annotated field or method represents. This will determine based
    * on the annotation attributes and the dependent type required
    * what the name of the XML element this represents is.
    *
    * @return this returns the name of the XML element expected
    */
   public String getName() throws Exception {
      String entry = label.getEntry();

      if(!label.isInline()) {
         entry = getDefault();
      }
      return entry.intern();
   }

   /**
    * This is used to acquire the name for an element by firstly
    * checking for an override in the annotation. If one exists
    * then this is returned if not then the name of the field
    * or method contact is returned.
    *
    * @return this returns the XML element name to be used
    */
   private String getDefault() throws Exception {
      String name = label.getOverride();

      if(!isEmpty(name)) {
         return name;
      }
      return contact.getName();
   }

   /**
    * This is used to acquire the XPath location of an XML entity.
    * The path is acquired from a Path annotation. If
    * this annotation is not defined for the field or method then
    * this will return null, representing no defined path.
    *
    * @return this will return the path for the field or method
    */
   public String getPath() {
      Path path = contact.getAnnotation(Path.class);

      if(path == null) {
         return null;
      }
      return path.value();
   }

   /**
    * This method is used to determine if a root annotation value is
    * an empty value. Rather than determining if a string is empty
    * be comparing it to an empty string this method allows for the
    * value an empty string represents to be changed in future.
    *
    * @param value this is the value to determine if it is empty
    *
    * @return true if the string value specified is an empty value
    */
   public boolean isEmpty(String value) {
      if(value != null) {
         return value.length() == 0;
      }
      return true;
   }

   /**
    * This method is used to construct a string that describes the
    * signature of an XML annotated field or method. This will use
    * the Contact object and the annotation used for
    * that contact to construct a string that has sufficient
    * information such that it can be used in error reporting.
    *
    * @return returns a string used to represent this signature
    */
   public String toString() {
      return String.format("%s on %s", marker, contact);
   }
}


text:
@protocol MBGLViewFrameSource;

@interface MBGLView : NSOpenGLView
@property (strong, nonatomic) NSObject <KeystoneTextureSourceProtocol> *frameSource;

- (void) startDisplayLink;
- (void) stopDisplayLink;

@end

@protocol MBGLViewFrameSource
- (CIImage*)GLView: (NSOpenGLView *)view wantsFrameWithOptions: (NSDictionary *)dict;
@end


text:
  NSLog(@"Entered: %s (%@:%d)", __func__, \
        [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__);
#else
#define Log(...) \
  do {           \
  } while (0);
#define LOG_ENTRY \
  do {            \
  } while (0);
#endif

//***************************************************************************

@interface Markup : RWAbstractPlugin<NSMenuDelegate> {
 @public
  BOOL usingSmartQuotes;
  NSString* _uniqueID;
}

+ (Markup*)sharedMarkupPlugin;
+ (NSBundle*)sharedBundle;

+ (NSArray*)markupStyles;

+ (NSNumber*)markupEnabledForFilterStyleInSelectedRange:(NSString*)markupStyleName;

+ (void)addMarkupMenuItem;

@end

//***************************************************************************

extern const NSString* const kMarkupStyleFilterCommand;
extern const NSString* const kMarkupStyleName;

extern const NSInteger kMarkupTextMenuItemTag;

//***************************************************************************


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 org.brixcms.plugin.site.resource;

import org.apache.wicket.IRequestTarget;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.RequestParameters;
import org.brixcms.Brix;
import org.brixcms.jcr.wrapper.BrixNode;
import org.brixcms.plugin.site.NodeConverter;
import org.brixcms.plugin.site.SimpleCallback;
import org.brixcms.plugin.site.SiteNodePlugin;
import org.brixcms.plugin.site.SitePlugin;
import org.brixcms.plugin.site.resource.admin.CreateResourcePanel;
import org.brixcms.plugin.site.resource.admin.ManageResourceNodeTabFactory;
import org.brixcms.plugin.site.resource.managers.image.ImageNodeTabFactory;
import org.brixcms.plugin.site.resource.managers.text.TextNodeTabFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ResourceNodePlugin implements SiteNodePlugin {
// ------------------------------ FIELDS ------------------------------

    public static final String TYPE = Brix.NS_PREFIX + "resource";

    private Map<String /* extension */, String /* mime-type */> mimeTypes = new ConcurrentHashMap<String, String>();

// --------------------------- CONSTRUCTORS ---------------------------

    public ResourceNodePlugin(SitePlugin sp) {
        registerDefaultMimeTypes();
        sp.registerManageNodeTabFactory(new ManageResourceNodeTabFactory());
        sp.registerManageNodeTabFactory(new ImageNodeTabFactory());
        sp.registerManageNodeTabFactory(new TextNodeTabFactory());
    }

    private void registerDefaultMimeTypes() {
        registerMimeType("application/xml", "xml");
        registerMimeType("text/html", "html", "htm", "dwt");
        registerMimeType("text/plain", "txt");
        registerMimeType("text/css", "css");
        registerMimeType("text/javascript", "js");
        registerMimeType("image/jpeg", "jpg", "jpeg");
        registerMimeType("image/png", "png");
        registerMimeType("image/gif", "gif");
        registerMimeType("application/octet-stream", "exe");
        registerMimeType("application/octet-stream", "dmg");
    }

    public void registerMimeType(String mimeType, String... extensions) {
        for (String s : extensions) {
            mimeTypes.put(s, mimeType);
        }
    }

// ------------------------ INTERFACE METHODS ------------------------

// --------------------- Interface SiteNodePlugin ---------------------

    public String getNodeType() {
        return TYPE;
    }

    public String getName() {
        return (new ResourceModel("resource", "Resource")).getObject();
    }

    public IRequestTarget respond(IModel<BrixNode> nodeModel, RequestParameters requestParameters) {
        // IRequestTarget switchTarget =
        // SwitchProtocolRequestTarget.requireProtocol(Protocol.HTTP);
        // if (switchTarget != null)
        // {
        // return switchTarget;
        // }
        // else
        // {
        return new ResourceRequestTarget(nodeModel);
        // }
    }

    public IModel<String> newCreateNodeCaptionModel(IModel<BrixNode> parentNode) {
        return new ResourceModel("create");
    }

    public Panel newCreateNodePanel(String id, IModel<BrixNode> parentNode, SimpleCallback goBack) {
        return new CreateResourcePanel(id, parentNode, goBack);
    }

    public NodeConverter getConverterForNode(BrixNode node) {
        return null;
    }

// -------------------------- OTHER METHODS --------------------------

    public String resolveMimeTypeFromFileName(String fileName) {
        int last = fileName.lastIndexOf(".");
        if (last != -1) {
            String ext = fileName.substring(last + 1).toLowerCase();
            return mimeTypeFromExtension(ext);
        }
        return null;
    }

    private String mimeTypeFromExtension(String ext) {
        return mimeTypes.get(ext);
    }
}


text:
require 'watirspec_helper'

describe 'Area' do
  before :each do
    browser.goto(WatirSpec.url_for('images.html'))
  end

  # Exists method
  describe '#exist?' do
    it 'returns true if the area exists' do
      expect(browser.area(id: 'NCE')).to exist
      expect(browser.area(id: /NCE/)).to exist
      expect(browser.area(title: 'Tables')).to exist
      expect(browser.area(title: /Tables/)).to exist
      expect(browser.area(href: 'tables.html')).to exist
      expect(browser.area(href: /tables/)).to exist

      expect(browser.area(index: 0)).to exist
      expect(browser.area(xpath: "//area[@id='NCE']")).to exist
    end

    it 'returns the first area if given no args' do
      expect(browser.area).to exist
    end

    it "returns false if the area doesn't exist" do
      expect(browser.area(id: 'no_such_id')).to_not exist
      expect(browser.area(id: /no_such_id/)).to_not exist
      expect(browser.area(title: 'no_such_title')).to_not exist
      expect(browser.area(title: /no_such_title/)).to_not exist

      expect(browser.area(href: 'no-tables.html')).to_not exist
      expect(browser.area(href: /no-tables/)).to_not exist

      expect(browser.area(index: 1337)).to_not exist
      expect(browser.area(xpath: "//area[@id='no_such_id']")).to_not exist
    end

    it "raises TypeError when 'what' argument is invalid" do
      expect { browser.area(id: 3.14).exists? }.to raise_error(TypeError)
    end
  end

  # Attribute methods
  describe '#id' do
    it 'returns the id attribute' do
      expect(browser.area(index: 0).id).to eq 'NCE'
    end

    it "returns an empty string if the element exists and the attribute doesn't" do
      expect(browser.area(index: 2).id).to eq ''
    end

    it "raises UnknownObjectException if the area doesn't exist" do
      expect { browser.area(id: 'no_such_id').id }.to raise_unknown_object_exception
      expect { browser.area(index: 1337).id }.to raise_unknown_object_exception
    end
  end

  describe '#respond_to?' do
    it 'returns true for all attribute methods' do
      expect(browser.area(index: 0)).to respond_to(:id)
    end
  end
end


text:
from unittest import mock

from oslo_config import cfg
from oslo_config import fixture as conf_fixture

from blazar import context
from blazar import tests
from blazar.utils.openstack import base
from blazar.utils.openstack import keystone
from blazar.utils import trusts

CONF = cfg.CONF

class TestTrusts(tests.TestCase):
    def setUp(self):
        super(TestTrusts, self).setUp()
        self.base = base
        self.trusts = trusts
        self.context = context
        self.keystone = keystone

        self.client = self.patch(self.keystone, 'BlazarKeystoneClient')
        self.patch(self.context, 'current')
        self.patch(self.base, 'url_for').return_value = 'http://www.foo.fake'

        self.cfg = self.useFixture(conf_fixture.Config(CONF))

    def test_create_trust(self):
        correct_trust = self.client().trusts.create()

        trust = self.trusts.create_trust()

        self.assertEqual(trust, correct_trust)

    def test_delete_trust(self):
        lease = mock.MagicMock(trust_id='1')

        self.trusts.delete_trust(lease)

        self.client.assert_called_once_with(trust_id='1')

    def test_create_ctx_from_trust(self):
        self.cfg.config(os_admin_project_name='admin')
        self.cfg.config(os_admin_username='admin')
        ctx = self.trusts.create_ctx_from_trust('1')
        fake_ctx_dict = {
            'auth_token': self.client().session.get_token(),
            'domain': None,
            'global_request_id': self.context.current().global_request_id,
            'is_admin': False,
            'is_admin_project': True,
            'project': self.client().session.get_project_id(),
            'project_domain': None,
            'read_only': False,
            'request_id': ctx.request_id,
            'resource_uuid': None,
            'roles': [],
            'service_catalog': ctx.service_catalog,
            'show_deleted': False,
            'system_scope': None,
            'user': None,
            'user_domain': None}
        self.assertDictContainsSubset(fake_ctx_dict, ctx.to_dict())

    def test_use_trust_auth_dict(self):
        def to_wrap(self, arg_to_update):
            return arg_to_update

        correct_trust = self.client().trusts.create()
        fill_with_trust_id = {}
        updated_arg = self.trusts.use_trust_auth()(to_wrap)(self,
                                                            fill_with_trust_id)
        self.assertIn('trust_id', updated_arg)
        self.assertEqual(correct_trust.id, updated_arg['trust_id'])

    def test_use_trust_auth_object(self):
        class AsDict(object):
            def __init__(self, value):
                self.value = value

            def as_dict(self):
                to_return = {}
                for key in dir(self):
                    to_return[key] = getattr(self, key)
                return to_return

        def to_wrap(self, arg_to_update):
            return arg_to_update

        correct_trust = self.client().trusts.create()
        fill_with_trust_id = AsDict(1)
        updated_arg = self.trusts.use_trust_auth()(to_wrap)(self,
                                                            fill_with_trust_id)
        self.assertIn('trust_id', updated_arg.as_dict())
        self.assertEqual(correct_trust.id, updated_arg.trust_id)


text:
// Copyright 1998-2013 Epic Games, Inc. All Rights Reserved.

#include "TreeMapModule.h"
#include "ITreeMap.h"
#include "XmlParser.h"

typedef TSharedPtr<class FTreeMapNode> FTreeMapNodePtr;
typedef TSharedRef<class FTreeMapNode> FTreeMapNodeRef;

/**
 * Rectangle used for tree maps
 */
struct FTreeMapRect
{
	/** Position of the rectangle */
	FVector2D Position;

	/** Dimensions of the rectangle */
	FVector2D Size;

	/** Default constructor */
	FTreeMapRect()
		: Position( FVector2D::ZeroVector ),
		  Size( FVector2D::ZeroVector )
	{
	}
};

/**
 * Single node in a tree map, which may have any number of child nodes, each with their own children and so on
 */
class FTreeMapNode
{

public:

	/** Pointer to the source data for this node */
	FTreeMapNodeDataPtr Data;

	/** List of child nodes */
	TArray< FTreeMapNodePtr > Children;

	/** For leaf nodes, the size of this node.  For non-leaf nodes, the size of all of my child nodes. */
	float Size;

	/** Node rectangle */
	FTreeMapRect Rect;

	/** Node rectangle, with padding applied */
	FTreeMapRect PaddedRect;

	/** Font to use for this node's title */
	FSlateFontInfo NameFont;

	/** Font to use for this node's second line title */
	FSlateFontInfo Name2Font;

	/** Font to use for this node's centered text */
	FSlateFontInfo CenterTextFont;

	/** True if the node is 'interactive'.  That is, we have enough room for a title area and padding for the node to be clicked on */
	bool bIsInteractive;

public:

	/** Default constructor for FTreeMapNode */
	FTreeMapNode( const FTreeMapNodeDataRef& InitNodeData );

	/** @return Returns true if this is a leaf node */
	bool IsLeafNode() const
	{
		return Children.Num() == 0;
	}

};

/**
 * Tree map object
 */
class FTreeMap : public ITreeMap
{

public:

	/** Default constructor for FTreeMap */
	FTreeMap( const FTreeMapOptions& Options, const FTreeMapNodeDataRef& RootNodeData );

	/** ITreeMap interface */
	virtual TArray<FTreeMapNodeVisualInfo> GetVisuals() override;

private:

	enum class ESplitDirection
	{
		Horizontal,
		Vertical
	};

	/** Recursively sets up nodes in the tree */
	void AddNodesRecursively( FTreeMapNodePtr& Node, const FTreeMapNodeDataRef& NodeData );

	/** Recursively caches the size of each node.  Leaf nodes get the size of their source node, while non-leaf nodes are set to the total size of all of their children */
	void CalculateNodeSizesRecursively( const FTreeMapNodeRef& Node, float& MaxNodeSize );

	/** Scales the specified node and all sub-nodes by the specified amount */
	void ScaleNodesRecursively( const FTreeMapNodeRef& NodeToScale, const float ScaleFactor );

	/** Sets up a node using the standard tree mapping algorithm */
	void MakeStandardTreeNode( const FTreeMapOptions& Options, FTreeMap::ESplitDirection SplitDirection, const FTreeMapNodeRef& Node );

	/** Sets up a node using a squarification method */
	void MakeSquarifiedTreeNode( const FTreeMapOptions& Options, const FTreeMapNodeRef& Node );

	/** Partitions nodes recursively */
	void PartitionNodesRecursively( const FTreeMapOptions& Options, FTreeMap::ESplitDirection SplitDirection, const FTreeMapNodeRef& Node );

	/** Pad all of the nodes in to make room for titles and border */
	void PadNodesRecursively( const FTreeMapOptions& Options, const FTreeMapNodeRef& Node, const int32 TreeDepth );

private:

	/** Root node in the tree map */
	FTreeMapNodePtr RootNode;
};

FTreeMapNode::FTreeMapNode( const FTreeMapNodeDataRef& InitNodeData )
	: Data( InitNodeData ),
	  Children(),
	  Size( 0.0f ),
	  Rect(),
	  PaddedRect(),
	  NameFont(),
	  Name2Font(),
	  CenterTextFont(),
	  bIsInteractive( true )
{
}

FTreeMap::FTreeMap( const FTreeMapOptions& Options, const FTreeMapNodeDataRef& RootNodeData )
{
	AddNodesRecursively( RootNode, RootNodeData );

	// Cache the size of every node
	float MaxNodeSize = 0.0f;
	CalculateNodeSizesRecursively( RootNode.ToSharedRef(), MaxNodeSize );

	// Also fix up the node sizes as we go.  We want the sizes to be proportional to the total display size
	const float DisplaySize = Options.DisplayWidth * Options.DisplayHeight;
	ScaleNodesRecursively( RootNode.ToSharedRef(), DisplaySize / MaxNodeSize );	// @todo treemap perf: Could use a scale factor w/ accessor instead of recursing here

	// The root node has a fixed position and size
	RootNode->Rect.Position = FVector2D::ZeroVector;
	RootNode->Rect.Size = FVector2D( Options.DisplayWidth, Options.DisplayHeight );

	// For regular tree types, we'll choose a "next split direction" that matches the aspect of the display area
	const float DisplayAspect = Options.DisplayWidth / Options.DisplayHeight;
	const bool bIsWiderThanTall = DisplayAspect >= 1.0f;
	const auto SplitDirection = bIsWiderThanTall ? ESplitDirection::Horizontal : ESplitDirection::Vertical;
	PartitionNodesRecursively( Options, SplitDirection, RootNode.ToSharedRef() );

	// Now add space for titles and borders
	const int32 TreeDepth = 0;
	PadNodesRecursively( Options, RootNode.ToSharedRef(), TreeDepth );
}

void FTreeMap::AddNodesRecursively( FTreeMapNodePtr& OutNode, const FTreeMapNodeDataRef& NodeData )
{
	// Setup this node
	OutNode = MakeShareable( new FTreeMapNode( NodeData ) );

	// Add children
	for( const auto& ChildNodeData : NodeData->Children )
	{
		FTreeMapNodePtr ChildNode;
		AddNodesRecursively( ChildNode, ChildNodeData.ToSharedRef() );

		OutNode->Children.Add( ChildNode );
	}
}

void FTreeMap::CalculateNodeSizesRecursively( const FTreeMapNodeRef& Node, float& MaxNodeSize )
{
	// Is this a leaf node?  Leaf nodes will actually determine the size of non-leaf nodes.
	if( Node->IsLeafNode() )
	{
		// NOTE: Size should really always be greater than zero here to get good results, but we don't want to assert.
		Node->Size = Node->Data->Size;
	}
	else
	{
		// Update child node sizes
		float TotalSizeOfChildren = 0.0f;
		float MaxSizeOfChildren = 0.0f;
		for( const auto& ChildNode : Node->Children )
		{
			CalculateNodeSizesRecursively( ChildNode.ToSharedRef(), MaxSizeOfChildren );
			TotalSizeOfChildren += ChildNode->Size;
		}

		// Container node.  If a size was explicitly set, then we'll use that size.
		if( Node->Data->Size > 0.0f )
		{
			Node->Size = Node->Data->Size;

			// Scale the child nodes to fit into the forced container size
			const float ScaleFactor = Node->Size / TotalSizeOfChildren;
			{
				for( const auto& ChildNode : Node->Children )
				{
					ScaleNodesRecursively( ChildNode.ToSharedRef(), ScaleFactor );
				}
			}
		}
		else
		{
			// Create a size for the node by summing it's child node sizes
			Node->Size = TotalSizeOfChildren;
		}

		// Sort our children, largest to smallest
		Node->Children.Sort( []( const FTreeMapNodePtr& A, const FTreeMapNodePtr& B ) { return A->Size > B->Size; } );
	}

	MaxNodeSize = FMath::Max( MaxNodeSize, Node->Size );
}

void FTreeMap::ScaleNodesRecursively( const FTreeMapNodeRef& NodeToScale, const float ScaleFactor )
{
	NodeToScale->Size *= ScaleFactor;

	for( const auto& ChildNode : NodeToScale->Children )
	{
		ScaleNodesRecursively( ChildNode.ToSharedRef(), ScaleFactor );
	}
}

void FTreeMap::MakeStandardTreeNode( const FTreeMapOptions& Options, FTreeMap::ESplitDirection SplitDirection, const FTreeMapNodeRef& Node )
{
	// Standard tree map algorithm.  We alternate between horizontal and vertical packing of children.  All children are packed
	// into a single row or column.  This makes it fairly easy to see the hierarchical structure of the tree, but yields really long rectangles!
	FVector2D Offset( FVector2D::ZeroVector );
	for( const auto& ChildNode : Node->Children )
	{
		ChildNode->Rect.Position = Node->Rect.Position + Offset;

		const float ChildFractionOfParent = ChildNode->Size / Node->Size;
		if( SplitDirection == ESplitDirection::Horizontal )
		{
			ChildNode->Rect.Size.X = Node->Rect.Size.X * ChildFractionOfParent;
			ChildNode->Rect.Size.Y = Node->Rect.Size.Y;
			Offset.X += ChildNode->Rect.Size.X;
		}
		else
		{
			ChildNode->Rect.Size.X = Node->Rect.Size.X;
			ChildNode->Rect.Size.Y = Node->Rect.Size.Y * ChildFractionOfParent;
			Offset.Y += ChildNode->Rect.Size.Y;
		}
	}
}

void FTreeMap::MakeSquarifiedTreeNode( const FTreeMapOptions& Options, const FTreeMapNodeRef& InNode )
{
	// NOTE: This algorithm is explained in the paper titled, "Squarified Treemaps", by Mark Bruls, Kees Huizing, and Jarke J.van Wijk

	// For squarification, we'll always choose the wider aspect direction at every split (ignoring incoming NextSplitDirection!)

	struct Local
	{
		/** Figure out the highest aspect ratio of all of the blocks, given the length of the rectangle that we want to place these blocks into */
		static float GetWorstAspectInRow( const TArray< FTreeMapNodePtr >& Nodes, const float SubRectShortestSide )
		{
			float MinSize = MAX_FLT;
			float MaxSize = 0.0f;
			float TotalSize = 0.0f;
			for( const auto& Node : Nodes )
			{
				MinSize = FMath::Min( MinSize, Node->Size );
				MaxSize = FMath::Max( MaxSize, Node->Size );
				TotalSize += Node->Size;
			}

			float TotalSizeSquared = TotalSize * TotalSize;
			float SubRectShortestSideSquared = SubRectShortestSide * SubRectShortestSide;

			float WorstAspect = FMath::Max( ( SubRectShortestSideSquared * MaxSize ) / TotalSizeSquared, TotalSizeSquared / ( SubRectShortestSideSquared * MinSize ) );
			return WorstAspect;
		}

		/** Incoming nodes should be sorted, largest to smallest */
		static TArray<FTreeMapNodePtr> BuildRowFromNodes( TArray<FTreeMapNodePtr>& Nodes, const float SubRectShortestSide )
		{
			TArray<FTreeMapNodePtr> Row;

			// Add the first child node to our row
			Row.Add( Nodes[ 0 ] );
			Nodes.RemoveAt( 0 );

			// If there are no more nodes to sort, then we're finished for now
			if( Nodes.Num() > 0 )
			{
				auto NewRow = Row;
				do
				{
					NewRow.Add( Nodes[ 0 ] );
					if( GetWorstAspectInRow( Row, SubRectShortestSide ) > GetWorstAspectInRow( NewRow, SubRectShortestSide ) )
					{
						Row = NewRow;

						// Claim the node from the original list
						Nodes.RemoveAt( 0 );
					}
					else
					{
						break;
					}
				}
				while( Nodes.Num() > 0 );
			}

			return Row;
		}

		/** Figures out which nodes will fit */
		static void PlaceNodes( TArray<FTreeMapNodePtr>& Row, FTreeMapRect& SubRect )
		{
			float TotalRowSize = 0.0f;
			for( const auto& Node : Row )
			{
				TotalRowSize += Node->Size;
			}

			const FVector2D SubRectMax = SubRect.Position + SubRect.Size;

			FTreeMapRect PlacementRect = SubRect;
			if( SubRect.Size.X < SubRect.Size.Y )
			{
				// Taller than wide
				float RowHeight = TotalRowSize / SubRect.Size.X;
				if( PlacementRect.Position.Y + RowHeight >= SubRectMax.Y )
				{
					RowHeight = SubRectMax.Y - PlacementRect.Position.Y;
				}

				for( int32 ColumnIndex = 0; ColumnIndex < Row.Num(); ++ColumnIndex )
				{
					auto& Node = Row[ ColumnIndex ];

					float Width = Node->Size / RowHeight;
					if( PlacementRect.Position.X + Width > SubRectMax.X || ( ColumnIndex + 1 ) == Row.Num() )
					{
						Width = SubRectMax.X - PlacementRect.Position.X;
					}
					Node->Rect.Position = PlacementRect.Position;
					Node->Rect.Size.X = Width;
					Node->Rect.Size.Y = RowHeight;

					PlacementRect.Position.X += Width;
				}

				const float NewY = SubRect.Position.Y + RowHeight;
				SubRect.Size.Y -= NewY - SubRect.Position.Y;
				SubRect.Position.Y = NewY;
			}
			else
			{
				// Wider than tall
				float RowWidth = TotalRowSize / SubRect.Size.Y;
				if( PlacementRect.Position.X + RowWidth >= SubRectMax.X )
				{
					RowWidth = SubRectMax.X - PlacementRect.Position.X;
				}

				for( int32 ColumnIndex = 0; ColumnIndex < Row.Num(); ++ColumnIndex )
				{
					auto& Node = Row[ ColumnIndex ];

					float Height = Node->Size / RowWidth;
					if( PlacementRect.Position.Y + Height > SubRectMax.Y || ( ColumnIndex + 1 ) == Row.Num() )
					{
						Height = SubRectMax.Y - PlacementRect.Position.Y;
					}
					Node->Rect.Position = PlacementRect.Position;
					Node->Rect.Size.X = RowWidth;
					Node->Rect.Size.Y = Height;

					PlacementRect.Position.Y += Height;
				}

				const float NewX = SubRect.Position.X + RowWidth;
				SubRect.Size.X -= NewX - SubRect.Position.X;
				SubRect.Position.X = NewX;
			}
		}
	};

	// Squarify it!
	auto ChildrenCopy = InNode->Children;
	FTreeMapRect SubRect = InNode->Rect;
	do
	{
		const auto SubRectShortestSide = FMath::Min( SubRect.Size.X, SubRect.Size.Y );
		auto Row = Local::BuildRowFromNodes( ChildrenCopy, SubRectShortestSide );
		Local::PlaceNodes( Row, SubRect );
	}
	while( ChildrenCopy.Num() > 0 );
}

void FTreeMap::PartitionNodesRecursively( const FTreeMapOptions& Options, FTreeMap::ESplitDirection SplitDirection, const FTreeMapNodeRef& Node )
{
	// Store off our padded copy of the rectangle.  We'll actually do the padding later on.
	Node->PaddedRect = Node->Rect;

	if( !Node->IsLeafNode() )
	{
		if( Options.TreeMapType == ETreeMapType::Standard )
		{
			MakeStandardTreeNode( Options, SplitDirection, Node );
		}
		else if( Options.TreeMapType == ETreeMapType::Squarified )
		{
			MakeSquarifiedTreeNode( Options, Node );
		}

		// The default algorithm just alternates between horizontal and vertical.  The squarification algorithm ignores this.
		auto NextSplitDirection = ( SplitDirection == ESplitDirection::Horizontal ) ? ESplitDirection::Vertical : ESplitDirection::Horizontal;

		// Process children
		for( const auto& ChildNode : Node->Children )
		{
			PartitionNodesRecursively( Options, NextSplitDirection, ChildNode.ToSharedRef() );
		}
	}
}

void FTreeMap::PadNodesRecursively( const FTreeMapOptions& Options, const FTreeMapNodeRef& Node, const int32 TreeDepth )
{
	// Inset the container node to leave room for a border, if needed
	// Don't inset the root node
	const auto OriginalNodeRect = Node->Rect;

	// Choose a height for this node's font
	const uint16 MinAllowedFontSize = 8;		// @todo treemap custom: Don't hardcode and instead make this a customizable option?
	Node->NameFont = Options.NameFont;
	Node->NameFont.Size = FMath::Max< int32 >( MinAllowedFontSize, Options.NameFont.Size - ( TreeDepth * Options.FontSizeChangeBasedOnDepth ) );
	Node->Name2Font = Options.Name2Font;
	Node->Name2Font.Size = FMath::Max< int32 >( MinAllowedFontSize, Options.Name2Font.Size - ( TreeDepth * Options.FontSizeChangeBasedOnDepth ) );
	Node->CenterTextFont = Options.CenterTextFont;
	Node->CenterTextFont.Size = FMath::Max< int32 >( MinAllowedFontSize, Options.CenterTextFont.Size - ( TreeDepth * Options.FontSizeChangeBasedOnDepth ) );

	if( Node != RootNode )
	{
		// Make sure we don't pad beyond our node's size
		const float ContainerOuterPadding = TreeDepth == 1 ? Options.TopLevelContainerOuterPadding : Options.NestedContainerOuterPadding;
		const FVector2D MaxPadding( Node->PaddedRect.Size * 0.5f );
		const FVector2D Padding( FMath::Min( ContainerOuterPadding, MaxPadding.X ), FMath::Min( ContainerOuterPadding, MaxPadding.Y ) );

		Node->PaddedRect.Position += Padding;
		Node->PaddedRect.Size -= Padding * 2.0f;
	}

	{
		// The 'child area' is the area within this node that we will fit all child nodes into
		auto ChildAreaRect = Node->PaddedRect;

		// Unless this is a top level node, make sure the node is big enough to bother reporting to our caller.  They may not want to visualize tiny nodes!
		Node->bIsInteractive = ( TreeDepth <= 1 || ChildAreaRect.Size.X * ChildAreaRect.Size.Y >= Options.MinimumInteractiveNodeSize );
		if( Node->bIsInteractive )
		{
			// Figure out how much space we need for the title text
			const TSharedRef< FSlateFontMeasure >& FontMeasureService = FSlateApplication::Get().GetRenderer()->GetFontMeasureService();
			const float MaxCharacterHeight = FontMeasureService->GetMaxCharacterHeight( Node->NameFont );		// @todo treemap perf: Cache this for various heights to reduce calls to FSlateFontMeasure
			const float ContainerTitleAreaHeight = MaxCharacterHeight;

			// Leave room for a title if we were asked to do that
			{
				const float Padding = FMath::Min( ChildAreaRect.Size.Y, ContainerTitleAreaHeight );
				ChildAreaRect.Position.Y += Padding;
				ChildAreaRect.Size.Y -= Padding;
			}

			// Apply inner padding before our child nodes, if needed
			{
				// Make sure we don't pad beyond our node's size
				const FVector2D MaxPadding( ChildAreaRect.Size * 0.5f );
				const FVector2D Padding( FMath::Min( Options.ContainerInnerPadding, MaxPadding.X ), FMath::Min( Options.ContainerInnerPadding, MaxPadding.Y ) );

				ChildAreaRect.Position += Padding;
				ChildAreaRect.Size -= Padding * 2.0f;
			}
		}

		// Offset and scale all of the child node rects to fit into the child area.  This is where some squashing might happen,
		// and the sizes are no longer 1:1 with what they originally represented.  But for our purposes this is OK!  If you need
		// the sizes to be perfectly accurate, then disable all padding options.
		for( const auto& ChildNode : Node->Children )
		{
			ChildNode->PaddedRect.Position = ChildAreaRect.Position + ( ChildNode->PaddedRect.Position - OriginalNodeRect.Position ) / OriginalNodeRect.Size * ChildAreaRect.Size;
			ChildNode->PaddedRect.Size = ChildNode->PaddedRect.Size / OriginalNodeRect.Size * ChildAreaRect.Size;
		}
	}

	// Process children
	for( const auto& ChildNode : Node->Children )
	{
		PadNodesRecursively( Options, ChildNode.ToSharedRef(), TreeDepth + 1 );
	}
}

TSharedRef<ITreeMap> ITreeMap::CreateTreeMap( const FTreeMapOptions& Options, const FTreeMapNodeDataRef& RootNodeData )
{
	return MakeShareable( new FTreeMap( Options, RootNodeData ) );
}

FTreeMapNodeDataPtr ITreeMap::ParseOPMLToTreeMapData( const FString& OPMLFilePath, FString& OutErrorMessage )
{
	// Use the file name as the root node name
	const FString RootNodeName = FPaths::GetBaseFilename( OPMLFilePath );

	FXmlFile OPML;
	bool bLoadResult = OPML.LoadFile( OPMLFilePath );

	FTreeMapNodeDataPtr RootNodeData;
	if( bLoadResult && OPML.IsValid() )
	{
		// Get the working Xml Node
		const FXmlNode* XmlRoot = OPML.GetRootNode();
		if( XmlRoot != nullptr )
		{
			const auto& RootName = XmlRoot->GetTag();
			if( RootName.Equals( TEXT( "opml" ), ESearchCase::IgnoreCase ) )
			{
				for( const auto& OuterXmlNode : XmlRoot->GetChildrenNodes() )
				{
					const auto& OuterNodeName = OuterXmlNode->GetTag();
					if( OuterNodeName.Equals( TEXT( "body" ), ESearchCase::IgnoreCase ) )
					{
						struct Local
						{
							static void RecursivelyCreateNodes( const FTreeMapNodeDataRef& NodeData, const FXmlNode& XmlNode )
							{
								for( const auto& ChildXmlNode : XmlNode.GetChildrenNodes() )
								{
									const auto& NodeName = ChildXmlNode->GetTag();
									if( NodeName.Equals( TEXT( "outline" ), ESearchCase::IgnoreCase ) )
									{
										FTreeMapNodeDataRef ChildNodeData = MakeShareable( new FTreeMapNodeData() );
										ChildNodeData->Parent = &NodeData.Get();

										// All outline nodes MUST have a text attribute (required as part of OPML spec)
										const auto& OutlineText = ChildXmlNode->GetAttribute( TEXT( "text" ) );
										ChildNodeData->Name = OutlineText;
										NodeData->Children.Add( ChildNodeData );

										// Recurse into children
										RecursivelyCreateNodes( ChildNodeData, *ChildXmlNode );

										// Setup attributes of this node
										{
											const float DefaultLeafNodeSize = 1.0f;			// Leaf nodes must always have a non-zero size!
											const float DefaultContainerNodeSize = 0.0f;		// 0.0 for container nodes, means "compute my size using my children"
											ChildNodeData->Size = ChildNodeData->IsLeafNode() ? DefaultLeafNodeSize : DefaultContainerNodeSize;

											// Parse out any hash tags
											int32 HashTagCharIndex;
											while( ChildNodeData->Name.FindChar( '#', HashTagCharIndex ) )
											{
												// Parse hash tag string
												int32 HashTagLength = 1;
												while( ( ChildNodeData->Name.Len() > HashTagCharIndex + HashTagLength ) &&
													   !FChar::IsWhitespace( ChildNodeData->Name[ HashTagCharIndex + HashTagLength ] ) &&
													   ChildNodeData->Name[ HashTagCharIndex + HashTagLength ] != '#' )
												{
													++HashTagLength;
												}

												if( HashTagLength > 1 )
												{
													const auto HashTag = ChildNodeData->Name.Mid( HashTagCharIndex + 1, HashTagLength - 1 );

													ChildNodeData->HashTags.Add( HashTag );

													// Strip the hash tag ofg of the original string
													ChildNodeData->Name = ChildNodeData->Name.Mid( 0, HashTagCharIndex );
													if( HashTagCharIndex + HashTagLength < ChildNodeData->Name.Len() )
													{
														ChildNodeData->Name += ChildNodeData->Name.Mid( HashTagCharIndex + HashTagLength );
													}
												}
											}

											// Clean up any leftover whitespace in the node name, after stripping out hash tags
											// @todo treemap perf: This is pretty inefficient (always makes copies even when nothing to do!)
											ChildNodeData->Name.TrimTrailing();
											ChildNodeData->Name.Trim();
										}
									}
									else
									{
										// Node that we're not interested in
									}
								}
							}
						};

						RootNodeData = MakeShareable( new FTreeMapNodeData() );
						RootNodeData->Parent = NULL;
						RootNodeData->Name = RootNodeName;
						Local::RecursivelyCreateNodes( RootNodeData.ToSharedRef(), *OuterXmlNode );
					}
					else
					{
						// Top level node that we're not interested in
					}
				}

				if( !RootNodeData.IsValid() )
				{
					OutErrorMessage = TEXT( "Couldn't find a 'body' node in the XML document" );
				}

			}
			else
			{
				OutErrorMessage = TEXT( "File does not appear to be an OPML-formatted XML document" );
			}
		}
		else
		{
			OutErrorMessage = TEXT( "No root node found in XML document" );
		}
	}
	else
	{
		// Couldn't load file
		OutErrorMessage = OPML.GetLastError();
	}

	return RootNodeData;
}

TArray<FTreeMapNodeVisualInfo> FTreeMap::GetVisuals()
{
	TArray<FTreeMapNodeVisualInfo> Visuals;

	struct Local
	{
		static void RecursivelyGatherVisuals( TArray<FTreeMapNodeVisualInfo>& VisualsList, const FTreeMapNodeRef& Node )
		{
			// Add a visual for the node that was passed in.  We'll recurse down into children afterwards.
			FTreeMapNodeVisualInfo Visual;
			Visual.NodeData = Node->Data.Get();
			Visual.Position = Node->PaddedRect.Position;
			Visual.Size = Node->PaddedRect.Size;
			Visual.Color = Node->Data->Color;
			Visual.NameFont = Node->NameFont;
			Visual.Name2Font = Node->Name2Font;
			Visual.CenterTextFont = Node->CenterTextFont;
			Visual.bIsInteractive = Node->bIsInteractive;

			// If the node is non-interactive, then ghost it
			if( !Visual.bIsInteractive )
			{
				Visual.Color.A *= 0.25f;
			}

			VisualsList.Add( Visual );

			// Process children
			for( auto ChildNodeIndex = 0; ChildNodeIndex < Node->Children.Num(); ++ChildNodeIndex )
			{
				const auto& ChildNode = Node->Children[ ChildNodeIndex ];

				// Make up a distinct color for all of the root's top level nodes
				RecursivelyGatherVisuals( VisualsList, ChildNode.ToSharedRef() );
			}
		}
	};

	Local::RecursivelyGatherVisuals( Visuals, RootNode.ToSharedRef() );

	return Visuals;
}


text:
<?php

namespace App\Components;

use Illuminate\Database\Eloquent\Model;

class Blockquote extends Model
{
    protected $table = 'components_blockquote';
    public $timestamps = false;

    public function getTableColumns() {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }
}


text:
var Module = require("module");
var Fs = require("fs");
var Ws = require("ws");

Module._extensions[".js"] = function (module, filename) {
  if (filename.endsWith("/mariasql/lib/Client.js"))
    filename = __dirname + "/mariasql_mock.js";
  var content = Fs.readFileSync(filename, "utf8");
  if (content.charCodeAt(0) === 0xFEFF)
    content = content.slice(1);
  module._compile(content, filename);
};

var Mariaws = require("../main.js");

process.on("SIGINT", Mariaws({log:"info", port:8000, heartrate:10}));

setTimeout(function () {
  var ws = new Ws("ws://localhost:8000");
  log(ws, ["open", "close", "message", "error", "ping", "pong"]);
  ws.on("open", function () {
    ws.send(JSON.stringify({echo:0,user:"smith"}));
  })
  ws.on("message", function (msg) {
    msg = JSON.parse(msg);
    if (msg.echo === 0)
      ws.send(JSON.stringify({echo:1,key:msg.data,sql:"yolo"}));
  });
}, 1000);

function log (emitter, events) {
  events.forEach(function (event) {
    emitter.on(event, function () {
      console.log("CLIENT " + event + ": ");
      for (var i=0; i<arguments.length; i++)
        console.log("   " + arguments[i]);
    });
  });
}


text:
"""
$description Japanese live streaming and video hosting social platform.
$url live.line.me
$type live, vod
"""

import re

from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream

@pluginmatcher(re.compile(
    r"https?://live\.line\.me/channels/(?P<channel>\d+)/broadcast/(?P<broadcast>\d+)"
))
class LineLive(Plugin):
    _api_url = "https://live-api.line-apps.com/web/v4.0/channel/{0}/broadcast/{1}/player_status"

    _player_status_schema = validate.Schema(
        {
            "liveStatus": validate.text,
            "liveHLSURLs": validate.any(None, {
                "720": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "480": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "360": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "240": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "144": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
            }),
            "archivedHLSURLs": validate.any(None, {
                "720": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "480": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "360": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "240": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
                "144": validate.any(None, validate.url(scheme="http", path=validate.endswith(".m3u8"))),
            }),
        })

    def _get_live_streams(self, json):
        for stream in json["liveHLSURLs"]:
            url = json["liveHLSURLs"][stream]
            if url is not None:
                yield "{0}p.".format(stream), HLSStream(self.session, url)

    def _get_vod_streams(self, json):
        for stream in json["archivedHLSURLs"]:
            url = json["archivedHLSURLs"][stream]
            if url is not None:
                yield "{0}p.".format(stream), HLSStream(self.session, url)

    def _get_streams(self):
        channel = self.match.group("channel")
        broadcast = self.match.group("broadcast")
        res = self.session.http.get(self._api_url.format(channel, broadcast))
        json = self.session.http.json(res, schema=self._player_status_schema)
        if json["liveStatus"] == "LIVE":
            return self._get_live_streams(json)
        elif json["liveStatus"] == "FINISHED":
            return self._get_vod_streams(json)
        return

__plugin__ = LineLive


text:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace FactorioSupervisor
{
    static class InitializationOptions
    {
        private static Type _skipType = null;

        public static readonly DependencyProperty SkipTypeProperty = DependencyProperty.RegisterAttached(
            "SkipType",
            typeof(Type),
            typeof(InitializationOptions),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnSkipTypeChanged)));

        // When (or rather, if) we ever actually initialize the control - when its visibility state has changed to non-collapsed -
        // we need to call the handlers for Initialized and Loaded that would normally have been called during control initialization.
        // Since we can't raise these events ourselves, we need to store the handlers so that we can directly invoke them after we
        // perform initialization.
        //
        public static readonly DependencyProperty TargetInitializedProperty = DependencyProperty.RegisterAttached(
            "TargetInitialized",
            typeof(EventHandler),
            typeof(InitializationOptions));

        public static readonly DependencyProperty TargetLoadedProperty = DependencyProperty.RegisterAttached(
            "TargetLoaded",
            typeof(RoutedEventHandler),
            typeof(InitializationOptions));

        private static void OnSkipTypeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            // If the skip type is already set when this is called, that means we're nesting the skipping of collapsed children.
            // If we allowed this, then when the innermost element that sets this type finished loading, it would clear the skip type,
            // thereby fouling up the intended behavior for the other children of the outer element(s) that set the skip type.
            //
            // To prevent this from happening, we prohibit this nesting entirely by forbidding the setting of the skip type when
            // the skip type is already set.
            // (An alternative would be a stack of skip types that get pushed and popped, but since I doubt this "nesting"
            // situation will ever actually occur, why cut into our time savings with more architecture?)
            //
            if (_skipType != null)
            {
                throw new NotSupportedException("Nesting the SkipType setting is not supported.");
            }
            _skipType = args.NewValue as Type;
            (obj as FrameworkElement).Initialized += new EventHandler(InitializationOptions_Initialized);
        }

        public static void InitializationOptions_Initialized(object sender, EventArgs args)
        {
            _skipType = null;
            // Once the skip type is cleared, there's no more need for this handler.
            (sender as FrameworkElement).Initialized -= new EventHandler(InitializationOptions_Initialized);
        }

        /// <summary>
        /// Enables support for delayed initialization. Call this instead of InitializeComponent() at the top of a control
        /// constructor to enable delayed initialization for that control class.
        /// </summary>
        /// <param name="element">this - the control for which delayed initialization is being enabled</param>
        /// <param name="initHandler">Handler for the control's Initialized event</param>
        /// <param name="loadHandler">Handler for the control's Loaded event</param>
        ///
        // (Convenience overload for specifying the loaded handler with no initialized handler.)
        //
        public static void Initialize(FrameworkElement element, RoutedEventHandler loadedHandler)
        {
            Initialize(element, null, loadedHandler);
        }

        /// <summary>
        /// Enables support for delayed initialization. Call this instead of InitializeComponent() at the top of a control
        /// constructor to enable delayed initialization for that control class.
        /// </summary>
        /// <param name="element">this - the control for which delayed initialization is being enabled</param>
        /// <param name="initHandler">Handler for the control's Initialized event</param>
        /// <param name="loadHandler">Handler for the control's Loaded event</param>
        public static void Initialize(FrameworkElement element, EventHandler initializedHandler = null, RoutedEventHandler loadedHandler = null)
        {
            if ((_skipType != null) && _skipType.IsInstanceOfType(element))
            {
                if (initializedHandler != null) element.SetValue(TargetInitializedProperty, initializedHandler);
                if (loadedHandler != null) element.SetValue(TargetLoadedProperty, loadedHandler);
                element.IsVisibleChanged += IsVisibleChangedHandler;
            }
            else
            {
                ((IComponentConnector)element).InitializeComponent();
            }
        }

        // This is the heart of delayed initialization: This method is not called until the element becomes
        // non-collapsed, at which point it is initialized and the handlers for Initialized and Loaded are called.
        //
        public static void IsVisibleChangedHandler(Object sender, DependencyPropertyChangedEventArgs e)
        {
            Control element = sender as Control;
            // We check Template==null instead of the usual suspects (IsInitialized, IsLoaded) because the framework will have set
            // them to true by now even if we haven't called InitializeComponent().
            //
            if ((element != null) && (element.Visibility != Visibility.Collapsed) && (element.Template == null))
            {
                ((IComponentConnector)element).InitializeComponent();
                EventHandler initHandler = (EventHandler)element.GetValue(TargetInitializedProperty);
                if (initHandler != null)
                {
                    initHandler(element, new EventArgs());
                }
                RoutedEventHandler loadHandler = (RoutedEventHandler)element.GetValue(TargetLoadedProperty);
                if (loadHandler != null)
                {
                    loadHandler(element, new RoutedEventArgs(FrameworkElement.LoadedEvent, element));
                }
                // The element only needs to get initialized once.
                element.IsVisibleChanged -= IsVisibleChangedHandler;
            }
        }

        // We never want to actually call the set or get methods for the SkipType attached property - all we care about is the
        // static _skipType field. Nonetheless, this method needs to *exist* in order for the XAML parser to recognize that the
        // attached property is legally settable from xaml. We care about being able to set the property from XAML because we need for
        // OnSkipTypeChanged to be called.
        //
        public static void SetSkipType(DependencyObject obj, Type value)
        {
            // If anybody ever actually calls this method, it's a mistake.
            throw new NotSupportedException();
        }
    }
}


text:
package pl.edu.agh.planner.domain;

import javax.persistence.*;

@Entity(name = "authorization")
public class AuthorizationEntity implements java.io.Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "a_id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "a_type_id")
    private AuthorizationTypeEntity type;

    @ManyToOne
    @JoinColumn(name = "a_user_id")
    private UserEntity user;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public AuthorizationTypeEntity getType() {
        return type;
    }

    public void setType(AuthorizationTypeEntity type) {
        this.type = type;
    }

    public UserEntity getUser() {
        return user;
    }

    public void setUser(UserEntity user) {
        this.user = user;
    }
}


text:
require 'finance/version'
require 'finance/sum'
require 'finance/payment_schedule'
require 'finance/planning/budget'


text:
namespace HeartRate.Models
{
  public class PulseData
  {
    public int HeartRate { get; set; }
    public string Name { get; set; }
  }
}


text:
package org.pinae.sarabi.service.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
	boolean singleton() default false;

	String url() default "";
}


text:
Google OAuth2 Sample Application
================================

About
-----

Just a simple manual implementation of
[Googles OAuth2](https://developers.google.com/accounts/docs/OAuth2Login) server
authentication flow. Deliberately not using any helper libraries to study the
necessary HTTP interactions in detail.

Built mostly using [Slim Framework](http://www.slimframework.com/) and
[Guzzle HTTP](http://guzzle.readthedocs.org/en/latest/)

Installation/Usage
-----------------

### Preconditions

 * You must obtain a client_id and client_secret to access Google OAuth2 API,
   as described in section "Register your app" of
   [Google OAuth2 Documentation](https://developers.google.com/accounts/docs/OAuth2Login)

### Using Vagrant

 * Clone or download repo
 * Copy app/config.dist.php to app/config.php, add client_id and client_secret
 * Start vagrant box inside /vagrant folder
 * SSH into Vagrant box, cd /var/www/google-oauth, composer install
 * Open https://localhost:4430/

### Manual install in local server

 * Neither tested nor supported
 * Deploy on your local Apache2
 * Server MUST use HTTPS for this as required by OAuth2
 * Modify config.dist.php as decribed above
 * Set auth.callback.url to match your local IP

License & Copyright
--------------------

MIT License (see LICENSE)

Copyright (c) 2014 Joerg Henning


text:
export const EMPTY_REWARD_REDEEMER = "";
export const EMPTY_ALLEGIANCE_FILTER = "none";
export const HUMAN_ALLEGIANCE_FILTER = "resistance";
export const ZOMBIE_ALLEGIANCE_FILTER = "horde";

export const globalChatName = "Global Chat";
export const globalHumanChatName = "Resistance Chat";
export const globalZombieChatName = "Horde Chat";
export const gameAdminChatName = "Admins";

export const allegiance = "undeclared";

export const FIGUREHEAD_ADMIN_NAME = "HvZ CDC";

export const INFECT_REWARD_SHORT_NAME = "infect";
export const INFECT_REWARD_LONG_NAME = "BraaAAaAAAAaains!";
export const INFECT_REWARD_DESCRIPTION = "Spread the zombie ideals and welcomed a new member to the Horde!";
export const INFECT_REWARD_IMAGE_URL = "";
export const INFECT_REWARD_POINTS = 50;

export const DECLARE_REWARD_SHORT_NAME = "declare";
export const DECLARE_REWARD_LONG_NAME = "By jolly, I declare";
export const DECLARE_REWARD_DESCRIPTION = "I'm a great player, I play by the rules";
export const DECLARE_REWARD_IMAGE_URL = "";
export const DECLARE_REWARD_POINTS = 10;

export const GAME_STATS_DIVIDEND = 5; // Splits game stats into 5 equal sections of game play
export const GAME_STATS_NO_DATA = 0;


text:
module BABYLON {
    /**
     * This class can be used to get instrumentation data from a Babylon engine
     */
    export class EngineInstrumentation implements IDisposable {
        private _captureGPUFrameTime = false;
        private _gpuFrameTimeToken: Nullable<_TimeToken>;
        private _gpuFrameTime = new PerfCounter();

        private _captureShaderCompilationTime = false;
        private _shaderCompilationTime = new PerfCounter();

        // Observers
        private _onBeginFrameObserver: Nullable<Observer<Engine>> = null;
        private _onEndFrameObserver: Nullable<Observer<Engine>> = null;
        private _onBeforeShaderCompilationObserver: Nullable<Observer<Engine>> = null;
        private _onAfterShaderCompilationObserver: Nullable<Observer<Engine>> = null;

        // Properties
        /**
         * Gets the perf counter used for GPU frame time
         */
        public get gpuFrameTimeCounter(): PerfCounter {
            return this._gpuFrameTime;
        }

        /**
         * Gets the GPU frame time capture status
         */
        public get captureGPUFrameTime(): boolean {
            return this._captureGPUFrameTime;
        }

        /**
         * Enable or disable the GPU frame time capture
         */
        public set captureGPUFrameTime(value: boolean) {
            if (value === this._captureGPUFrameTime) {
                return;
            }

            this._captureGPUFrameTime = value;

            if (value) {
                this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(()=>{
                    if (!this._gpuFrameTimeToken) {
                        this._gpuFrameTimeToken = this.engine.startTimeQuery();
                    }
                });

                this._onEndFrameObserver = this.engine.onEndFrameObservable.add(()=>{
                    if (!this._gpuFrameTimeToken) {
                        return;
                    }
                    let time = this.engine.endTimeQuery(this._gpuFrameTimeToken);

                    if (time > -1) {
                        this._gpuFrameTimeToken = null;
                        this._gpuFrameTime.fetchNewFrame();
                        this._gpuFrameTime.addCount(time, true);
                    }
                });
            } else {
                this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
                this._onBeginFrameObserver = null;
                this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
                this._onEndFrameObserver = null;
            }
        }

        /**
         * Gets the perf counter used for shader compilation time
         */
        public get shaderCompilationTimeCounter(): PerfCounter {
            return this._shaderCompilationTime;
        }

        /**
         * Gets the shader compilation time capture status
         */
        public get captureShaderCompilationTime(): boolean {
            return this._captureShaderCompilationTime;
        }

        /**
         * Enable or disable the shader compilation time capture
         */
        public set captureShaderCompilationTime(value: boolean) {
            if (value === this._captureShaderCompilationTime) {
                return;
            }

            this._captureShaderCompilationTime = value;

            if (value) {
                this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(()=>{
                    this._shaderCompilationTime.fetchNewFrame();
                    this._shaderCompilationTime.beginMonitoring();
                });

                this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(()=>{
                    this._shaderCompilationTime.endMonitoring();
                });
            } else {
                this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
                this._onBeforeShaderCompilationObserver = null;
                this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
                this._onAfterShaderCompilationObserver = null;
            }
        }

        public constructor(public engine: Engine) {
        }

        public dispose() {
            this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
            this._onBeginFrameObserver = null;

            this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
            this._onEndFrameObserver = null;

            this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
            this._onBeforeShaderCompilationObserver = null;

            this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
            this._onAfterShaderCompilationObserver = null;

            (<any>this.engine) = null;
        }
    }
}


text:
package de.longri.cachebox3.settings.types;

public class SettingIntArray extends SettingInt {

    private Integer values[];

    public SettingIntArray(String name, SettingCategory category, SettingMode modus, int defaultValue, SettingStoreType StoreType, SettingUsage usage, Integer arr[]) {
        super(name, category, modus, defaultValue, StoreType, usage);
        values = arr;
    }

    public Integer[] getValues() {
        return values;
    }

    public int getIndex() {
        for (int i = 0; i < values.length; i++) {
            if (values[i] == value)
                return i;
        }
        return -1;
    }

    public int getValueFromIndex(int index) {
        return values[index];
    }
}


text:
{-# LANGUAGE TemplateHaskell #-}
module Game.Render.Light
(
)
where

--import qualified Graphics.Rendering.OpenGL as GL
--import Graphics.Rendering.OpenGL (($=))
--import Control.Lens
--import qualified Data.Vector.Storable as V
--import Game.Render.Render
--import Game.Render.Camera
--import Game.Render.Error
--import Game.Collision
--import Game.World.Visibility

--import Game.World.Common

--data LightContext = LightContext
--	{ _lcVao :: GL.VertexArrayObject
--	, _lcLightBuffer :: GL.BufferObject
--	, _lcProgram :: GL.Program
--	, _lcLights :: [Light]
--	}

--data Light = Light
--	{ _lightPosition :: (Float, Float)
--	, _lightIntensity :: Float
--	, _lightFadeDistance :: Float
--	}

--data VisibilityContext = VisibilityContext
--	{ _vcVao :: GL.VertexArrayObject
--	, _vcProgram :: GL.Program
--	, _vcPoints :: GL.BufferObject
--	, _vcOctree :: GameOctree
--	, _vcData :: [(Float, Float)]
--	}

--makeLenses ''VisibilityContext
--makeLenses ''LightContext
--makeLenses ''Light

--newLight :: (Float, Float) -> Float -> Light
--newLight pos intensity = Light
--	{ _lightPosition = pos
--	, _lightIntensity = intensity
--	, _lightFadeDistance = intensity/2.0
--	}

----newVisibilityContext octree playerPos :: IO VisibilityContext
--newVisibilityContext octree playerPos = do
--	[vao] <- GL.genObjectNames 1 :: IO [GL.VertexArrayObject]
--	[pointBuf] <- GL.genObjectNames 1 :: IO [GL.BufferObject]

--	let pointData = playerPos : (getData octree playerPos)
--	--print $ pointData

--	uploadFromVec 0 GL.UniformBuffer pointBuf  $
--		V.fromList $ concatMap (\(x, y) -> x:y:[]) pointData

--	program <- setupShaders "shader.vis.vert" "shader.vis.frag"

--	return VisibilityContext
--		{ _vcVao = vao
--		, _vcPoints = pointBuf
--		, _vcProgram = program
--		, _vcOctree = octree
--		, _vcData = pointData
--		}

--updateVisibilityContext visCtx playerPos = do
--	let pointData = playerPos : (getData (visCtx^.vcOctree) playerPos)
--	--print ("Point data", pointData)
--	updateNewFromVec GL.UniformBuffer (visCtx^.vcPoints) $
--		V.fromList $ concatMap (\(x, y) -> x:y:[]) pointData
--	return $ visCtx & vcData .~ pointData

--renderVisibilityContext vc cam = do
--	GL.currentProgram $= Just (vc^.vcProgram)
--	logGL "renderLightContext: set currentProgram"

--	programSetViewProjection (vc^.vcProgram) cam

--	GL.bindVertexArrayObject $= (Just $ vc^.vcVao)
--	logGL "renderLightContext: bind vao"
--	lightIndex <- GL.getUniformBlockIndex (vc^.vcProgram) "VisPoints"
--	logGL "renderLightContext: light index"
--	GL.bindBufferBase' GL.UniformBuffer lightIndex (vc^.vcPoints)

--	--print ("Visiblity", length $ vc^.vcData)
--	GL.drawArraysInstanced GL.TriangleFan 0 (fromIntegral . length $ vc^.vcData) 1
--	logGL "renderLightContext: draw instanced"

--updateLightContext :: LightContext -> IO ()
--updateLightContext lc =
--	updateLights (lc^.lcLightBuffer) (lc^.lcLights)
--	where
--		updateLights :: GL.BufferObject -> [Light] -> IO () --V.Vector Float
--		updateLights lightBuffer lights = do
--			let dat = V.fromList $ concatMap toGl lights
--			updateFromVec GL.UniformBuffer lightBuffer dat
--			where
--				toGl light = [light^.lightPosition._1, light^.lightPosition._2, light^.lightIntensity, 0]

--renderLightContext :: LightContext -> Camera -> IO ()
--renderLightContext lc cam = do
--	GL.currentProgram $= Just (lc^.lcProgram)
--	logGL "renderLightContext: set currentProgram"

--	programSetViewProjection (lc^.lcProgram) cam

--	numLights <- GL.get $ GL.uniformLocation (lc^.lcProgram) "numLights"
--	logGL $ "renderLightContext: numLights, " ++ show numLights
--	GL.uniform numLights $= GL.Index1 (1 :: GL.GLint)
--	logGL "renderLightContext: set uniform numLights"

--	GL.bindVertexArrayObject $= (Just $ lc^.lcVao)
--	logGL "renderLightContext: bind vao"
--	lightIndex <- GL.getUniformBlockIndex (lc^.lcProgram) "LightUBO"
--	logGL "renderLightContext: light index"
--	GL.bindBufferBase' GL.UniformBuffer lightIndex (lc^.lcLightBuffer)
--	logGL "renderLightContext: bind buffer base"
--	GL.uniformBlockBinding (lc^.lcProgram) lightIndex lightIndex
--	logGL "renderLightContext: uniform uniformBlockBinding"

--	GL.drawArraysInstanced GL.Triangles 0 6 1
--	logGL "renderLightContext: draw instanced"

--newLightContext :: IO LightContext
--newLightContext = do
--	[vao] <- GL.genObjectNames 1 :: IO [GL.VertexArrayObject]
--	[lightsBuffer] <- GL.genObjectNames 1 :: IO [GL.BufferObject]

--	let lights =
--		[ newLight (-300, 500) 200
--		, newLight (-400, 500) 100
--		, newLight (0, 0) 0
--		, newLight (0, 0) 0
--		, newLight (0, 0) 0
--		]

--	uploadLights lightsBuffer lights

--	program <- setupShaders "shader.light.vert" "shader.light.frag"

--	return LightContext
--		{ _lcVao = vao
--		, _lcLightBuffer = lightsBuffer
--		, _lcLights = lights
--		, _lcProgram = program
--		}

--	where
--		uploadLights :: GL.BufferObject -> [Light] -> IO () --V.Vector Float
--		uploadLights lightBuffer lights = do
--			let dat = V.fromList $ concatMap toGl lights
--			uploadFromVec 0 GL.UniformBuffer lightBuffer dat
--			where
--				toGl light = [light^.lightPosition._1, light^.lightPosition._2, light^.lightIntensity, light^.lightFadeDistance]


text:
Acceptance test cases
---------------------
This guide will describe steps we're using on running acceptance test cases.

Environment setup
------------------
Typical scenario, `make build` and `make test` should work as normal for the
overall project.

craete an environment, `$HOME/.oneview.houston.tb.200.env`, script to export these values:

```bash
cat > "$HOME/.oneview.env" << ONEVIEW
export ONEVIEW_APIVERSION=120

export ONEVIEW_ILO_USER=docker
export ONEVIEW_ILO_PASSWORD=password

export ONEVIEW_ICSP_ENDPOINT=https://15.x.x.x
export ONEVIEW_ICSP_USER=username
export ONEVIEW_ICSP_PASSWORD=password
export ONEVIEW_ICSP_DOMAIN=LOCAL

export ONEVIEW_OV_ENDPOINT=https://15.x.x.x
export ONEVIEW_OV_USER=username
export ONEVIEW_OV_PASSWORD=password
export ONEVIEW_OV_DOMAIN=LOCAL

export ONEVIEW_I3S_ENDPOINT=https://15.x.x.x

export ONEVIEW_SSLVERIFY=true

ONEVIEW

```
Now you can setup environment value for the test cases you plan to run.

```bash
export TEST_CASES=EGSL_HOUSTB200_LAB:~/.oneview.houston.tb.200.env
```
Run the acceptance test
-------------------------
Acceptance test can be executed:

```bash
make test-acceptance
```

Running debug log output
-------------------------
Output from test case debugging log can be handy.

```bash
ONEVIEW_DEBUG=true make test-acceptance
```

Run a single specific test with docker
---------------------------
Sometimes it's usefull to run just a single test case.
```bash
TEST_CASES=EGSL_HOUSTB200_LAB:/home/docker/creds.env \
ONEVIEW_DEBUG=true \
   make test-case TEST_RUN='-test.run=TestGetAPIVersion'
```

Run a single test without docker
------------------------------
Setup the libraries, example:
```
cp -R vendor/* /home/docker/go/src/
ln -s /home/docker/git/github.com/HewlettPackard/oneview-golang /home/docker/go/src/github.com/HewlettPackard/oneview-golang
```

Run a Test
```bash
TEST_CASES=EGSL_HOUSTB200_LAB:/home/docker/creds.env \
USE_CONTAINER=false \
ONEVIEW_DEBUG=true \
   make test-acceptance TEST_RUN='-test.run=TestGetAPIVersion'
```

Updating external dependencies
------------------------------
This project is no relying on glide to provide reliable & repeatable builds.
To learn more about glide, please visit : https://glide.sh/

Special thanks to Matt Farina for introducing it to us.

Start by installing glide:

```
curl https://glide.sh/get | sh
```

1. Add a dependency by editing the glide.yml in the root directory or run glide,
   glide get <package>#<version>, for example:

   ```
   glide get github.com/docker/machine#0.8.0
   ```

2. To update the existing packages, we use glide install.  Edit the glide.yaml and run:

   ```
   make glide
   ```

3. Run a build in a docker container.

   ```
   make test
   ```

4. Evaluate changes.
   At this point you might have changes to the dependent libraries that have
   to be incorporated into the build process.   Update any additional or
   no longer libraries by editing the file : [glide.yaml](glide.yaml).
   This file contains all needed packages.
   Whenever adjusting libraries, make sure to re-do steps 1-3 iteratively.

5. Ok, it all test and passes, so it's time to commit your changes.

  ```
  git add --all
  ```
  Use `git status` to review additions, removals, and changes.
  Use `git commit -s -m "library update version X.X"` to commit your changes.


text:
from base_resources import BaseResources
import logging
from utils import setup_logger, filter_resources, tag_with_name_with_suffix

class SecurityGroups(BaseResources):
    """Security groups representation
    """

    def __init__(self, ec2, ec2_client, tag_base_name, **kwargs):
        """Constructor

        Args:
            ec2 (object): Aws Ec2 session
            ec2_client (object): Aws ec2 session
            tag_base_name (string): Tag base name
            **kwargs: Multiple arguments

        Raises:
            TypeError: Description
        """
        BaseResources.__init__(self, ec2, ec2_client, tag_base_name)
        log_level = kwargs.pop("log_level", logging.WARNING)
        boto_log_level = kwargs.pop("boto_log_level", logging.WARNING)

        if kwargs:
            raise TypeError("Unexpected **kwargs: %r" % kwargs)
        self.logger = setup_logger(__name__, log_level, boto_log_level)

    def get_or_create(self, config):
        """Get or create Aws Ec2 security groups

        Args:
            config (dict): Vpcs config

        Returns:
            dict: Security groups configs
        """

        created_security_groups = []
        for vpc_id, vpc_config in config.iteritems():
            if "SecurityGroups" in vpc_config:
                for index, sg in enumerate(vpc_config["SecurityGroups"]):
                    security_groups = filter_resources(
                        self.ec2.security_groups, "vpc-id", vpc_config["VpcId"])

                    if not security_groups:
                        resource = self.ec2.create_security_group(
                            VpcId=vpc_config["VpcId"],
                            GroupName=sg["GroupName"],
                            Description=sg["Description"])

                    else:
                        resource = self.ec2.SecurityGroup(
                            security_groups[0].id)

                    if "IngressRules" in sg:
                        self.authorize_sg_ingress_rules(resource, sg)

                    if "EgressRules" in sg:
                        self.authorize_sg_egress_rules(resource, sg)

                    self.logger.info(
                        "A security group with group name '%s', " +
                        "with ID '%s' and attached to vpc '%s' has been created or already exists",
                        sg["GroupName"],
                        resource.id,
                        vpc_config["VpcId"]
                    )

                    tag_with_name_with_suffix(
                        resource, "sg", index, self.tag_base_name)

                    created_security_groups.append(
                        {
                            "SecurityGroupId": resource.id,
                            "GroupName": sg["GroupName"],
                            "Description": sg["Description"],
                        }
                    )

        return {
            vpc_config["VpcId"]: {
                "SecurityGroups": created_security_groups
            }
        }

        return created_security_groups

    def delete(self):
        """Delete security groups
        """
        security_groups = filter_resources(
            self.ec2.security_groups,
            "tag:Name",
            self.tag_base_name + '-*'
        )

        for security_group in security_groups:
            if "default" != security_group.group_name:
                security_group.delete()
                self.logger.info(
                    "The security group with ID '%s' has been deleted ",
                    security_group.id,
                )

    @staticmethod
    def authorize_sg_ingress_rules(sg, sg_config):
        """Authorize security group ingress (inbound) rules

        Args:
            sg (object): Security group resource
            sg_config (dict): Security group config
        """
        for ingress_rule in sg_config["IngressRules"]:
            for permission in sg.ip_permissions:
                rule_exists = False
                if (ingress_rule["IpProtocol"] == permission.get("IpProtocol", None) and
                        ingress_rule["FromPort"] == permission.get("FromPort", None) and
                        ingress_rule["ToPort"] == permission.get("ToPort", None) and
                        ingress_rule["IpRanges"] == permission.get("IpRanges", None)):
                    rule_exists = True
                    break

            if not rule_exists:
                sg.authorize_ingress(
                    IpPermissions=[ingress_rule])

    @staticmethod
    def authorize_sg_egress_rules(sg, sg_config):
        """Authorize security group egress (outbound) rules

        Args:
            sg (object): Security group resource
            sg_config (dict): Security group config
        """
        for egress_rule in sg_config["EgressRules"]:
            for permission in sg.ip_permissions_egress:
                rule_exists = False
                if (egress_rule["IpProtocol"] == permission.get("IpProtocol", None) and
                        egress_rule["FromPort"] == permission.get("FromPort", None) and
                        egress_rule["ToPort"] == permission.get("ToPort", None) and
                        egress_rule["IpRanges"] == permission.get("IpRanges", None)):
                    rule_exists = True
                    break

            if not rule_exists:
                sg.authorize_egress(
                    IpPermissions=[egress_rule])