text:
package org.apache.sis.internal.system;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.sis.util.logging.Logging;
import org.apache.sis.util.resources.Messages;

// Branch-dependent imports
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.InvalidPathException;

/**
 * Sub-directories of {@code SIS_DATA} where SIS looks for EPSG database, datum shift grids and other resources.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @since   0.7
 * @version 0.7
 * @module
 */
public enum DataDirectory {
    /**
     * The {@code "Databases"} directory.
     * This directory is used for storing EPSG database and other metadata.
     */
    DATABASES,

    /**
     * The {@code "DatumChanges"} directory.
     * This directory is used for storing datum shift grids.
     */
    DATUM_CHANGES,

    /**
     * The {@code "DomainsOfValidity"} directory.
     * This directory is used for storing shapefiles for the CRS domains of validity.
     */
    DOMAINS_OF_VALIDITY;

    /**
     * The name of the environment variable.
     */
    public static final String ENV = "SIS_DATA";

    /**
     * Key of the last message logged at {@link Level#WARNING}, or {@code null} if none.
     *
     * @see #getRootDirectory()
     */
    private static short lastWarning;

    /**
     * The root directory fetched from the {@code SIS_DATA} environment variable when first needed,
     * or {@code null} if none or not yet determined.
     *
     * @see #getRootDirectory()
     */
    private static Path rootDirectory;

    /**
     * The directory, or {@code null} if none or not yet determined.
     *
     * @see #getDirectory()
     */
    private Path directory;

    /**
     * Logs a message to the {@code "org.apache.sis.system"} logger only if different than the last warning.
     */
    private static void warning(final String method, final Exception e, final short key, final Object... parameters) {
        if (key != lastWarning) {
            lastWarning = key;
            log(Level.WARNING, method, e, key, parameters);
        }
    }

    /**
     * Logs a message to the {@code "org.apache.sis.system"} logger.
     */
    private static void log(final Level level, final String method, final Exception e, final short key, final Object... parameters) {
        final LogRecord record = Messages.getResources(null).getLogRecord(level, key, parameters);
        record.setLoggerName(Loggers.SYSTEM);
        if (e != null) {
            record.setThrown(e);
        }
        Logging.log(DataDirectory.class, method, record);
    }

    /**
     * Returns the root directory fetched from the {@code SIS_DATA} environment variable.
     * If the environment variable is not set or the directory does not exist, then this method returns {@code null}.
     *
     * @return The root SIS data directory, or {@code null} if none.
     */
    public static synchronized Path getRootDirectory() {
        if (rootDirectory == null) try {
            final String dir = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getenv(ENV));
            if (dir == null || dir.isEmpty()) {
                warning("getRootDirectory", null, Messages.Keys.DataDirectoryNotSpecified_1, ENV);
            } else try {
                final Path path = Paths.get(dir);
                if (!Files.isDirectory(path)) {
                    warning("getRootDirectory", null, Messages.Keys.DataDirectoryDoesNotExist_2, ENV, path);
                } else if (!Files.isReadable(path)) {
                    warning("getRootDirectory", null, Messages.Keys.DataDirectoryNotReadable_2, ENV, path);
                } else {
                    log(Level.CONFIG, "getRootDirectory", null, Messages.Keys.DataDirectory_2, ENV, path);
                    rootDirectory = path;
                }
            } catch (InvalidPathException e) {
                warning("getRootDirectory", e, Messages.Keys.DataDirectoryDoesNotExist_2, ENV, dir);
            }
        } catch (SecurityException e) {
            warning("getRootDirectory", e, Messages.Keys.DataDirectoryNotAuthorized_1, ENV);
        }
        return rootDirectory;
    }

    /**
     * Returns the sub-directory identified by this enum, or {@code null} if the parent {@code $SIS_DATA}
     * directory was not specified. If the {@code $SIS_DATA} directory exists but not the sub-directory,
     * then this method creates the sub-directory.
     *
     * @return The sub-directory, or {@code null} if unspecified.
     */
    public synchronized Path getDirectory() {
        if (directory == null) {
            final Path root = getRootDirectory();
            if (root != null) {
                final StringBuilder buffer = new StringBuilder(name());
                for (int i=1; i<buffer.length(); i++) {
                    final char c = buffer.charAt(i);
                    if (c == '_') buffer.deleteCharAt(i);
                    else buffer.setCharAt(i, Character.toLowerCase(c));
                }
                final String name = buffer.toString();
                final Path dir = root.resolve(name).normalize();
                try {
                    if (Files.isDirectory(dir)) {
                        directory = dir;
                    } else if (Files.isWritable(root)) try {
                        directory = Files.createDirectory(dir);
                    } catch (IOException e) {
                        warning("getDirectory", e, Messages.Keys.DataDirectoryNotWritable_2, ENV, root);
                    } else {
                        warning("getDirectory", null, Messages.Keys.DataDirectoryNotWritable_2, ENV, root);
                    }
                } catch (SecurityException e) {
                    warning("getDirectory", e, Messages.Keys.DataDirectoryNotAccessible_2, ENV, name);
                }
            }
        }
        return directory;
    }

    /**
     * If the given path is relative, returns the path as a child of the directory represented this enum.
     * If no valid directory is configured by the {@code SIS_DATA} environment variable, then the relative
     * path is returned as-is.
     *
     * @param  file The path to resolve, or {@code null}.
     * @return The path to use, or {@code null} if the given path was null.
     */
    public Path resolve(Path file) {
        if (file != null && !file.isAbsolute()) {
            final Path dir = getDirectory();
            if (dir != null) {
                return dir.resolve(file);
            }
        }
        return file;
    }
}


text:
package conversion

import (
	"fmt"
	"reflect"
)

type notRegisteredErr struct {
	kind    string
	version string
	t       reflect.Type
}

func (k *notRegisteredErr) Error() string {
	if k.t != nil {
		return fmt.Sprintf("no kind is registered for the type %v", k.t)
	}
	if len(k.kind) == 0 {
		return fmt.Sprintf("no version %q has been registered", k.version)
	}
	if len(k.version) == 0 {
		return fmt.Sprintf("no kind %q is registered for the default version", k.kind)
	}
	return fmt.Sprintf("no kind %q is registered for version %q", k.kind, k.version)
}

// IsNotRegisteredError returns true if the error indicates the provided
// object or input data is not registered.
func IsNotRegisteredError(err error) bool {
	if err == nil {
		return false
	}
	_, ok := err.(*notRegisteredErr)
	return ok
}

type missingKindErr struct {
	data string
}

func NewMissingKindErr(data string) error {
	return &missingKindErr{data}
}

func (k *missingKindErr) Error() string {
	return fmt.Sprintf("Object 'Kind' is missing in '%s'", k.data)
}

func IsMissingKind(err error) bool {
	if err == nil {
		return false
	}
	_, ok := err.(*missingKindErr)
	return ok
}

type missingVersionErr struct {
	data string
}

func NewMissingVersionErr(data string) error {
	return &missingVersionErr{data}
}

func (k *missingVersionErr) Error() string {
	return fmt.Sprintf("Object 'apiVersion' is missing in '%s'", k.data)
}

func IsMissingVersion(err error) bool {
	if err == nil {
		return false
	}
	_, ok := err.(*missingVersionErr)
	return ok
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.facebook.thrift.annotation_deprecated;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import com.facebook.thrift.*;
import com.facebook.thrift.annotations.*;
import com.facebook.thrift.async.*;
import com.facebook.thrift.meta_data.*;
import com.facebook.thrift.server.*;
import com.facebook.thrift.transport.*;
import com.facebook.thrift.protocol.*;

/**
 * Adds a typedef of {enum}Set that is sutable for storing a `packed` set of
 * values for the annotated enum.
 *
 * Any enum with this annotation must only have values between 1 and 32 inclusive.
 *
 * For example:
 *   @thrift.GenEnumSet
 *   enum Flag {
 *     Option1 = 1,
 *     ...
 *   }
 *
 * Generates the equivalent of:
 *   @cpp.Adapter("::apache::thrift::EnumSetAdapter<::ns::Flag>")
 *   ...
 *   typedef i32 FlagSet
 *
 * `FlagSet` can then be used like a normal typedef.
 */
@SuppressWarnings({ "unused", "serial" })
public class GenEnumSet implements TBase, java.io.Serializable, Cloneable, Comparable<GenEnumSet> {
  private static final TStruct STRUCT_DESC = new TStruct("GenEnumSet");
  private static final TField NAME_FIELD_DESC = new TField("name", TType.STRING, (short)1);

  /**
   * If a custom name is not provided, `{EnumName}Set` is used.
   */
  public String name;
  public static final int NAME = 1;

  // isset id assignments

  public static final Map<Integer, FieldMetaData> metaDataMap;

  static {
    Map<Integer, FieldMetaData> tmpMetaDataMap = new HashMap<Integer, FieldMetaData>();
    tmpMetaDataMap.put(NAME, new FieldMetaData("name", TFieldRequirementType.DEFAULT,
        new FieldValueMetaData(TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMetaDataMap);
  }

  static {
    FieldMetaData.addStructMetaDataMap(GenEnumSet.class, metaDataMap);
  }

  public GenEnumSet() {
  }

  public GenEnumSet(
      String name) {
    this();
    this.name = name;
  }

  public static class Builder {
    private String name;

    public Builder() {
    }

    public Builder setName(final String name) {
      this.name = name;
      return this;
    }

    public GenEnumSet build() {
      GenEnumSet result = new GenEnumSet();
      result.setName(this.name);
      return result;
    }
  }

  public static Builder builder() {
    return new Builder();
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public GenEnumSet(GenEnumSet other) {
    if (other.isSetName()) {
      this.name = TBaseHelper.deepCopy(other.name);
    }
  }

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

  /**
   * If a custom name is not provided, `{EnumName}Set` is used.
   */
  public String getName() {
    return this.name;
  }

  /**
   * If a custom name is not provided, `{EnumName}Set` is used.
   */
  public GenEnumSet setName(String name) {
    this.name = name;
    return this;
  }

  public void unsetName() {
    this.name = null;
  }

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

  public void setNameIsSet(boolean __value) {
    if (!__value) {
      this.name = null;
    }
  }

  public void setFieldValue(int fieldID, Object __value) {
    switch (fieldID) {
    case NAME:
      if (__value == null) {
        unsetName();
      } else {
        setName((String)__value);
      }
      break;

    default:
      throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
    }
  }

  public Object getFieldValue(int fieldID) {
    switch (fieldID) {
    case NAME:
      return getName();

    default:
      throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
    }
  }

  @Override
  public boolean equals(Object _that) {
    if (_that == null)
      return false;
    if (this == _that)
      return true;
    if (!(_that instanceof GenEnumSet))
      return false;
    GenEnumSet that = (GenEnumSet)_that;

    if (!TBaseHelper.equalsNobinary(this.isSetName(), that.isSetName(), this.name, that.name)) { return false; }

    return true;
  }

  @Override
  public int hashCode() {
    return Arrays.deepHashCode(new Object[] {name});
  }

  @Override
  public int compareTo(GenEnumSet other) {
    if (other == null) {
      // See java.lang.Comparable docs
      throw new NullPointerException();
    }

    if (other == this) {
      return 0;
    }
    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName());
    if (lastComparison != 0) {
      return lastComparison;
    }
    lastComparison = TBaseHelper.compareTo(name, other.name);
    if (lastComparison != 0) {
      return lastComparison;
    }
    return 0;
  }

  public void read(TProtocol iprot) throws TException {
    TField __field;
    iprot.readStructBegin(metaDataMap);
    while (true)
    {
      __field = iprot.readFieldBegin();
      if (__field.type == TType.STOP) {
        break;
      }
      switch (__field.id)
      {
        case NAME:
          if (__field.type == TType.STRING) {
            this.name = iprot.readString();
          } else {
            TProtocolUtil.skip(iprot, __field.type);
          }
          break;
        default:
          TProtocolUtil.skip(iprot, __field.type);
          break;
      }
      iprot.readFieldEnd();
    }
    iprot.readStructEnd();

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

  public void write(TProtocol oprot) throws TException {
    validate();

    oprot.writeStructBegin(STRUCT_DESC);
    if (this.name != null) {
      oprot.writeFieldBegin(NAME_FIELD_DESC);
      oprot.writeString(this.name);
      oprot.writeFieldEnd();
    }
    oprot.writeFieldStop();
    oprot.writeStructEnd();
  }

  @Override
  public String toString() {
    return toString(1, true);
  }

  @Override
  public String toString(int indent, boolean prettyPrint) {
    String indentStr = prettyPrint ? TBaseHelper.getIndentedString(indent) : "";
    String newLine = prettyPrint ? "\n" : "";
    String space = prettyPrint ? " " : "";
    StringBuilder sb = new StringBuilder("GenEnumSet");
    sb.append(space);
    sb.append("(");
    sb.append(newLine);
    boolean first = true;

    sb.append(indentStr);
    sb.append("name");
    sb.append(space);
    sb.append(":").append(space);
    if (this.getName() == null) {
      sb.append("null");
    } else {
      sb.append(TBaseHelper.toString(this.getName(), indent + 1, prettyPrint));
    }
    first = false;
    sb.append(newLine + TBaseHelper.reduceIndent(indentStr));
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws TException {
    // check for required fields
  }

}


text:
from datetime import timedelta, datetime
from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.exceptions import ValidationError
from django.conf import settings
from django.utils import timezone
from model_mommy import mommy

from ..models import (
    Contact,
    County,
    Ward,
    Constituency,
    Town,
    ContactType,
    PhysicalAddress,
    UserCounty,
    UserContact,
    UserConstituency,
    SubCounty,
    ErrorQueue
)
from facilities.models import RegulationStatus

class AbstractBaseModelTest(TestCase):

    def setUp(self):
        self.leo = timezone.now()
        self.jana = timezone.now() - timedelta(days=1)
        self.juzi = timezone.now() - timedelta(days=2)
        self.user_1 = mommy.make(settings.AUTH_USER_MODEL)
        self.user_2 = mommy.make(settings.AUTH_USER_MODEL)

    def test_validate_updated_date_greater_than_created(self):
        fake = ContactType(created=self.leo, updated=self.jana)

        with self.assertRaises(ValidationError) as ve:
            fake.validate_updated_date_greater_than_created()
        self.assertTrue(
            'The updated date cannot be less than the created date'
            in ve.exception.detail)

    def test_preserve_created_and_created_by(self):
        # Create  a new instance
        fake = mommy.make(ContactType, created=self.jana, updated=self.leo,
                          created_by=self.user_1, updated_by=self.user_1)
        # Switch the create
        fake.created = self.juzi
        fake.save()

        self.assertEqual(self.jana, fake.created)

        # Switch created_by
        fake.created_by = self.user_2
        fake.updated_by = self.user_2
        fake.save()

        self.assertEqual(self.user_1.id, fake.created_by.id)
        self.assertEqual(self.user_2.id, fake.updated_by.id)

    def test_delete_override(self):
        bp_type = mommy.make(ContactType, created=timezone.now(),
                             updated=timezone.now())
        bp_type.delete()
        with self.assertRaises(ContactType.DoesNotExist):
            self.assertTrue(ContactType.objects.get(
                pk=bp_type.id))

        assert ContactType.everything.get(pk=bp_type.id)

    def test_timezone(self):
        naive_datetime = datetime.now()
        instance = mommy.make(ContactType)
        instance.updated = naive_datetime
        with self.assertRaises(ValidationError):
            instance.save()

        naive_after_object_is_saved = datetime.now()
        instance.updated = naive_after_object_is_saved
        instance.save()
        self.assertTrue(timezone.is_aware(instance.updated))

        # Test that we don't need to make created timezone aware
        # It is already tizezone aware
        self.assertTrue(timezone.is_aware(instance.created))
        created_naive_datetime = datetime.now()
        instance.create = created_naive_datetime  # This should not even update
        instance.save()
        self.assertTrue(timezone.is_aware(instance.created))

class BaseTestCase(TestCase):

    def setUp(self):
        self.user = get_user_model().objects.create_superuser(
            email='tester1@ehealth.or.ke',
            first_name='Test',
            employee_number='2124124124',
            password='mtihani124',
            is_national=True
        )
        self.default_regulation_status = mommy.make(
            RegulationStatus, name="Pending Regulation", is_default=True)

        super(BaseTestCase, self).setUp()

    def inject_audit_fields(self, data):
        data["created_by"] = self.user
        data["updated_by"] = self.user
        data["created"] = timezone.now()
        data["updated"] = timezone.now()
        return data

class TestContactModel(BaseTestCase):

    def test_save_contact(self):
        contact_type = mommy.make(ContactType, name='EMAIL')
        contact_data = {
            "contact": "test@mail.com",
            "contact_type": contact_type
        }
        contact_data = self.inject_audit_fields(contact_data)
        Contact.objects.create(**contact_data)
        self.assertEquals(1, Contact.objects.count())

    def test_save_model_with_id(self):
        contact_type = mommy.make(ContactType)
        Contact.objects.create(
            pk='1a049a8a-6e1f-4427-9098-a779cf9f63fa',
            contact='375818195',
            contact_type=contact_type)
        self.assertEquals(1, Contact.objects.count())

class TestCountyModel(BaseTestCase):

    def test_save_county(self):
        county_data = {
            "name": "WAJIR"
        }
        county_data = self.inject_audit_fields(county_data)
        county = County.objects.create(**county_data)
        self.assertEquals(1, County.objects.count())
        self.assertIsNotNone(county.code)

    def test_county_code_seq(self):
        # make code None so that model mommy does not supply it
        county = mommy.make(County, code=None)
        county_2 = mommy.make(County, code=None)
        county_2_code = int(county.code) + 1
        self.assertEquals(county_2_code, county_2.code)

    def test_lookup_facility_coordinates(self):
        county = mommy.make(County)
        self.assertEqual(
            county.facility_coordinates,
            []
        )

    def test_county_bound(self):
        county = mommy.make(County)
        self.assertEqual(
            county.county_bound,
            {}
        )

class TestConstituencyModel(BaseTestCase):

    def setUp(self):
        super(TestConstituencyModel, self).setUp()
        self.county = County.objects.create(
            updated_by=self.user, created_by=self.user,
            name='county')

    def test_save_constituency(self):
        constituency_data = {
            "name": "KAPSA",
            "county": self.county

        }
        constituency_data = self.inject_audit_fields(constituency_data)
        constituency = Constituency.objects.create(**constituency_data)
        self.assertEquals(1, Constituency.objects.count())
        self.assertIsNotNone(constituency.code)

    def test_constituency_code_sequence(self):
        constituency_1 = mommy.make(Constituency, code=None)
        constituency_2 = mommy.make(Constituency, code=None)
        constituency_2_code = int(constituency_1.code) + 1
        self.assertEquals(constituency_2_code, int(constituency_2.code))

    def test_consituency_bound(self):
        const = mommy.make(Constituency)
        self.assertEqual(
            const.constituency_bound,
            {}
        )

class TestWardModel(BaseTestCase):

    def setUp(self):
        super(TestWardModel, self).setUp()
        county = mommy.make(County)
        self.constituency = Constituency.objects.create(
            created_by=self.user, updated_by=self.user,
            name='constituency', county=county)

    def test_save_ward(self):
        data = {
            "name": "KAPSA",
            "constituency": self.constituency
        }
        data = self.inject_audit_fields(data)
        ward = Ward.objects.create(**data)
        self.assertEquals(1, Ward.objects.count())
        self.assertIsNotNone(ward.code)

    def test_sub_county_code_seq(self):
        sub_county_1 = mommy.make(Ward, code=None)
        sub_county_2 = mommy.make(Ward, code=None)
        sub_county_2_code = int(sub_county_1.code) + 1
        self.assertEquals(sub_county_2_code, int(sub_county_2.code))

    def test_get_county(self):
        county = mommy.make(County)
        constituency = mommy.make(Constituency, county=county)
        ward = mommy.make(Ward, constituency=constituency)
        self.assertEquals(county, ward.county)

    def test_ward_county(self):
        # test that the county for the sub-county and the constituency
        # are the same
        sub_county = mommy.make(SubCounty)
        const = mommy.make(Constituency)
        with self.assertRaises(ValidationError):
            mommy.make(Ward, constituency=const, sub_county=sub_county)

class TestPhysicalAddress(BaseTestCase):

    def test_save(self):
        data = {
            "town": mommy.make(Town, name="Nairobi"),
            "nearest_landmark": "",
            "plot_number": "35135"
        }
        data = self.inject_audit_fields(data)
        PhysicalAddress.objects.create(**data)
        self.assertEquals(1, PhysicalAddress.objects.count())

class TestUserCountyModel(BaseTestCase):

    def test_save(self):
        user = mommy.make(get_user_model())
        county = mommy.make(County)
        data = {
            "user": user,
            "county": county
        }
        UserCounty.objects.create(**data)
        self.assertEquals(1, UserCounty.objects.count())

    def test_user_linked_to_a_county_once(self):
        user = mommy.make(get_user_model())
        county = mommy.make(County)
        # First time should save with no issue
        user_county_rec = mommy.make(UserCounty, user=user, county=county)
        # Deactivating the record should have no incident
        user_county_rec.active = False
        user_county_rec.save()
        self.assertFalse(UserCounty.objects.get(user=user).active)

        user_county_rec.active = True
        user_county_rec.save()
        self.assertTrue(UserCounty.objects.get(user=user).active)

class TestUserContactModel(BaseTestCase):

    def test_save(self):
        user = mommy.make(get_user_model())
        contact = mommy.make(Contact)
        data = {
            "user": user,
            "contact": contact
        }
        data = self.inject_audit_fields(data)
        UserContact.objects.create(**data)
        self.assertEquals(1, UserContact.objects.count())

    def test_user_and_contact_unique(self):
        contact = mommy.make(Contact)
        user = mommy.make(get_user_model())
        mommy.make(UserContact, user=user, contact=contact)
        with self.assertRaises(ValidationError):
            mommy.make(UserContact, user=user, contact=contact)

    def test_user_contact_deletion(self):
        contact = mommy.make(Contact)
        user = mommy.make(get_user_model())
        user_contact = mommy.make(UserContact, user=user, contact=contact)
        self.assertEquals(1, UserContact.objects.filter(user=user).count())
        user_contact.delete()
        self.assertEquals(0, UserContact.objects.filter(user=user).count())

class TestUserConstituencyModel(BaseTestCase):

    def test_save(self):
        user = mommy.make(get_user_model())
        county = mommy.make(County)
        const = mommy.make(Constituency, county=county)
        creator_user = mommy.make(get_user_model())
        mommy.make(
            UserCounty, county=county, user=creator_user)
        mommy.make(
            UserConstituency, constituency=const, user=user,
            created_by=creator_user)
        self.assertEquals(1, UserConstituency.objects.count())

    def test_validator_constituency_in_creators_county(self):
        county = mommy.make(County)
        county_2 = mommy.make(County)
        const = mommy.make(Constituency, county=county)
        const_2 = mommy.make(Constituency, county=county_2)
        user = mommy.make(get_user_model())
        user_2 = mommy.make(get_user_model())
        creator_user = mommy.make(get_user_model())
        mommy.make(UserCounty, county=county, user=creator_user)

        # should save without incidence
        mommy.make(
            UserConstituency, user=user, constituency=const,
            created_by=creator_user
        )
        self.assertEquals(1, UserConstituency.objects.count())
        # should raise validation error'
        with self.assertRaises(ValidationError):
            mommy.make(UserConstituency, user=user_2, constituency=const_2)
        # test user constituencies
        self.assertEquals(const, user.constituency)

    def test_user_created_is_in_the_creators_sub_county(self):
        county = mommy.make(County)
        constituency = mommy.make(Constituency, county=county)
        constituency_2 = mommy.make(Constituency)
        user = mommy.make(get_user_model())
        user_2 = mommy.make(get_user_model())
        user_3 = mommy.make(get_user_model())
        mommy.make(UserCounty, county=county, user=user)
        mommy.make(
            UserConstituency, constituency=constituency,
            user=user_2, created_by=user, updated_by=user)

        # the user being created and the creating user are not in
        # the same constituency
        with self.assertRaises(ValidationError):
            mommy.make(
                UserConstituency, constituency=constituency_2,
                user=user_3, created_by=user_2, updated_by=user_2)

    def test_user_linked_to_a_constituency_once(self):
        user = mommy.make(get_user_model())
        county = mommy.make(County)
        const = mommy.make(Constituency, county=county)
        creator_user = mommy.make(get_user_model())
        mommy.make(UserCounty, user=creator_user, county=county)
        # First time should save with no issue
        user_const_rec = mommy.make(
            UserConstituency, user=user, constituency=const,
            created_by=creator_user, updated_by=creator_user)
        # Deactivating the record should have no incident
        user_const_rec.active = False
        user_const_rec.save()
        self.assertFalse(UserConstituency.objects.get(user=user).active)

        user_const_rec.active = True
        user_const_rec.save()
        self.assertTrue(UserConstituency.objects.get(user=user).active)

class TestSubCounty(TestCase):

    def test_save(self):
        mommy.make(SubCounty)
        self.assertEquals(1, SubCounty.objects.count())

class TestErrorQueue(TestCase):
    def test_save(self):
        mommy.make(ErrorQueue)
        self.assertEquals(1, ErrorQueue.objects.count())

    def test_representation(self):
        error = mommy.make(
            ErrorQueue,
            object_pk='1',
            app_label='users',
            model_name='MflUser')
        string_rep = "1 - users - MflUser"
        self.assertEquals(string_rep, error.__str__())


text:
package com.jiabangou.ninja.vertx.standalone.utils;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DateGenerator {
    private static final TimeZone __GMT = TimeZone.getTimeZone("GMT");

    static {
        __GMT.setID("GMT");
    }

    static final String[] DAYS =
            {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    static final String[] MONTHS =
            {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"};

    private static final ThreadLocal<DateGenerator> __dateGenerator = new ThreadLocal<DateGenerator>() {
        @Override
        protected DateGenerator initialValue() {
            return new DateGenerator();
        }
    };

    public final static String __01Jan1970 = DateGenerator.formatDate(0);

    /**
     * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
     */
    public static String formatDate(long date) {
        return __dateGenerator.get().doFormatDate(date);
    }

    /**
     * Format "EEE, dd-MMM-yyyy HH:mm:ss 'GMT'" for cookies
     */
    public static void formatCookieDate(StringBuilder buf, long date) {
        __dateGenerator.get().doFormatCookieDate(buf, date);
    }

    /**
     * Format "EEE, dd-MMM-yyyy HH:mm:ss 'GMT'" for cookies
     * @param date
     * @return
     */
    public static String formatCookieDate(long date) {
        StringBuilder buf = new StringBuilder(28);
        formatCookieDate(buf, date);
        return buf.toString();
    }

    private final StringBuilder buf = new StringBuilder(32);
    private final GregorianCalendar gc = new GregorianCalendar(__GMT);

    /**
     * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'"
     * @param date
     * @return
     */
    public String doFormatDate(long date) {
        buf.setLength(0);
        gc.setTimeInMillis(date);

        int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
        int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
        int month = gc.get(Calendar.MONTH);
        int year = gc.get(Calendar.YEAR);
        int century = year / 100;
        year = year % 100;

        int hours = gc.get(Calendar.HOUR_OF_DAY);
        int minutes = gc.get(Calendar.MINUTE);
        int seconds = gc.get(Calendar.SECOND);

        buf.append(DAYS[day_of_week]);
        buf.append(',');
        buf.append(' ');
        append2digits(buf, day_of_month);

        buf.append(' ');
        buf.append(MONTHS[month]);
        buf.append(' ');
        append2digits(buf, century);
        append2digits(buf, year);

        buf.append(' ');
        append2digits(buf, hours);
        buf.append(':');
        append2digits(buf, minutes);
        buf.append(':');
        append2digits(buf, seconds);
        buf.append(" GMT");
        return buf.toString();
    }

    /**
     * Format "EEE, dd-MMM-yy HH:mm:ss 'GMT'" for cookies
     * @param buf
     * @param date
     */
    public void doFormatCookieDate(StringBuilder buf, long date) {
        gc.setTimeInMillis(date);

        int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
        int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
        int month = gc.get(Calendar.MONTH);
        int year = gc.get(Calendar.YEAR);
        year = year % 10000;

        int epoch = (int) ((date / 1000) % (60 * 60 * 24));
        int seconds = epoch % 60;
        epoch = epoch / 60;
        int minutes = epoch % 60;
        int hours = epoch / 60;

        buf.append(DAYS[day_of_week]);
        buf.append(',');
        buf.append(' ');
        append2digits(buf, day_of_month);

        buf.append('-');
        buf.append(MONTHS[month]);
        buf.append('-');
        append2digits(buf, year / 100);
        append2digits(buf, year % 100);

        buf.append(' ');
        append2digits(buf, hours);
        buf.append(':');
        append2digits(buf, minutes);
        buf.append(':');
        append2digits(buf, seconds);
        buf.append(" GMT");
    }

    public static void append2digits(StringBuilder buf, int i) {
        if (i < 100) {
            buf.append((char) (i / 10 + 48));
            buf.append((char) (i % 10 + 48));
        }
    }
}


text:
<Type Name="LogNotifyHandler" FullName="Hyena.LogNotifyHandler">
  <TypeSignature Language="C#" Value="public delegate void LogNotifyHandler(LogNotifyArgs args);" />
  <AssemblyInfo>
    <AssemblyName>Hyena</AssemblyName>
    <AssemblyVersion>0.90.1.25402</AssemblyVersion>
    <AssemblyVersion>1.3.1.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Delegate</BaseTypeName>
  </Base>
  <Parameters>
    <Parameter Name="args" Type="Hyena.LogNotifyArgs" />
  </Parameters>
  <ReturnValue>
    <ReturnType>System.Void</ReturnType>
  </ReturnValue>
  <Docs>
    <param name="args">To be added.</param>
    <summary>To be added.</summary>
    <remarks>To be added.</remarks>
  </Docs>
</Type>


text:
package me.rybakiewicz.objectmapping;

import java.io.File;
import java.io.InputStream;

import org.codehaus.jackson.map.ObjectMapper;

public class DataParserJSON implements DataParser {

	public DataParserResult parseFromString(String jsonString) {
		try {
			return new DataParserResult(new ObjectMapper().readValue(jsonString, Object.class));
		} catch (Exception e) {
		}
		return new DataParserResult();
	}

	public DataParserResult parseFromInputStream(InputStream inputStream) {
		try {
			return new DataParserResult(new ObjectMapper().readValue(inputStream, Object.class));
		} catch (Exception e) {
		}
		return new DataParserResult();
	}

	public DataParserResult parseFromFile(File file) {
		try {
			return new DataParserResult(new ObjectMapper().readValue(file, Object.class));
		} catch (Exception e) {
		}
		return new DataParserResult();
	}

}


text:
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');

var ComponentGenerator = module.exports = function ComponentGenerator(args, options, config) {

    // By calling `NamedBase` here, we get the argument to the subgenerator call
    // as `this.name`.
    yeoman.generators.NamedBase.apply(this, arguments);

    this.generatorName = this.name;
};

util.inherits(ComponentGenerator, yeoman.generators.NamedBase);

ComponentGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // have Yeoman greet the user.
    console.log(this.yeoman);

    var prompts = [
        {
            type: 'confirm',
            name: 'jquery',
            message: 'Would you like to use jquery?',
            default: true
        },
        {
            type: 'confirm',
            name: 'bootstrap_style',
            message: 'Would you like to use bootstrap 3.0 styles?',
            default: true
        },
        {
            type: 'confirm',
            name: 'bootstrap_components',
            message: 'Would you like to use bootstrap 3.0 javascript components? (jQuery is as a dependency)',
            default: true
        }
    ];

    this.prompt(prompts, function (props) {
        // These values are accessible in this project as <% blogName %>
        // `props` is an object passed in containing the response values, named in
        // accordance with the `name` property from your prompt object. So, for us:
        this.jquery = props.jquery;
        this.bootstrap_style = props.bootstrap_style;
        this.bootstrap_components = props.bootstrap_components;

        cb();
    }.bind(this));
};

ComponentGenerator.prototype.writeIndex = function writeIndex() {
    // this.indexFile = this.engine((this.read('component-template.html')), this);
    var indexPath = this.sourceRoot() + '/component-template.html',
        jsPath = this.sourceRoot() + '/component-script.js',
        cssPath = this.sourceRoot() + '/component-styles.css';

    //index
    this.indexFile = this.readFileAsString(indexPath);
    this.indexFile = this.engine(this.indexFile, this);

    //js
    this.jsFile = this.readFileAsString(jsPath);
    this.jsFile = this.engine(this.jsFile, this);

    //css
    this.cssFile = this.readFileAsString(cssPath);
    this.cssFile = this.engine(this.cssFile, this);
};

ComponentGenerator.prototype.files = function files() {

    //add html component
    var fileName = this._.camelize(this.name) + '.html';
    this.write('app/' + fileName, this.indexFile);

    //add js
    var jsName = this._.camelize(this.name) + '.js';
    this.write('app/scripts/' + jsName, this.jsFile);

    //add css
    var cssName = this._.camelize(this.name) + '.css';
    this.write('app/styles/' + cssName, this.cssFile);

    //copy over libs
    if (this.jquery) {
        this.copy('jquery-1.10.2.min.js', 'app/scripts/lib/jquery-1.10.2.min.js');
    }

    /**
     * TODO
     * Shouldn't copy over files if they exist
     */
    if (this.bootstrap_style) {

        //regular css
        this.copy('bootstrap-3.0/css/bootstrap.css', 'app/styles/lib/bootstrap.css');
        this.copy('bootstrap-3.0/css/bootstrap.min.css', 'app/styles/lib/bootstrap.min.css');

        //extended theme css
        this.copy('bootstrap-3.0/css/bootstrap-theme.css', 'app/styles/lib/bootstrap-theme.css');
        this.copy('bootstrap-3.0/css/bootstrap-theme.min.css', 'app/styles/lib/bootstrap-theme.min.css');

        //fonts necessary for css glyphicons
        this.copy('bootstrap-3.0/fonts/glyphicons-halflings-regular.eot', 'app/fonts/glyphicons-halflings-regular.eot');
        this.copy('bootstrap-3.0/fonts/glyphicons-halflings-regular.svg', 'app/fonts/glyphicons-halflings-regular.svg');
        this.copy('bootstrap-3.0/fonts/glyphicons-halflings-regular.ttf', 'app/fonts/glyphicons-halflings-regular.ttf');
        this.copy('bootstrap-3.0/fonts/glyphicons-halflings-regular.woff', 'app/fonts/glyphicons-halflings-regular.woff');

        //html5 and responsive media queries polyfill for IE9 and below
        this.copy('bootstrap-3.0/assets/js/html5shiv.js', 'app/scripts/lib/html5shiv.js');
        this.copy('bootstrap-3.0/assets/js/respond.min.js', 'app/scripts/lib/respond.min.js');
    }

    if (this.bootstrap_components) {
        this.copy('bootstrap-3.0/js/bootstrap.js', 'app/scripts/lib/bootstrap.js');
        this.copy('bootstrap-3.0/js/bootstrap.min.js', 'app/scripts/lib/bootstrap.min.js');

        if (!(this.jquery)) {
            this.copy('jquery-1.10.2.min.js', 'app/scripts/lib/jquery-1.10.2.min.js');
        }
    }
};


text:
Imagine you have been tasked by the Account Manager to create a basic reporting application that will allow the account manager to view complaints via a online portal.
The company already has an internal json rest api that stores all the complaints that the business has recieved and the number of corresponding sales in that period.

The internal json rest api can be hosted locally using the following commands:

```shell
$ npm install -g json-server

$ json-server --watch db.json
```

## 1. Develop a basic reporting portal using any frameworks you see fit for purpose.

![Example Reporting Porta](/example-2.png "Example Reporting Portal")

## 2. Allow the ability for the user to toggle Quarter and Month consolidation.

For example:

|Month       | CPMU|
|---------- | ----------|
|01 January 2012|	5.47388874|
|01 February 2012|	57.65682657|
|01 March 2012|	12.12591551|
|01 May 2012|	67.77995238|
|01 June 2012|	93.67857009|

Should be displayed as:

|Quarter       | CPMU|
|---------- | ----------|
|1|	7.186971458|
|2|	82.6888992|

## 3. Within the report there are missing months when data are not available, these days should be displayed as 0.

For example:

Month       | Amounts
---------- | ----------|
|01 February 2012|	57.65682657|
|01 March 2012|	12.12591551|
|01 May 2012|	67.77995238|
|01 June 2012|	93.67857009|

Should be displayed as:

|Month       | Amounts
|---------- | ----------|
|01 February 2012|	57.65682657|
|01 March 2012|	12.12591551|
|01 April 2012|	0.00000|
|01 June 2012|	93.67857009|
|01 July 2012|	57.29516406|

# The Test #
Hopefully, completing the test itself shouldn't be too difficult to complete, but what we are looking for here is you approach the project, the tests put in place, the structure of the code etc… You should approach this as if it were part of much bigger interconnected project. There are no prizes for finishing quickly.


text:
module WhinyValidation
  VERSION = "1.0"
end


text:
/**
 * @file
 * Network Point to Point Protocol over Layer 2 Tunneling Protocol header file.
 *
 */

/*
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 */

#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && PPPOL2TP_SUPPORT /* don't build if not configured for use in lwipopts.h */

#ifndef PPPOL2TP_H
#define PPPOL2TP_H

#include "ppp.h"

#ifdef __cplusplus
extern "C" {
#endif

/* Timeout */
#define PPPOL2TP_CONTROL_TIMEOUT         (5*1000)  /* base for quick timeout calculation */
#define PPPOL2TP_SLOW_RETRY              (60*1000) /* persistent retry interval */

#define PPPOL2TP_MAXSCCRQ                4         /* retry SCCRQ four times (quickly) */
#define PPPOL2TP_MAXICRQ                 4         /* retry IRCQ four times */
#define PPPOL2TP_MAXICCN                 4         /* retry ICCN four times */

/* L2TP header flags */
#define PPPOL2TP_HEADERFLAG_CONTROL      0x8000
#define PPPOL2TP_HEADERFLAG_LENGTH       0x4000
#define PPPOL2TP_HEADERFLAG_SEQUENCE     0x0800
#define PPPOL2TP_HEADERFLAG_OFFSET       0x0200
#define PPPOL2TP_HEADERFLAG_PRIORITY     0x0100
#define PPPOL2TP_HEADERFLAG_VERSION      0x0002

/* Mandatory bits for control: Control, Length, Sequence, Version 2 */
#define PPPOL2TP_HEADERFLAG_CONTROL_MANDATORY     (PPPOL2TP_HEADERFLAG_CONTROL|PPPOL2TP_HEADERFLAG_LENGTH|PPPOL2TP_HEADERFLAG_SEQUENCE|PPPOL2TP_HEADERFLAG_VERSION)
/* Forbidden bits for control: Offset, Priority */
#define PPPOL2TP_HEADERFLAG_CONTROL_FORBIDDEN     (PPPOL2TP_HEADERFLAG_OFFSET|PPPOL2TP_HEADERFLAG_PRIORITY)

/* Mandatory bits for data: Version 2 */
#define PPPOL2TP_HEADERFLAG_DATA_MANDATORY        (PPPOL2TP_HEADERFLAG_VERSION)

/* AVP (Attribute Value Pair) header */
#define PPPOL2TP_AVPHEADERFLAG_MANDATORY  0x8000
#define PPPOL2TP_AVPHEADERFLAG_HIDDEN     0x4000
#define PPPOL2TP_AVPHEADERFLAG_LENGTHMASK 0x03ff

/* -- AVP - Message type */
#define PPPOL2TP_AVPTYPE_MESSAGE      0 /* Message type */

/* Control Connection Management */
#define PPPOL2TP_MESSAGETYPE_SCCRQ    1 /* Start Control Connection Request */
#define PPPOL2TP_MESSAGETYPE_SCCRP    2 /* Start Control Connection Reply */
#define PPPOL2TP_MESSAGETYPE_SCCCN    3 /* Start Control Connection Connected */
#define PPPOL2TP_MESSAGETYPE_STOPCCN  4 /* Stop Control Connection Notification */
#define PPPOL2TP_MESSAGETYPE_HELLO    6 /* Hello */
/* Call Management */
#define PPPOL2TP_MESSAGETYPE_OCRQ     7 /* Outgoing Call Request */
#define PPPOL2TP_MESSAGETYPE_OCRP     8 /* Outgoing Call Reply */
#define PPPOL2TP_MESSAGETYPE_OCCN     9 /* Outgoing Call Connected */
#define PPPOL2TP_MESSAGETYPE_ICRQ    10 /* Incoming Call Request */
#define PPPOL2TP_MESSAGETYPE_ICRP    11 /* Incoming Call Reply */
#define PPPOL2TP_MESSAGETYPE_ICCN    12 /* Incoming Call Connected */
#define PPPOL2TP_MESSAGETYPE_CDN     14 /* Call Disconnect Notify */
/* Error reporting */
#define PPPOL2TP_MESSAGETYPE_WEN     15 /* WAN Error Notify */
/* PPP Session Control */
#define PPPOL2TP_MESSAGETYPE_SLI     16 /* Set Link Info */

/* -- AVP - Result code */
#define PPPOL2TP_AVPTYPE_RESULTCODE   1 /* Result code */
#define PPPOL2TP_RESULTCODE           1 /* General request to clear control connection */

/* -- AVP - Protocol version (!= L2TP Header version) */
#define PPPOL2TP_AVPTYPE_VERSION      2
#define PPPOL2TP_VERSION         0x0100 /* L2TP Protocol version 1, revision 0 */

/* -- AVP - Framing capabilities */
#define PPPOL2TP_AVPTYPE_FRAMINGCAPABILITIES           3 /* Bearer capabilities */
#define PPPOL2TP_FRAMINGCAPABILITIES          0x00000003 /* Async + Sync framing */

/* -- AVP - Bearer capabilities */
#define PPPOL2TP_AVPTYPE_BEARERCAPABILITIES           4 /* Bearer capabilities */
#define PPPOL2TP_BEARERCAPABILITIES          0x00000003 /* Analog + Digital Access */

/* -- AVP - Tie breaker */
#define PPPOL2TP_AVPTYPE_TIEBREAKER   5

/* -- AVP - Host name */
#define PPPOL2TP_AVPTYPE_HOSTNAME     7 /* Host name */
#define PPPOL2TP_HOSTNAME        "lwIP" /* FIXME: make it configurable */

/* -- AVP - Vendor name */
#define PPPOL2TP_AVPTYPE_VENDORNAME   8 /* Vendor name */
#define PPPOL2TP_VENDORNAME      "lwIP" /* FIXME: make it configurable */

/* -- AVP - Assign tunnel ID */
#define PPPOL2TP_AVPTYPE_TUNNELID     9 /* Assign Tunnel ID */

/* -- AVP - Receive window size */
#define PPPOL2TP_AVPTYPE_RECEIVEWINDOWSIZE  10 /* Receive window size */
#define PPPOL2TP_RECEIVEWINDOWSIZE           8 /* FIXME: make it configurable */

/* -- AVP - Challenge */
#define PPPOL2TP_AVPTYPE_CHALLENGE   11 /* Challenge */

/* -- AVP - Cause code */
#define PPPOL2TP_AVPTYPE_CAUSECODE   12 /* Cause code*/

/* -- AVP - Challenge response */
#define PPPOL2TP_AVPTYPE_CHALLENGERESPONSE   13 /* Challenge response */
#define PPPOL2TP_AVPTYPE_CHALLENGERESPONSE_SIZE  16

/* -- AVP - Assign session ID */
#define PPPOL2TP_AVPTYPE_SESSIONID   14 /* Assign Session ID */

/* -- AVP - Call serial number */
#define PPPOL2TP_AVPTYPE_CALLSERIALNUMBER   15 /* Call Serial Number */

/* -- AVP - Framing type */
#define PPPOL2TP_AVPTYPE_FRAMINGTYPE         19 /* Framing Type */
#define PPPOL2TP_FRAMINGTYPE         0x00000001 /* Sync framing */

/* -- AVP - TX Connect Speed */
#define PPPOL2TP_AVPTYPE_TXCONNECTSPEED      24 /* TX Connect Speed */
#define PPPOL2TP_TXCONNECTSPEED       100000000 /* Connect speed: 100 Mbits/s */

/* L2TP Session state */
#define PPPOL2TP_STATE_INITIAL     0
#define PPPOL2TP_STATE_SCCRQ_SENT  1
#define PPPOL2TP_STATE_ICRQ_SENT   2
#define PPPOL2TP_STATE_ICCN_SENT   3
#define PPPOL2TP_STATE_DATA        4

#define PPPOL2TP_OUTPUT_DATA_HEADER_LEN   6 /* Our data header len */

/*
 * PPPoL2TP interface control block.
 */
typedef struct pppol2tp_pcb_s pppol2tp_pcb;
struct pppol2tp_pcb_s {
  ppp_pcb *ppp;                /* PPP PCB */
  u8_t phase;                  /* L2TP phase */
  struct udp_pcb *udp;         /* UDP L2TP Socket */
  struct netif *netif;         /* Output interface, used as a default route */
  ip_addr_t remote_ip;         /* LNS IP Address */
  u16_t remote_port;           /* LNS port */
#if PPPOL2TP_AUTH_SUPPORT
  const u8_t *secret;          /* Secret string */
  u8_t secret_len;             /* Secret string length */
  u8_t secret_rv[16];          /* Random vector */
  u8_t challenge_hash[16];     /* Challenge response */
  u8_t send_challenge;         /* Boolean whether the next sent packet should contains a challenge response */
#endif /* PPPOL2TP_AUTH_SUPPORT */

  u16_t tunnel_port;           /* Tunnel port */
  u16_t our_ns;                /* NS to peer */
  u16_t peer_nr;               /* NR from peer */
  u16_t peer_ns;               /* Expected NS from peer */
  u16_t source_tunnel_id;      /* Tunnel ID assigned by peer */
  u16_t remote_tunnel_id;      /* Tunnel ID assigned to peer */
  u16_t source_session_id;     /* Session ID assigned by peer */
  u16_t remote_session_id;     /* Session ID assigned to peer */

  u8_t sccrq_retried;          /* number of SCCRQ retries already done */
  u8_t icrq_retried;           /* number of ICRQ retries already done */
  u8_t iccn_retried;           /* number of ICCN retries already done */
};

/* Create a new L2TP session. */
ppp_pcb *pppol2tp_create(struct netif *pppif,
       struct netif *netif, const ip_addr_t *ipaddr, u16_t port,
       const u8_t *secret, u8_t secret_len,
       ppp_link_status_cb_fn link_status_cb, void *ctx_cb);

#ifdef __cplusplus
}
#endif

#endif /* PPPOL2TP_H */
#endif /* PPP_SUPPORT && PPPOL2TP_SUPPORT */


text:
/* Type-specific source code for unit test
 *
 * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
 * We check in the generated source files so that the test tree can be used
 * independently of the rest of the source tree.
 */

// -- This file was mechanically generated: Do not edit! -- //

import java.nio.*;
import java.lang.reflect.Method;

public class BasicByte
    extends Basic
{

    private static final byte[] VALUES = {
        Byte.MIN_VALUE,
        (byte) -1,
        (byte) 0,
        (byte) 1,
        Byte.MAX_VALUE,

    };

    private static void relGet(ByteBuffer b) {
        int n = b.capacity();
        byte v;
        for (int i = 0; i < n; i++)
            ck(b, (long)b.get(), (long)((byte)ic(i)));
        b.rewind();
    }

    private static void relGet(ByteBuffer b, int start) {
        int n = b.remaining();
        byte v;
        for (int i = start; i < n; i++)
            ck(b, (long)b.get(), (long)((byte)ic(i)));
        b.rewind();
    }

    private static void absGet(ByteBuffer b) {
        int n = b.capacity();
        byte v;
        for (int i = 0; i < n; i++)
            ck(b, (long)b.get(), (long)((byte)ic(i)));
        b.rewind();
    }

    private static void bulkGet(ByteBuffer b) {
        int n = b.capacity();
        byte[] a = new byte[n + 7];
        b.get(a, 7, n);
        for (int i = 0; i < n; i++)
            ck(b, (long)a[i + 7], (long)((byte)ic(i)));
    }

    private static void relPut(ByteBuffer b) {
        int n = b.capacity();
        b.clear();
        for (int i = 0; i < n; i++)
            b.put((byte)ic(i));
        b.flip();
    }

    private static void absPut(ByteBuffer b) {
        int n = b.capacity();
        b.clear();
        for (int i = 0; i < n; i++)
            b.put(i, (byte)ic(i));
        b.limit(n);
        b.position(0);
    }

    private static void bulkPutArray(ByteBuffer b) {
        int n = b.capacity();
        b.clear();
        byte[] a = new byte[n + 7];
        for (int i = 0; i < n; i++)
            a[i + 7] = (byte)ic(i);
        b.put(a, 7, n);
        b.flip();
    }

    private static void bulkPutBuffer(ByteBuffer b) {
        int n = b.capacity();
        b.clear();
        ByteBuffer c = ByteBuffer.allocate(n + 7);
        c.position(7);
        for (int i = 0; i < n; i++)
            c.put((byte)ic(i));
        c.flip();
        c.position(7);
        b.put(c);
        b.flip();
    }

    //6231529
    private static void callReset(ByteBuffer b) {
        b.position(0);
        b.mark();

        b.duplicate().reset();
        b.asReadOnlyBuffer().reset();
    }

    private static void checkSlice(ByteBuffer b, ByteBuffer slice) {
        ck(slice, 0, slice.position());
        ck(slice, b.remaining(), slice.limit());
        ck(slice, b.remaining(), slice.capacity());
        if (b.isDirect() != slice.isDirect())
            fail("Lost direction", slice);
        if (b.isReadOnly() != slice.isReadOnly())
            fail("Lost read-only", slice);
    }

    private static void checkBytes(ByteBuffer b, byte[] bs) {
        int n = bs.length;
        int p = b.position();
        byte v;
        if (b.order() == ByteOrder.BIG_ENDIAN) {
            for (int i = 0; i < n; i++)
                ck(b, b.get(), bs[i]);
        } else {
            for (int i = n - 1; i >= 0; i--)
                ck(b, b.get(), bs[i]);
        }
        b.position(p);
    }

    private static void compact(Buffer b) {
        try {
            Class<?> cl = b.getClass();
            Method m = cl.getDeclaredMethod("compact");
            m.setAccessible(true);
            m.invoke(b);
        } catch (Exception e) {
            fail(e.getMessage(), b);
        }
    }

    private static void checkInvalidMarkException(final Buffer b) {
        tryCatch(b, InvalidMarkException.class, new Runnable() {
            public void run() {
                b.mark();
                compact(b);
                b.reset();
            }});
    }

    private static void testViews(int level, ByteBuffer b, boolean direct) {

        ShortBuffer sb = b.asShortBuffer();
        BasicShort.test(level, sb, direct);
        checkBytes(b, new byte[] { 0, (byte)ic(0) });
        checkInvalidMarkException(sb);

        CharBuffer cb = b.asCharBuffer();
        BasicChar.test(level, cb, direct);
        checkBytes(b, new byte[] { 0, (byte)ic(0) });
        checkInvalidMarkException(cb);

        IntBuffer ib = b.asIntBuffer();
        BasicInt.test(level, ib, direct);
        checkBytes(b, new byte[] { 0, 0, 0, (byte)ic(0) });
        checkInvalidMarkException(ib);

        LongBuffer lb = b.asLongBuffer();
        BasicLong.test(level, lb, direct);
        checkBytes(b, new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)ic(0) });
        checkInvalidMarkException(lb);

        FloatBuffer fb = b.asFloatBuffer();
        BasicFloat.test(level, fb, direct);
        checkBytes(b, new byte[] { 0x42, (byte)0xc2, 0, 0 });
        checkInvalidMarkException(fb);

        DoubleBuffer db = b.asDoubleBuffer();
        BasicDouble.test(level, db, direct);
        checkBytes(b, new byte[] { 0x40, 0x58, 0x40, 0, 0, 0, 0, 0 });
        checkInvalidMarkException(db);
    }

    private static void testHet(int level, ByteBuffer b) {

        int p = b.position();
        b.limit(b.capacity());
        show(level, b);
        out.print("    put:");

        b.putChar((char)1);
        b.putChar((char)Character.MAX_VALUE);
        out.print(" char");

        b.putShort((short)1);
        b.putShort((short)Short.MAX_VALUE);
        out.print(" short");

        b.putInt(1);
        b.putInt(Integer.MAX_VALUE);
        out.print(" int");

        b.putLong((long)1);
        b.putLong((long)Long.MAX_VALUE);
        out.print(" long");

        b.putFloat((float)1);
        b.putFloat((float)Float.MIN_VALUE);
        b.putFloat((float)Float.MAX_VALUE);
        out.print(" float");

        b.putDouble((double)1);
        b.putDouble((double)Double.MIN_VALUE);
        b.putDouble((double)Double.MAX_VALUE);
        out.print(" double");

        out.println();
        b.limit(b.position());
        b.position(p);
        show(level, b);
        out.print("    get:");

        ck(b, b.getChar(), 1);
        ck(b, b.getChar(), Character.MAX_VALUE);
        out.print(" char");

        ck(b, b.getShort(), 1);
        ck(b, b.getShort(), Short.MAX_VALUE);
        out.print(" short");

        ck(b, b.getInt(), 1);
        ck(b, b.getInt(), Integer.MAX_VALUE);
        out.print(" int");

        ck(b, b.getLong(), 1);
        ck(b, b.getLong(), Long.MAX_VALUE);
        out.print(" long");

        ck(b, (long)b.getFloat(), 1);
        ck(b, (long)b.getFloat(), (long)Float.MIN_VALUE);
        ck(b, (long)b.getFloat(), (long)Float.MAX_VALUE);
        out.print(" float");

        ck(b, (long)b.getDouble(), 1);
        ck(b, (long)b.getDouble(), (long)Double.MIN_VALUE);
        ck(b, (long)b.getDouble(), (long)Double.MAX_VALUE);
        out.print(" double");

        out.println();

    }

    private static void fail(String problem,
                             ByteBuffer xb, ByteBuffer yb,
                             byte x, byte y) {
        fail(problem + String.format(": x=%s y=%s", x, y), xb, yb);
    }

    private static void tryCatch(Buffer b, Class<?> ex, Runnable thunk) {
        boolean caught = false;
        try {
            thunk.run();
        } catch (Throwable x) {
            if (ex.isAssignableFrom(x.getClass())) {
                caught = true;
            } else {
                fail(x.getMessage() + " not expected");
            }
        }
        if (!caught)
            fail(ex.getName() + " not thrown", b);
    }

    private static void tryCatch(byte [] t, Class<?> ex, Runnable thunk) {
        tryCatch(ByteBuffer.wrap(t), ex, thunk);
    }

    public static void test(int level, final ByteBuffer b, boolean direct) {

        show(level, b);

        if (direct != b.isDirect())
            fail("Wrong direction", b);

        // Gets and puts

        relPut(b);
        relGet(b);
        absGet(b);
        bulkGet(b);

        absPut(b);
        relGet(b);
        absGet(b);
        bulkGet(b);

        bulkPutArray(b);
        relGet(b);

        bulkPutBuffer(b);
        relGet(b);

        // Compact

        relPut(b);
        b.position(13);
        b.compact();
        b.flip();
        relGet(b, 13);

        // Exceptions

        relPut(b);
        b.limit(b.capacity() / 2);
        b.position(b.limit());

        tryCatch(b, BufferUnderflowException.class, new Runnable() {
                public void run() {
                    b.get();
                }});

        tryCatch(b, BufferOverflowException.class, new Runnable() {
                public void run() {
                    b.put((byte)42);
                }});

        // The index must be non-negative and lesss than the buffer's limit.
        tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    b.get(b.limit());
                }});
        tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    b.get(-1);
                }});

        tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    b.put(b.limit(), (byte)42);
                }});

        tryCatch(b, InvalidMarkException.class, new Runnable() {
                public void run() {
                    b.position(0);
                    b.mark();
                    b.compact();
                    b.reset();
                }});

        // Values

        b.clear();
        b.put((byte)0);
        b.put((byte)-1);
        b.put((byte)1);
        b.put(Byte.MAX_VALUE);
        b.put(Byte.MIN_VALUE);

        byte v;
        b.flip();
        ck(b, b.get(), 0);
        ck(b, b.get(), (byte)-1);
        ck(b, b.get(), 1);
        ck(b, b.get(), Byte.MAX_VALUE);
        ck(b, b.get(), Byte.MIN_VALUE);

        // Comparison
        b.rewind();
        ByteBuffer b2 = ByteBuffer.allocate(b.capacity());
        b2.put(b);
        b2.flip();
        b.position(2);
        b2.position(2);
        if (!b.equals(b2)) {
            for (int i = 2; i < b.limit(); i++) {
                byte x = b.get(i);
                byte y = b2.get(i);
                if (x != y

                    )
                    out.println("[" + i + "] " + x + " != " + y);
            }
            fail("Identical buffers not equal", b, b2);
        }
        if (b.compareTo(b2) != 0)
            fail("Comparison to identical buffer != 0", b, b2);

        b.limit(b.limit() + 1);
        b.position(b.limit() - 1);
        b.put((byte)99);
        b.rewind();
        b2.rewind();
        if (b.equals(b2))
            fail("Non-identical buffers equal", b, b2);
        if (b.compareTo(b2) <= 0)
            fail("Comparison to shorter buffer <= 0", b, b2);
        b.limit(b.limit() - 1);

        b.put(2, (byte)42);
        if (b.equals(b2))
            fail("Non-identical buffers equal", b, b2);
        if (b.compareTo(b2) <= 0)
            fail("Comparison to lesser buffer <= 0", b, b2);

        // Check equals and compareTo with interesting values
        for (byte x : VALUES) {
            ByteBuffer xb = ByteBuffer.wrap(new byte[] { x });
            if (xb.compareTo(xb) != 0) {
                fail("compareTo not reflexive", xb, xb, x, x);
            }
            if (! xb.equals(xb)) {
                fail("equals not reflexive", xb, xb, x, x);
            }
            for (byte y : VALUES) {
                ByteBuffer yb = ByteBuffer.wrap(new byte[] { y });
                if (xb.compareTo(yb) != - yb.compareTo(xb)) {
                    fail("compareTo not anti-symmetric",
                         xb, yb, x, y);
                }
                if ((xb.compareTo(yb) == 0) != xb.equals(yb)) {
                    fail("compareTo inconsistent with equals",
                         xb, yb, x, y);
                }
                if (xb.compareTo(yb) != Byte.compare(x, y)) {

                    fail("Incorrect results for ByteBuffer.compareTo",
                         xb, yb, x, y);
                }
                if (xb.equals(yb) != ((x == y) || ((x != x) && (y != y)))) {
                    fail("Incorrect results for ByteBuffer.equals",
                         xb, yb, x, y);
                }
            }
        }

        // Sub, dup

        relPut(b);
        relGet(b.duplicate());
        b.position(13);
        relGet(b.duplicate(), 13);
        relGet(b.duplicate().slice(), 13);
        relGet(b.slice(), 13);
        relGet(b.slice().duplicate(), 13);

        // Slice

        b.position(5);
        ByteBuffer sb = b.slice();
        checkSlice(b, sb);
        b.position(0);
        ByteBuffer sb2 = sb.slice();
        checkSlice(sb, sb2);

        if (!sb.equals(sb2))
            fail("Sliced slices do not match", sb, sb2);
        if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
            fail("Array offsets do not match: "
                 + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);

        // Views

        b.clear();
        b.order(ByteOrder.BIG_ENDIAN);
        testViews(level + 1, b, direct);

        for (int i = 1; i <= 9; i++) {
            b.position(i);
            show(level + 1, b);
            testViews(level + 2, b, direct);
        }

        b.position(0);
        b.order(ByteOrder.LITTLE_ENDIAN);
        testViews(level + 1, b, direct);

        // Heterogeneous accessors

        b.order(ByteOrder.BIG_ENDIAN);
        for (int i = 0; i <= 9; i++) {
            b.position(i);
            testHet(level + 1, b);
        }
        b.order(ByteOrder.LITTLE_ENDIAN);
        b.position(3);
        testHet(level + 1, b);

        // Read-only views

        b.rewind();
        final ByteBuffer rb = b.asReadOnlyBuffer();
        if (!b.equals(rb))
            fail("Buffer not equal to read-only view", b, rb);
        show(level + 1, rb);

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    relPut(rb);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    absPut(rb);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    bulkPutArray(rb);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    bulkPutBuffer(rb);
                }});

        // put(ByteBuffer) should not change source position
        final ByteBuffer src = ByteBuffer.allocate(1);
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.put(src);
                 }});
        ck(src, src.position(), 0);

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.compact();
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putChar((char)1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putChar(0, (char)1);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putShort((short)1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putShort(0, (short)1);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putInt(1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putInt(0, 1);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putLong((long)1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putLong(0, (long)1);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putFloat((float)1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putFloat(0, (float)1);
                }});

        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putDouble((double)1);
                }});
        tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                public void run() {
                    rb.putDouble(0, (double)1);
                }});

        if (rb.getClass().getName().startsWith("java.nio.Heap")) {

            tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                    public void run() {
                        rb.array();
                    }});

            tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
                    public void run() {
                        rb.arrayOffset();
                    }});

            if (rb.hasArray())
                fail("Read-only heap buffer's backing array is accessible",
                     rb);

        }

        // Bulk puts from read-only buffers

        b.clear();
        rb.rewind();
        b.put(rb);

        // For byte buffers, test both the direct and non-direct cases
        ByteBuffer ob
            = (b.isDirect()
               ? ByteBuffer.allocate(rb.capacity())
               : ByteBuffer.allocateDirect(rb.capacity()));
        rb.rewind();
        ob.put(rb);

        relPut(b);                       // Required by testViews

    }

    public static void test(final byte [] ba) {
        int offset = 47;
        int length = 900;
        final ByteBuffer b = ByteBuffer.wrap(ba, offset, length);
        show(0, b);
        ck(b, b.capacity(), ba.length);
        ck(b, b.position(), offset);
        ck(b, b.limit(), offset + length);

        // The offset must be non-negative and no larger than <array.length>.
        tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap(ba, -1, ba.length);
                }});
        tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap(ba, ba.length + 1, ba.length);
                }});
        tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap(ba, 0, -1);
                }});
        tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap(ba, 0, ba.length + 1);
                }});

        // A NullPointerException will be thrown if the array is null.
        tryCatch(ba, NullPointerException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap((byte []) null, 0, 5);
                }});
        tryCatch(ba, NullPointerException.class, new Runnable() {
                public void run() {
                    ByteBuffer.wrap((byte []) null);
                }});
    }

    private static void testAllocate() {
        // An IllegalArgumentException will be thrown for negative capacities.
        tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
                public void run() {
                    ByteBuffer.allocate(-1);
                }});

        tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
                public void run() {
                    ByteBuffer.allocateDirect(-1);
                }});

    }

    public static void test() {
        testAllocate();
        test(0, ByteBuffer.allocate(7 * 1024), false);
        test(0, ByteBuffer.wrap(new byte[7 * 1024], 0, 7 * 1024), false);
        test(new byte[1024]);

        ByteBuffer b = ByteBuffer.allocateDirect(7 * 1024);
        for (b.position(0); b.position() < b.limit(); )
            ck(b, b.get(), 0);
        test(0, b, true);

        callReset(ByteBuffer.allocate(10));

    }

}


text:
@class CTMainViewController;

@interface CTAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) CTMainViewController *mainController;

@end


text:
package com.programyourhome.spiques.master.model.question;

import java.util.Locale;

public interface Question {

	QuestionType getType();

	Locale getLocale();

	String getDeclaration();

}


text:
package com.wrbug.gravitybox.nougat;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.PathInterpolator;

import java.util.ArrayList;
import java.util.HashSet;

public class KeyButtonRipple extends Drawable {

    private static final float GLOW_MAX_SCALE_FACTOR = 1.35f;
    private static final int ANIMATION_DURATION_SCALE = 350;
    private static final int ANIMATION_DURATION_FADE = 450;

    private Paint mRipplePaint;
    private float mGlowAlpha = 0f;
    private float mGlowAlphaMax = 0.2f;
    private float mGlowScale = 1f;
    private boolean mPressed;
    private int mMaxWidth;

    private final Interpolator mInterpolator = new LogInterpolator();
    private final Interpolator mAlphaExitInterpolator = new PathInterpolator(0f, 0f, 0.8f, 1f);

    private final HashSet<Animator> mRunningAnimations = new HashSet<>();
    private final ArrayList<Animator> mTmpArray = new ArrayList<>();

    public KeyButtonRipple(Context ctx, View targetView) {
        Resources res = ctx.getResources();
        int resId = res.getIdentifier("key_button_ripple_max_width", "dimen",
                ModNavigationBar.PACKAGE_NAME);
        mMaxWidth =  ctx.getResources().getDimensionPixelSize(resId);
    }

    private Paint getRipplePaint() {
        if (mRipplePaint == null) {
            mRipplePaint = new Paint();
            mRipplePaint.setAntiAlias(true);
            mRipplePaint.setColor(0xffffff);
            mRipplePaint.setAlpha((int)(mGlowAlphaMax * 255f));
        }
        return mRipplePaint;
    }

    public void setGlowColor(int color) {
        int rgb = Color.rgb(Color.red(color), Color.green(color), Color.blue(color));
        getRipplePaint().setColor(rgb);
        mGlowAlphaMax = Color.alpha(color) / 255f;
    }

    private void drawSoftware(Canvas canvas) {
        if (mGlowAlpha > 0f) {
            final Paint p = getRipplePaint();
            p.setAlpha((int)(mGlowAlpha * 255f));

            final float w = getBounds().width();
            final float h = getBounds().height();
            final boolean horizontal = w > h;
            final float diameter = getRippleSize() * mGlowScale;
            final float radius = diameter * .5f;
            final float cx = w * .5f;
            final float cy = h * .5f;
            final float rx = horizontal ? radius : cx;
            final float ry = horizontal ? cy : radius;
            final float corner = horizontal ? cy : cx;

            canvas.drawRoundRect(cx - rx, cy - ry,
                    cx + rx, cy + ry,
                    corner, corner, p);
        }
    }

    @Override
    public void draw(Canvas canvas) {
        drawSoftware(canvas);
    }

    @Override
    public void setAlpha(int alpha) {
        // Not supported.
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        // Not supported.
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    private boolean isHorizontal() {
        return getBounds().width() > getBounds().height();
    }

    public float getGlowAlpha() {
        return mGlowAlpha;
    }

    public void setGlowAlpha(float x) {
        mGlowAlpha = x;
        invalidateSelf();
    }

    public float getGlowScale() {
        return mGlowScale;
    }

    public void setGlowScale(float x) {
        mGlowScale = x;
        invalidateSelf();
    }

    @Override
    protected boolean onStateChange(int[] state) {
        boolean pressed = false;
        for (int i = 0; i < state.length; i++) {
            if (state[i] == android.R.attr.state_pressed) {
                pressed = true;
                break;
            }
        }
        if (pressed != mPressed) {
            setPressed(pressed);
            mPressed = pressed;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isStateful() {
        return true;
    }

    public void setPressed(boolean pressed) {
        setPressedSoftware(pressed);
    }

    private void cancelAnimations() {
        mTmpArray.addAll(mRunningAnimations);
        int size = mTmpArray.size();
        for (int i = 0; i < size; i++) {
            Animator a = mTmpArray.get(i);
            a.cancel();
        }
        mTmpArray.clear();
        mRunningAnimations.clear();
    }

    private void setPressedSoftware(boolean pressed) {
        if (pressed) {
            enterSoftware();
        } else {
            exitSoftware();
        }
    }

    private void enterSoftware() {
        cancelAnimations();
        mGlowAlpha = mGlowAlphaMax;
        ObjectAnimator scaleAnimator = ObjectAnimator.ofFloat(this, "glowScale",
                0f, GLOW_MAX_SCALE_FACTOR);
        scaleAnimator.setInterpolator(mInterpolator);
        scaleAnimator.setDuration(ANIMATION_DURATION_SCALE);
        scaleAnimator.addListener(mAnimatorListener);
        scaleAnimator.start();
        mRunningAnimations.add(scaleAnimator);
    }

    private void exitSoftware() {
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(this, "glowAlpha", mGlowAlpha, 0f);
        alphaAnimator.setInterpolator(mAlphaExitInterpolator);
        alphaAnimator.setDuration(ANIMATION_DURATION_FADE);
        alphaAnimator.addListener(mAnimatorListener);
        alphaAnimator.start();
        mRunningAnimations.add(alphaAnimator);
    }

    private int getRippleSize() {
        int size = isHorizontal() ? getBounds().width() : getBounds().height();
        return Math.min(size, mMaxWidth);
    }

    private final AnimatorListenerAdapter mAnimatorListener =
            new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mRunningAnimations.remove(animation);
            if (mRunningAnimations.isEmpty() && !mPressed) {
                invalidateSelf();
            }
        }
    };

    /**
     * Interpolator with a smooth log deceleration
     */
    private static final class LogInterpolator implements Interpolator {
        @Override
        public float getInterpolation(float input) {
            return 1 - (float) Math.pow(400, -input * 1.4);
        }
    }
}


text:
/*
 * catoms2DBlockCode.h
 *
 *  Created on: 12 janvier 2014
 *      Author: Benoît
 */

#ifndef CATOMS2DBLOCKCODE_H_
#define CATOMS2DBLOCKCODE_H_

#include "blockCode.h"
#include "catoms2DBlock.h"
#include "network.h"

namespace Catoms2D {

class Catoms2DBlock;

class Catoms2DBlockCode : public BaseSimulator::BlockCode {
public:

	Catoms2DBlockCode(Catoms2DBlock *host);
	virtual ~Catoms2DBlockCode();
};

}

#endif /* CATOMS2DBLOCKCODE_H_ */


text:
var bkjs = require('backendjs');
var db = bkjs.db;
var api = bkjs.api;
var app = bkjs.app;
var core = bkjs.core;
var lib = bkjs.lib;
var logger = bkjs.logger;

// Create API endpoints and routes
app.configureWeb = function(options, callback)
{
    callback()
};

bkjs.server.start();


text:
RouteController = function (router, route, options) {
  var self = this;

  if (!(router instanceof IronRouter))
    throw new Error('RouteController requires a router');

  if (!(route instanceof Route))
    throw new Error('RouteController requires a route');

  options = this.options = options || {};

  this.router = router;
  this.route = route;

  this.path = options.path || '';
  this.params = options.params || [];
  this.where = options.where || 'client';
  this.action = options.action || this.action;

  Utils.rewriteLegacyHooks(this.options);
  Utils.rewriteLegacyHooks(this);
};

RouteController.prototype = {
  constructor: RouteController,

  /**
   * Returns the value of a property, searching for the property in this lookup
   * order:
   *
   *   1. RouteController options
   *   2. RouteController prototype
   *   3. Route options
   *   4. Router options
   */
  lookupProperty: function (key) {
    var value;

    if (!_.isString(key))
      throw new Error('key must be a string');

    // 1. RouteController options
    if (typeof (value = this.options[key]) !== 'undefined')
      return value;

    // 2. RouteController instance
    if (typeof (value = this[key]) !== 'undefined')
      return value;

    var opts;

    // 3. Route options
    opts = this.route.options;
    if (opts && typeof (value = opts[key]) !== 'undefined')
      return value;

    // 4. Router options
    opts = this.router.options;
    if (opts && typeof (value = opts[key]) !== 'undefined')
      return value;

    // 5. Oops couldn't find property
    return undefined;
  },

  runHooks: function (hookName, more, cb) {
    var self = this;
    var ctor = this.constructor;

    if (!_.isString(hookName))
      throw new Error('hookName must be a string');

    if (more && !_.isArray(more))
      throw new Error('more must be an array of functions');

    var isPaused = false;

    var lookupHook = function (nameOrFn) {
      var fn = nameOrFn;

      // if we already have a func just return it
      if (_.isFunction(fn))
        return fn;

      // look up one of the out-of-box hooks like
      // 'loaded or 'dataNotFound' if the nameOrFn is a
      // string
      if (_.isString(fn)) {
        if (_.isFunction(Router.hooks[fn]))
          return Router.hooks[fn];
      }

      // we couldn't find it so throw an error
      throw new Error("No hook found named: ", nameOrFn);
    };

    // concatenate together hook arrays from the inheritance
    // heirarchy, starting at the top parent down to the child.
    var collectInheritedHooks = function (ctor) {
      var hooks = [];

      if (ctor.__super__)
        hooks = hooks.concat(collectInheritedHooks(ctor.__super__.constructor));

      return Utils.hasOwnProperty(ctor.prototype, hookName) ?
        hooks.concat(ctor.prototype[hookName]) : hooks;
    };

    // get a list of hooks to run in the following order:
    // 1. RouteController option hooks
    // 2. RouteController proto hooks (including inherited super to child)
    // 3. RouteController object hooks
    // 4. Router global hooks
    // 5. Route option hooks
    // 6. more

    var toArray = Utils.toArray;
    var routerHooks = this.router.getHooks(hookName, this.route.name);

    var opts;
    opts = this.route.options;
    var routeOptionHooks = toArray(opts && opts[hookName]);

    opts = this.options;
    var optionHooks = toArray(opts && opts[hookName]);

    var protoHooks = collectInheritedHooks(this.constructor);

    var objectHooks;
    // don't accidentally grab the prototype hooks!
    // this makes sure the hook is on the object itself
    // not on its constructor's prototype object.
    if (_.has(this, hookName))
      objectHooks = toArray(this[hookName])
    else
      objectHooks = [];

    var allHooks = optionHooks
      .concat(protoHooks)
      .concat(objectHooks)
      .concat(routeOptionHooks)
      .concat(routerHooks)
      .concat(more);

    var isPaused = false;
    var pauseFn = function () {
      isPaused = true;
    };

    for (var i = 0, hook; hook = allHooks[i]; i++) {
      var hookFn = lookupHook(hook);

      if (!isPaused && !this.isStopped)
        hookFn.call(self, pauseFn, i);
    }

    cb && cb.call(self, isPaused);
    return isPaused;
  },

  action: function () {
    throw new Error('not implemented');
  },

  stop: function (cb) {
    return this._stopController(cb);
  },

  _stopController: function (cb) {
    var self = this;

    if (this.isStopped)
      return;

    self.isRunning = false;
    self.runHooks('onStop');
    self.isStopped = true;
    cb && cb.call(self);
  },

  _run: function () {
    throw new Error('not implemented');
  }
};

_.extend(RouteController, {
  /**
   * Inherit from RouteController
   *
   * @param {Object} definition Prototype properties for inherited class.
   */

  extend: function (definition) {
    Utils.rewriteLegacyHooks(definition);

    return Utils.extend(this, definition, function (definition) {
      var klass = this;

      /*
        Allow calling a class method from javascript, directly in the subclass
        definition.

        Instead of this:
          MyController = RouteController.extend({...});
          MyController.before(function () {});

        You can do:
          MyController = RouteController.extend({
            before: function () {}
          });

        And in Coffeescript you can do:
         MyController extends RouteController
           @before function () {}
       */
    });
  }
});


text:
package br.com.cinema.converter;

public class Test {

}


text:
PROGRAM = a.out

# Linked libraries
LIBS =

# Flags
FLAGS = -MMD -g -Wall -pedantic-errors

# Directories
SRC = ./src/
OBJ = ./obj/
BIN = ./bin/

# Source files
PRELIMSOURCES=$(shell find $(SRC) -name '*.cpp')
SOURCES=$(PRELIMSOURCES:$(SRC)%=%)

# Object files that mirror the source files
OBJECTS=$(SOURCES:.cpp=.o)

# Prefixed Source files
PREFIXED_SOURCES=$(addprefix $(SRC),$(SOURCES))

# Prefixed Object files
PREFIXED_OBJECTS=$(addprefix $(OBJ),$(OBJECTS))

# Prefixed Program name
PREFIXED_PROGRAM=$(addprefix $(BIN),$(PROGRAM))

# Make 'all' instructions
all: $(PREFIXED_SOURCES) $(PREFIXED_PROGRAM)

# Make '$(PROGRAM)' instructions
$(PREFIXED_PROGRAM): $(PREFIXED_OBJECTS)
	@mkdir -p $(@D) # Makes the 'bin' directory if it doesn't exist
	$(CXX) $(PREFIXED_OBJECTS) -o $@ $(LIBS)

# Make '$(OBJECTS)' instructions
$(OBJ)%.o: $(SRC)%.cpp
	@mkdir -p $(@D) # Makes the directories if they don't exist
	$(CXX) -c $(FLAGS) $< -o $@ -std=c++0x

# Make 'clean' instructions
# 'dir' gets the directories of the object files
# 'sort' sorts the directories and removes duplicates
# 'add' is pretty self-explanatory
clean:
	rm -rf $(OBJ)
	rm -rf $(BIN)

# Include all of our dependency files, if they exist
-include $(addprefix $(OBJ),$(SOURCES:.cpp=.d))


text:
"use strict";

const repl = require('repl');

const CommandManager = require('./command_manager');
const Module = require('./api/module');

class RemoteManagement {
  constructor(container) {
    this.container = container;

    this.shutdownCallback = null;
  }

  start() {
    this.repl = require('repl').start('> ');
    this.initializeReplContext(this.repl.context);

    this.repl.on('reset', this.initializeReplContext.bind(this));
    this.repl.on('exit', this.shutdown.bind(this));
  }

  shutdown() {
    if (this.shutdownCallback) {
      this.shutdownCallback();
    }
  }

  stop() {
    if (this.repl) {
      this.repl.close();
    }
  }

  initializeReplContext(context) {
    context.Module = Module;
    context.CommandManager = CommandManager;

    context.QueueUtils = require('../queue/utils');

    context.main = this;
    context.container = this.container;
  }

  setShutdownCallback(cb) {
    this.shutdownCallback = cb;
  }
}

module.exports = RemoteManagement;


text:
namespace media {
namespace cast {

class MockCastTransport : public CastTransport {
 public:
  MockCastTransport();
  virtual ~MockCastTransport();

  MOCK_METHOD4(InitializeAudio,
               void(const CastTransportRtpConfig& config,
                    const RtcpCastMessageCallback& cast_message_cb,
                    const RtcpRttCallback& rtt_cb,
                    const RtcpPliCallback& pli_cb));
  MOCK_METHOD4(InitializeVideo,
               void(const CastTransportRtpConfig& config,
                    const RtcpCastMessageCallback& cast_message_cb,
                    const RtcpRttCallback& rtt_cb,
                    const RtcpPliCallback& pli_cb));
  MOCK_METHOD2(InsertFrame, void(uint32_t ssrc, const EncodedFrame& frame));
  MOCK_METHOD3(SendSenderReport,
               void(uint32_t ssrc,
                    base::TimeTicks current_time,
                    RtpTimeTicks current_time_as_rtp_timestamp));
  MOCK_METHOD2(CancelSendingFrames,
               void(uint32_t ssrc, const std::vector<uint32_t>& frame_ids));
  MOCK_METHOD2(ResendFrameForKickstart, void(uint32_t ssrc, uint32_t frame_id));
  MOCK_METHOD0(PacketReceiverForTesting, PacketReceiverCallback());
  MOCK_METHOD2(AddValidRtpReceiver,
               void(uint32_t rtp_sender_ssrc, uint32_t rtp_receiver_ssrc));
  MOCK_METHOD2(InitializeRtpReceiverRtcpBuilder,
               void(uint32_t rtp_receiver_ssrc, const RtcpTimeData& time_data));
  MOCK_METHOD2(AddCastFeedback,
               void(const RtcpCastMessage& cast_message,
                    base::TimeDelta target_delay));
  MOCK_METHOD1(AddPli, void(const RtcpPliMessage& pli_message));
  MOCK_METHOD1(
      AddRtcpEvents,
      void(const ReceiverRtcpEventSubscriber::RtcpEvents& rtcp_events));
  MOCK_METHOD1(AddRtpReceiverReport,
               void(const RtcpReportBlock& rtp_report_block));
  MOCK_METHOD0(SendRtcpFromRtpReceiver, void());
  MOCK_METHOD1(SetOptions, void(const base::DictionaryValue& options));
};

}  // namespace cast
}  // namespace media

#endif  // MEDIA_CAST_NET_MOCK_CAST_TRANSPORT_H_