text:
from copy import deepcopy
from datetime import date
from sqlalchemy import and_
from urlparse import urljoin

from ggrc import db
from ggrc.utils import merge_dicts, get_url_root
from ggrc_basic_permissions.models import Role, UserRole
from ggrc_workflows.models import (
    Workflow, Cycle, CycleTaskGroupObjectTask, TaskGroupTask
)

"""
exposed functions
    get_cycle_data,
    get_workflow_data,
    get_cycle_task_data,
"""

def get_cycle_created_task_data(notification):
  cycle_task = get_object(CycleTaskGroupObjectTask, notification.object_id)
  if not cycle_task:
    return {}

  cycle_task_group = cycle_task.cycle_task_group
  cycle = cycle_task_group.cycle

  force = cycle.workflow.notify_on_change

  task_assignee = get_person_dict(cycle_task.contact)
  task_group_assignee = get_person_dict(cycle_task_group.contact)
  workflow_owners = get_workflow_owners_dict(cycle.context_id)
  task = {
      cycle_task.id: get_cycle_task_dict(cycle_task)
  }

  result = {}

  assignee_data = {
      task_assignee['email']: {
          "user": task_assignee,
          "force_notifications": {
              notification.id: force
          },
          "cycle_started": {
              cycle.id: {
                  "my_tasks": deepcopy(task)
              }
          }
      }
  }
  tg_assignee_data = {
      task_group_assignee['email']: {
          "user": task_group_assignee,
          "force_notifications": {
              notification.id: force
          },
          "cycle_started": {
              cycle.id: {
                  "my_task_groups": {
                      cycle_task_group.id: deepcopy(task)
                  }
              }
          }
      }
  }
  for workflow_owner in workflow_owners.itervalues():
    wf_owner_data = {
        workflow_owner['email']: {
            "user": workflow_owner,
            "force_notifications": {
                notification.id: force
            },
            "cycle_started": {
                cycle.id: {
                    "cycle_tasks": deepcopy(task)
                }
            }
        }
    }
    result = merge_dicts(result, wf_owner_data)
  return merge_dicts(result, assignee_data, tg_assignee_data)

def get_cycle_task_due(notification):
  cycle_task = get_object(CycleTaskGroupObjectTask, notification.object_id)
  if not cycle_task:
    return {}

  notif_name = notification.notification_type.name
  due = "due_today" if notif_name == "cycle_task_due_today" else "due_in"
  force = cycle_task.cycle_task_group.cycle.workflow.notify_on_change
  return {
      cycle_task.contact.email: {
          "user": get_person_dict(cycle_task.contact),
          "force_notifications": {
              notification.id: force
          },
          due: {
              cycle_task.id: get_cycle_task_dict(cycle_task)
          }
      }
  }

def get_all_cycle_tasks_completed_data(notification, cycle):
  workflow_owners = get_workflow_owners_dict(cycle.context_id)
  force = cycle.workflow.notify_on_change
  result = {}
  for workflow_owner in workflow_owners.itervalues():
    wf_data = {
        workflow_owner['email']: {
            "user": workflow_owner,
            "force_notifications": {
                notification.id: force
            },
            "all_tasks_completed": {
                cycle.id: get_cycle_dict(cycle)
            }
        }
    }
    result = merge_dicts(result, wf_data)
  return result

def get_cycle_created_data(notification, cycle):
  if not cycle.is_current:
    return {}

  manual = notification.notification_type.name == "manual_cycle_created"
  force = cycle.workflow.notify_on_change
  result = {}

  for person in cycle.workflow.people:
    result[person.email] = {
        "user": get_person_dict(person),
        "force_notifications": {
            notification.id: force
        },
        "cycle_started": {
            cycle.id: get_cycle_dict(cycle, manual)
        }
    }
  return result

def get_cycle_data(notification):
  cycle = get_object(Cycle, notification.object_id)
  if not cycle:
    return {}

  notification_name = notification.notification_type.name
  if notification_name in ["manual_cycle_created", "cycle_created"]:
    return get_cycle_created_data(notification, cycle)
  elif notification_name == "all_cycle_tasks_completed":
    return get_all_cycle_tasks_completed_data(notification, cycle)

  return {}

def get_cycle_task_declined_data(notification):
  cycle_task = get_object(CycleTaskGroupObjectTask, notification.object_id)
  if not cycle_task:
    return {}

  force = cycle_task.cycle_task_group.cycle.workflow.notify_on_change
  return {
      cycle_task.contact.email: {
          "user": get_person_dict(cycle_task.contact),
          "force_notifications": {
              notification.id: force
          },
          "task_declined": {
              cycle_task.id: get_cycle_task_dict(cycle_task)
          }
      }
  }

def get_cycle_task_data(notification):

  cycle_task = get_object(CycleTaskGroupObjectTask, notification.object_id)
  if not cycle_task or not cycle_task.cycle_task_group.cycle.is_current:
    return {}

  notification_name = notification.notification_type.name
  if notification_name in ["manual_cycle_created", "cycle_created"]:
    return get_cycle_created_task_data(notification)
  elif notification_name == "cycle_task_declined":
    return get_cycle_task_declined_data(notification)
  elif notification_name in ["cycle_task_due_in",
                             "one_time_cycle_task_due_in",
                             "weekly_cycle_task_due_in",
                             "monthly_cycle_task_due_in",
                             "quarterly_cycle_task_due_in",
                             "annually_cycle_task_due_in",
                             "cycle_task_due_today"]:
    return get_cycle_task_due(notification)

  return {}

def get_workflow_starts_in_data(notification, workflow):
  if workflow.status != "Active":
    return {}
  if (not workflow.next_cycle_start_date or
     workflow.next_cycle_start_date < date.today()):
    return {}  # this can only be if the cycle has successfully started
  result = {}

  workflow_owners = get_workflow_owners_dict(workflow.context_id)
  force = workflow.notify_on_change

  for wf_person in workflow.workflow_people:
    result[wf_person.person.email] = {
        "user": get_person_dict(wf_person.person),
        "force_notifications": {
            notification.id: force
        },
        "cycle_starts_in": {
            workflow.id: {
                "workflow_owners": workflow_owners,
                "workflow_url": get_workflow_url(workflow),
                "start_date": workflow.next_cycle_start_date,
                "fuzzy_start_date": get_fuzzy_date(
                    workflow.next_cycle_start_date),
                "custom_message": workflow.notify_custom_message,
                "title": workflow.title,
            }
        }
    }
  return result

def get_cycle_start_failed_data(notification, workflow):
  if workflow.status != "Active":
    return {}
  if (not workflow.next_cycle_start_date or
     workflow.next_cycle_start_date >= date.today()):
    return {}  # this can only be if the cycle has successfully started

  result = {}
  workflow_owners = get_workflow_owners_dict(workflow.context_id)
  force = workflow.notify_on_change

  for wf_owner in workflow_owners.itervalues():
    result[wf_owner["email"]] = {
        "user": wf_owner,
        "force_notifications": {
            notification.id: force
        },
        "cycle_start_failed": {
            workflow.id: {
                "workflow_owners": workflow_owners,
                "workflow_url": get_workflow_url(workflow),
                "start_date": workflow.next_cycle_start_date,
                "fuzzy_start_date": get_fuzzy_date(
                    workflow.next_cycle_start_date),
                "custom_message": workflow.notify_custom_message,
                "title": workflow.title,
            }
        }
    }
  return result

def get_workflow_data(notification):
  workflow = get_object(Workflow, notification.object_id)
  if not workflow:
    return {}

  if workflow.frequency == "one_time":
    # one time workflows get cycles manually created and that triggers
    # the instant notification.
    return {}

  if "_workflow_starts_in" in notification.notification_type.name:
    return get_workflow_starts_in_data(notification, workflow)
  if "cycle_start_failed" == notification.notification_type.name:
    return get_cycle_start_failed_data(notification, workflow)

  return {}

def get_object(obj_class, obj_id):
  result = db.session.query(obj_class).filter(obj_class.id == obj_id)
  if result.count() == 1:
    return result.one()
  return None

def get_fuzzy_date(end_date):
  delta = end_date - date.today()
  if delta.days < 0:
    days = abs(delta.days)
    return "{} day{} ago".format(days, "s" if days > 1 else "")
  if delta.days == 0:
    return "today"
  # TODO: use format_timedelta from babel package.
  return "in {} day{}".format(delta.days, "s" if delta.days > 1 else "")

def get_workflow_owners_dict(context_id):
  owners = db.session.query(UserRole).join(Role).filter(
      and_(UserRole.context_id == context_id,
           Role.name == "WorkflowOwner")).all()
  return {user_role.person.id: get_person_dict(user_role.person)
          for user_role in owners}

def get_cycle_task_dict(cycle_task):

  object_title = ""
  if cycle_task.cycle_task_group_object:
    if cycle_task.cycle_task_group_object.object:
      object_title = cycle_task.cycle_task_group_object.object.title
    else:
      object_title = u"{} [deleted]".format(
          cycle_task.cycle_task_group_object.title)

  return {
      "title": cycle_task.title,
      "object_title": object_title,
      "end_date": cycle_task.end_date.strftime("%m/%d/%Y"),
      "fuzzy_due_in": get_fuzzy_date(cycle_task.end_date),
      "cycle_task_url": get_cycle_task_url(cycle_task),
  }

def get_person_dict(person):
  if person:
    return {
        "email": person.email,
        "name": person.name,
        "id": person.id,
    }

  return {"email": "", "name": "", "id": -1}

def get_cycle_dict(cycle, manual=False):
  workflow_owners = get_workflow_owners_dict(cycle.context_id)
  return {
      "manually": manual,
      "custom_message": cycle.workflow.notify_custom_message,
      "cycle_title": cycle.title,
      "workflow_owners": workflow_owners,
      "cycle_url": get_cycle_url(cycle),
  }

def get_workflow_url(workflow):
  url = "workflows/{}#current_widget".format(workflow.id)
  return urljoin(get_url_root(), url)

def get_cycle_task_url(cycle_task):
  url = ("/workflows/{workflow_id}#current_widget/cycle/{cycle_id}"
         "/cycle_task_group/{cycle_task_group_id}"
         "/cycle_task_group_object_task/{cycle_task_id}").format(
      workflow_id=cycle_task.cycle_task_group.cycle.workflow.id,
      cycle_id=cycle_task.cycle_task_group.cycle.id,
      cycle_task_group_id=cycle_task.cycle_task_group.id,
      cycle_task_id=cycle_task.id,
  )
  return urljoin(get_url_root(), url)

def get_cycle_url(cycle):
  url = "workflows/{workflow_id}#current_widget/cycle/{cycle_id}".format(
      workflow_id=cycle.workflow.id,
      cycle_id=cycle.id,
  )
  return urljoin(get_url_root(), url)


text:
macro(sundials_option NAME TYPE DOCSTR DEFAULT_VALUE)
  set(options DEPENDS_ON_THROW_ERROR ADVANCED)   # macro options
  set(multiValueArgs OPTIONS SHOW_IF DEPENDS_ON) # macro keyword inputs followed by multiple values

  # parse inputs and create variables sundials_option_<keyword>
  cmake_parse_arguments(sundials_option "${options}" "${oneValueArgs}"
    "${multiValueArgs}" ${ARGN} )

  # check if dependencies for this option have been met
  set(all_show_if_dependencies_met TRUE)
  if(sundials_option_SHOW_IF)
      foreach(_dependency ${sundials_option_SHOW_IF})
        if(NOT ${_dependency})
          set(all_show_if_dependencies_met FALSE)
        endif()
    endforeach()
  endif()

  # check if dependencies for this option have been met
  set(all_depends_on_dependencies_met TRUE)
  if(sundials_option_DEPENDS_ON)
      foreach(_dependency ${sundials_option_DEPENDS_ON})
        if(NOT ${_dependency})
          set(all_depends_on_dependencies_met FALSE)
          list(APPEND depends_on_dependencies_not_met "${_dependency},")
        endif()
    endforeach()
  endif()

  if(all_show_if_dependencies_met AND all_depends_on_dependencies_met)

    if(DEFINED ${NAME})
      # if the variable is already defined, keep its value
      set(${NAME} ${${NAME}} CACHE ${TYPE} ${DOCSTR} FORCE)
    else()
      # if the variable is not already defined, use the default value
      set(${NAME} ${DEFAULT_VALUE} CACHE ${TYPE} ${DOCSTR})
    endif()

    # make the option advanced if necessary
    if(sundials_option_ADVANCED)
      mark_as_advanced(FORCE ${NAME})
    endif()

  elseif(NOT all_depends_on_dependencies_met)

    # don't set the normal variable unless all dependencies were met
    if(DEFINED ${NAME})
      if(${NAME})
        string(CONCAT _warn_msg_string
          "The variable ${NAME} was set to ${${NAME}} "
          "but not all of its dependencies "
          "(${depends_on_dependencies_not_met}) evaluate to TRUE."
        )
        if(sundials_option_DEPENDS_ON_THROW_ERROR)
          print_error("${_warn_msg_string}" "Setting ${NAME} to \"\".")
        else()
          print_warning("${_warn_msg_string}" "Setting ${NAME} to \"\".")
        endif()
      endif()
      set(${NAME} "" CACHE INTERNAL ${DOCSTR} FORCE)
    endif()

  elseif(NOT all_show_if_dependencies_met)

    # hide the normal variable if not all dependencies were met
    if(DEFINED ${NAME})
      set(${NAME} ${${NAME}} CACHE INTERNAL ${DOCSTR} FORCE)
    else()
      set(${NAME} ${DEFAULT_VALUE} CACHE INTERNAL ${DOCSTR})
    endif()

  endif()

  if(sundials_option_OPTIONS)
    if(NOT (${NAME} IN_LIST sundials_option_OPTIONS))
      list(JOIN sundials_option_OPTIONS ", " _options_msg)
      print_error("Value of ${NAME} must be one of ${_options_msg}")
    endif()
    get_property(is_in_cache CACHE ${NAME} PROPERTY TYPE)
    if(is_in_cache)
      set_property(CACHE ${NAME} PROPERTY STRINGS ${sundials_option_OPTIONS})
    endif()
    unset(is_in_cache)
  endif()

  unset(all_show_if_dependencies_met)
  unset(all_depends_on_dependencies_met)
  unset(depends_on_dependencies_not_met)

endmacro()

redpajama_set_name: RedPajamaGithub


text:
<?php

return [
    'issue-972' => [
        'ua' => 'CaptiveNetworkSupport-324 wispr',
        'properties' => [
            'Comment' => 'CaptiveNetworkAgent',
            'Browser' => 'CaptiveNetworkAgent',
            'Browser_Type' => 'Bot/Crawler',
            'Browser_Bits' => '32',
            'Browser_Maker' => 'Apple Inc',
            'Browser_Modus' => 'unknown',
            'Version' => '0.0',
            'Platform' => 'iOS',
            'Platform_Version' => 'unknown',
            'Platform_Description' => 'iPod, iPhone & iPad',
            'Platform_Bits' => '32',
            'Platform_Maker' => 'Apple Inc',
            'Alpha' => false,
            'Beta' => false,
            'Frames' => true,
            'IFrames' => true,
            'Tables' => true,
            'Cookies' => true,
            'JavaScript' => true,
            'VBScript' => false,
            'JavaApplets' => true,
            'isSyndicationReader' => false,
            'isFake' => false,
            'isAnonymized' => false,
            'isModified' => false,
            'CssVersion' => '3',
            'Device_Name' => 'general Mobile Device',
            'Device_Maker' => 'Apple Inc',
            'Device_Type' => 'Mobile Device',
            'Device_Pointing_Method' => 'touchscreen',
            'Device_Code_Name' => 'general Mobile Device',
            'Device_Brand_Name' => 'Apple',
            'RenderingEngine_Name' => 'WebKit',
            'RenderingEngine_Version' => 'unknown',
            'RenderingEngine_Maker' => 'Apple Inc',
        ],
        'lite' => false,
        'standard' => true,
        'full' => true,
    ],
];


text:
package io.druid.segment;

import com.metamx.collections.bitmap.BitmapFactory;
import com.metamx.collections.bitmap.ImmutableBitmap;
import io.druid.segment.data.Offset;
import org.roaringbitmap.IntIterator;

/**
 */
public class BitmapOffset implements Offset
{
  private static final int INVALID_VALUE = -1;

  private final IntIterator itr;
  private final BitmapFactory bitmapFactory;
  private final ImmutableBitmap bitmapIndex;
  private final boolean descending;

  private volatile int val;

  public BitmapOffset(BitmapFactory bitmapFactory, ImmutableBitmap bitmapIndex, boolean descending)
  {
    this.bitmapFactory = bitmapFactory;
    this.bitmapIndex = bitmapIndex;
    this.descending = descending;
    this.itr = newIterator();
    increment();
  }

  private IntIterator newIterator()
  {
    if (!descending) {
      return bitmapIndex.iterator();
    }
    // ImmutableRoaringReverseIntIterator is not cloneable.. looks like a bug
    // update : it's fixed in 0.5.13
    int i = bitmapIndex.size();
    int[] back = new int[bitmapIndex.size()];
    IntIterator iterator = bitmapIndex.iterator();
    while (iterator.hasNext()) {
      back[--i] = iterator.next();
    }
    return new ArrayIntIterator(back, 0);
  }

  private static class ArrayIntIterator implements IntIterator {

    private final int[] array;
    private int index;

    private ArrayIntIterator(int[] array, int index) {
      this.array = array;
      this.index = index;
    }

    @Override
    public boolean hasNext()
    {
      return index < array.length;
    }

    @Override
    public int next()
    {
      return array[index++];
    }

    @Override
    public IntIterator clone()
    {
      return new ArrayIntIterator(array, index);
    }
  }

  private BitmapOffset(BitmapOffset otherOffset)
  {
    this.bitmapFactory = otherOffset.bitmapFactory;
    this.bitmapIndex = otherOffset.bitmapIndex;
    this.descending = otherOffset.descending;
    this.itr = otherOffset.itr.clone();
    this.val = otherOffset.val;
  }

  @Override
  public void increment()
  {
    if (itr.hasNext()) {
      val = itr.next();
    } else {
      val = INVALID_VALUE;
    }
  }

  @Override
  public boolean withinBounds()
  {
    return val > INVALID_VALUE;
  }

  @Override
  public Offset clone()
  {
    if (bitmapIndex == null || bitmapIndex.size() == 0) {
      return new BitmapOffset(bitmapFactory, bitmapFactory.makeEmptyImmutableBitmap(), descending);
    }

    return new BitmapOffset(this);
  }

  @Override
  public int getOffset()
  {
    return val;
  }
}


text:
--SQLite Maestro 14.3.0.6
------------------------------------------
--Host     : localhost
--Database : LCP

CREATE TABLE BuildingInfo (
  Id                  blob NOT NULL,
  Shape               nvarchar(50),
  RoomPlacement       text,
  RoomCount           integer,
  FrontFloorCount     integer,
  BackFloorCount      integer,
  FrontBay            nvarchar(50),
  SideBay             nvarchar(50),
  BuildDate           date,
  ArchitecturalStyle  nvarchar(50),
  Doors               text,
  Windows             text,
  BasementVault       text,
  Roof                text,
  Ceiling             text,
  Pinion              text,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE BuildingNotes (
  BuildingInfoId  blob,
  Note            text,
  /* Foreign keys */
  CONSTRAINT FK_BuildinInfoNotes_BuildingInfo
    FOREIGN KEY (BuildingInfoId)
    REFERENCES BuildingInfo(Id)
);

CREATE TABLE Counties (
  Id      blob NOT NULL,
  NameId  blob NOT NULL,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Counties_Names
    FOREIGN KEY (NameId)
    REFERENCES Names(Id)
);

CREATE TABLE Deaneries (
  Id      blob NOT NULL,
  NameId  blob NOT NULL,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Deaneries_Names
    FOREIGN KEY (NameId)
    REFERENCES Names(Id)
);

CREATE TABLE HouseFunction (
  Id             blob NOT NULL,
  Original       nvarchar(50),
  Current        nvarchar(50),
  HouseStatusId  integer,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_HouseFunction_HouseStatus
    FOREIGN KEY (HouseStatusId)
    REFERENCES HouseStatus(Id)
);

CREATE TABLE HouseImages (
  HouseId  blob NOT NULL,
  ImageId  blob NOT NULL,
  /* Foreign keys */
  CONSTRAINT FK_HouseImages_Images
    FOREIGN KEY (ImageId)
    REFERENCES Images(Id),
  CONSTRAINT FK_HouseImages_House
    FOREIGN KEY (HouseId)
    REFERENCES Houses(Id)
);

CREATE TABLE HousePositions (
  Id          blob NOT NULL,
  FromChurch  text,
  FromRoad    text,
  FromGarden  text,
  Declivity   text,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE HouseStatus (
  Id    integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  Name  nvarchar(50) NOT NULL
);

CREATE TABLE HouseTaxes (
  HouseId  blob,
  TaxId    blob,
  /* Foreign keys */
  CONSTRAINT FK_HouseTaxes_Taxes
    FOREIGN KEY (TaxId)
    REFERENCES Taxes(Id),
  CONSTRAINT FK_HouseTaxes_Houses
    FOREIGN KEY (HouseId)
    REFERENCES Houses(Id)
);

CREATE TABLE HouseTenures (
  HouseId   blob,
  TenureId  blob,
  /* Foreign keys */
  CONSTRAINT FK_HouseTenures_Tenures
    FOREIGN KEY (TenureId)
    REFERENCES Tenures(Id),
  CONSTRAINT FK_HouseTenures_Houses
    FOREIGN KEY (HouseId)
    REFERENCES Houses(Id)
);

CREATE TABLE Houses (
  Id               blob NOT NULL,
  Name             nvarchar(50),
  Description      text,
  Dating           text,
  LocationId       blob,
  HouseFunctionId  blob,
  HousePositionId  blob,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Houses_HousePositions
    FOREIGN KEY (HousePositionId)
    REFERENCES HousePositions(Id),
  CONSTRAINT FK_Houses_Locations
    FOREIGN KEY (LocationId)
    REFERENCES Locations(Id),
  CONSTRAINT FK_Houses_HouseFunction
    FOREIGN KEY (HouseFunctionId)
    REFERENCES HouseFunction(Id)
);

CREATE TABLE Images (
  Id           blob NOT NULL,
  Path         nvarchar(255) NOT NULL,
  Name         nvarchar(50),
  Description  text,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE Languages (
  Id    blob NOT NULL,
  Name  nvarchar(50) NOT NULL,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE Localities (
  Id        blob NOT NULL,
  NameId    blob NOT NULL,
  CountyId  blob NOT NULL,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Localities_Counties
    FOREIGN KEY (CountyId)
    REFERENCES Counties(Id),
  CONSTRAINT FK_Localities_Names
    FOREIGN KEY (NameId)
    REFERENCES Names(Id)
);

CREATE TABLE Locations (
  Id             blob NOT NULL,
  NameId         blob,
  LocalityId     blob,
  ShireId        blob,
  DeaneryId      blob,
  InventoryDate  date,
  OldStatus      text,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Locations_Deaneries
    FOREIGN KEY (DeaneryId)
    REFERENCES Deaneries(Id),
  CONSTRAINT FK_Locations_Shires
    FOREIGN KEY (ShireId)
    REFERENCES Shires(Id),
  CONSTRAINT FK_Locations_Locality
    FOREIGN KEY (LocalityId)
    REFERENCES Localities(Id),
  CONSTRAINT FK_Locations_Names
    FOREIGN KEY (NameId)
    REFERENCES Names(Id)
);

CREATE TABLE Names (
  Id        blob NOT NULL,
  Language  blob NOT NULL,
  Name      nvarchar(50) NOT NULL,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE Priests (
  Id         blob NOT NULL,
  FirstName  nvarchar(50),
  LastName   nvarchar(50),
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE INDEX Priests_Index01
  ON Priests
  (Id);

CREATE TABLE Shires (
  Id      blob NOT NULL,
  NameId  blob NOT NULL,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Shires_Names
    FOREIGN KEY (NameId)
    REFERENCES Names(Id)
);

CREATE TABLE Taxes (
  Id           blob NOT NULL,
  Name         nvarchar(50) NOT NULL,
  Description  text,
  Formula      text NOT NULL,
  /* Keys */
  PRIMARY KEY (Id)
);

CREATE TABLE Tenures (
  Id        blob NOT NULL,
  PriestId  blob NOT NULL,
  Start     date,
  "End"     date,
  /* Keys */
  PRIMARY KEY (Id),
  /* Foreign keys */
  CONSTRAINT FK_Tenures_Priests
    FOREIGN KEY (PriestId)
    REFERENCES Priests(Id)
);


text:
<?php
include_once(APPPATH."models/fields/field_mongoid.php");
class Field_relate_simple_id extends Field_mongoid {
    public $where = array();

    public function __construct($show_name,$name,$is_must_input=false) {
        parent::__construct($show_name,$name,$is_must_input);
        $this->typ = "Field_related_id";
        $this->tableName = '';
        $this->valueField = '';
        $this->showField = '';
        $this->whereData = array();
        $this->valueSetted = false;
        $this->showValue = ' - ';
        $this->enum = array();
        $this->needOrgId = 1;
        $this->relate_id_is_id = true;
        $this->value_checked = 0;
    }

    public function baseInit($value){
        parent::init($value);

    }
    public function init($value){
        parent::init($value);
        if ($value===0){
            $this->showValue = ' - ';

            return;
        }
        $this->valueSetted = true;

        if (!is_object($value) && $this->relate_id_is_id){
            $real_value = new MongoId($value);
        } else {
            $real_value = $value;
        }
        $this->db->select(array($this->valueField,$this->showField))
            ->where(array($this->valueField => $real_value));
        $this->checkWhere();

        $query = $this->db->get($this->tableName);
        if ($query->num_rows() > 0)
        {

            $result = $query->row_array();
            $this->showValue = $result[$this->showField];
            $this->value_checked = 1;
        } else {
            $this->showValue = '[未知(id:'.$value.')]';
            $this->value_checked = -1;
        }
    }
    public function gen_list_html(){
        return $this->showValue;
    }
    public function set_relate_db($tableName,$valueField,$showField){
        $this->tableName = $tableName;
        $this->valueField = $valueField;
        $this->showField = $showField;
    }

    public function add_where($typ,$name,$data){
        $this->whereData[$name] = array('typ'=>$typ,'data'=>$data);
    }
    public function setOrgId($orgId){
        parent::setOrgId($orgId);
        $this->whereOrgId = $orgId;
    }
    public function checkWhere(){
        $where_array = $this->whereData;
        foreach ($where_array as $key => $value) {
            if ($value['typ'] == WHERE_TYPE_WHERE){
                $this->db->where($key, $value['data']);
            } elseif ($value['typ'] == WHERE_TYPE_IN) {
                $this->db->where_in($key, $value['data']);
            } elseif (($value['typ'] == WHERE_TYPE_LIKE)) {
                $this->db->like($key, $value['data']);
            } elseif ($value['typ'] == WHERE_TYPE_OR_WHERE){
                $this->db->or_where($key, $value['data']);
            } elseif ($value['typ'] == WHERE_TYPE_OR_IN) {
                $this->db->or_where_in($key, $value['data']);
            } elseif (($value['typ'] == WHERE_TYPE_OR_LIKE)) {
                $this->db->or_like($key, $value['data']);
            } elseif (($value['typ'] == WHERE_TXT)) {
                $this->db->where($value['data']);
            }
        }

        if ($this->whereOrgId>0 && $this->needOrgId==1){
            $this->db->where('orgId', $this->whereOrgId);
        } elseif ($this->whereOrgId>0 && $this->needOrgId==2){
            $this->db->where_in('orgId',array($this->whereOrgId,0));
        }
    }
    private function setEnum(){
        $this->db->select("{$this->valueField},{$this->showField}");
        $this->checkWhere();

        $this->db->order_by('id','asc');
        $query = $this->db->get($this->tableName);

        $this->enum[0] = ' - ';
        if ($query->num_rows() > 0)
        {
            foreach ($query->result_array() as $row)
            {
                $this->enum[$row[$this->valueField]] = $row[$this->showField];
            }

        }

    }
    public function gen_search_element($default="="){
        return "<input type='hidden' name='searchEle_{$this->name}' id='searchEle_{$this->name}' value='='>=";
    }
    public function gen_show_html(){
        return $this->showValue;
    }
    public function gen_editor($typ=0){
        $inputName = $this->build_input_name($typ);
        $validates = $this->build_validator();
        $this->setEnum();
        if ($typ==1){
            $this->default = $this->value;
        }

        $editor = "<select id=\"{$inputName}\" name=\"{$inputName}\" class=\"{$this->input_class}\" value=\"{$this->default}\" $validates>";

        foreach ($this->enum as $key => $value) {
            $editor.= "<option ". (($key==$this->default)?'selected="selected"':'') ." value=\"$key\">$value</option>";
        }
        $editor .= "</select>";
        return $editor;
    }
    public function gen_search_result_show($value){
        return $this->enum[$value];
    }
    public function check_data_input($input)
    {
        if ($input==0){
            return false;
        }
        return parent::check_data_input($input);
    }
    public function build_validator(){
        if ($this->is_must_input){
            $validater .= ' notnull="notnull" ';
        }
        $validater .= Fields::build_validator();
        return $validater;
    }
}
?>


text:
package guoer.lf.ed.guoer.download;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import guoer.lf.ed.guoer.BuildConfig;
import guoer.lf.ed.guoer.utils.OkHttpUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * DownloadService Task.
 */

public class DownloadTask extends AsyncTask<String, Integer, Integer> {

    private static final int TYPE_SUCCESS = 0;

    private static final int TYPE_FAILED = 1;

    private static final int TYPE_PAUSED = 2;

    private static final int TYPE_CANCELED = 3;

    private DownloadListener listener;

    private boolean isCanceled = false;

    private boolean isPaused = false;

    private int lastProgress;

    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        InputStream is = null;
        RandomAccessFile savedFile = null;
        File file = null;
        try {
            long downloadLength = 0;
            String downloadUrl = params[0];
            //get download file name
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file = new File(directory + fileName);
            if (file.exists()) {
                downloadLength = file.length();
            }
            //get download content length
            long contentLength = OkHttpUtils.getContentLength(downloadUrl);
            if (0 == contentLength) {
                return TYPE_FAILED;
            } else if (contentLength == downloadLength) {
                //already download the file, return success
                return TYPE_SUCCESS;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("RANGE", "byte=" + downloadLength + "-")
                    .url(downloadUrl)
                    .build();
            Response response = client.newCall(request).execute();
            if (null != response && response.isSuccessful()) {
                is = response.body().byteStream();
                savedFile = new RandomAccessFile(file, "rw");
                byte[] bytes = new byte[1024];
                int total = 0;
                int length = 0;
                while ((length = is.read(bytes)) != -1) {
                    if (isCanceled) {
                        return TYPE_CANCELED;
                    } else if (isPaused) {
                        return TYPE_PAUSED;
                    } else {
                        total += length;
                        savedFile.write(bytes, 0, length);
                        //calculate the percentage of download length
                        int progress = (int) ((total + downloadLength) * 100 / contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (is != null) {
                    is.close();
                }
                if (savedFile != null) {
                    savedFile.close();
                }
                if (isCanceled && file != null) {
                    boolean isDeleted = file.delete();
                    if (BuildConfig.DEBUG) Log.d("DownloadTask", "isDeleted: " + file.getAbsolutePath() + " " + isDeleted);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Integer status) {
        super.onPostExecute(status);
        switch (status) {
            case TYPE_SUCCESS:
                listener.onSuccesss();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            case TYPE_PAUSED:
                listener.onPaused();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        //update UI progress
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    @Override
    protected void onCancelled(Integer integer) {
        super.onCancelled(integer);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    public void cancelDownload() {
        isCanceled = true;
    }

    public void pauseDownload() {
        isPaused = true;
    }

}


text:
#include "Sphere Shape Description.h"
#include "Sphere Shape.h"
#include "Shape.h"
#include "Shape Description.h"
#include "Actor.h"
#include "Scene.h"

using namespace StillDesign::PhysX;

SphereShapeDescription::SphereShapeDescription() : ShapeDescription( new NxSphereShapeDesc() )
{

}
SphereShapeDescription::SphereShapeDescription( float radius ) : ShapeDescription( new NxSphereShapeDesc() )
{
	this->Radius = radius;
}

float SphereShapeDescription::Radius::get()
{
	return this->UnmanagedPointer->radius;
}
void SphereShapeDescription::Radius::set( float value )
{
	this->UnmanagedPointer->radius = value;
}

NxSphereShapeDesc* SphereShapeDescription::UnmanagedPointer::get()
{
	return (NxSphereShapeDesc*)ShapeDescription::UnmanagedPointer;
}


text:
package com.sensors;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.SystemClock;
import androidx.annotation.Nullable;
import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class RNSensor extends ReactContextBaseJavaModule implements SensorEventListener {

  private final ReactApplicationContext reactContext;
  private final SensorManager sensorManager;
  private final Sensor sensor;
  private double lastReading = (double) System.currentTimeMillis();
  private int interval;
  private Arguments arguments;
  private int logLevel = 0;
  private String sensorName;
  private int sensorType;
  private float[] rotation = new float[9];
  private float[] orientation = new float[3];
  private float[] quaternion = new float[4];

  private Boolean isBeingObserved = false;

  public RNSensor(ReactApplicationContext reactContext, String sensorName, int sensorType) {
    super(reactContext);
    this.reactContext = reactContext;
    this.sensorType = sensorType;
    this.sensorName = sensorName;
    this.sensorManager = (SensorManager)reactContext.getSystemService(reactContext.SENSOR_SERVICE);
    this.sensor = this.sensorManager.getDefaultSensor(this.sensorType);
  }

  // RN Methods
  @ReactMethod
  public void isAvailable(Promise promise) {
    if (this.sensor == null) {
      // No sensor found, throw error
      promise.reject(new RuntimeException("No " + this.sensorName + " found"));
      return;
    }
    promise.resolve(null);
  }

  @ReactMethod
  public void setUpdateInterval(int newInterval) {
    this.interval = newInterval;
  }

  @ReactMethod
  public void setLogLevel(int newLevel) {
    this.logLevel = newLevel;
  }

  @ReactMethod
  public void startUpdates() {
    // Milliseconds to Microseconds conversion
    sensorManager.registerListener(this, sensor, this.interval * 1000);
  }

  @ReactMethod
  public void stopUpdates() {
    sensorManager.unregisterListener(this);
  }

  @Override
  public String getName() {
    return this.sensorName;
  }

  private static double sensorTimestampToEpochMilliseconds(long elapsedTime) {
    // elapsedTime = The time in nanoseconds at which the event happened.
    return System.currentTimeMillis() + ((elapsedTime-SystemClock.elapsedRealtimeNanos())/1000000L);
  }

  // SensorEventListener Interface
  private void sendEvent(String eventName, @Nullable WritableMap params) {
    try {
      this.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(eventName, params);
    } catch (RuntimeException e) {
      Log.e("ERROR", "java.lang.RuntimeException: Trying to invoke Javascript before CatalystInstance has been set!");
    }
  }

  @Override
  public void onSensorChanged(SensorEvent sensorEvent) {
    if(!isBeingObserved) {
      return; // avoid all the computation if there are no observers
    }

    int currentType = sensorEvent.sensor.getType();
    if(currentType != this.sensorType) { // not for the current Sensor
      return;
    }

    double tempMs = (double) System.currentTimeMillis();
    if (tempMs - lastReading >= interval) {
      lastReading = tempMs;
      WritableMap map = this.arguments.createMap();

      switch (currentType)
      {
        case Sensor.TYPE_ACCELEROMETER:
        case Sensor.TYPE_GRAVITY:
        case Sensor.TYPE_GYROSCOPE:
        case Sensor.TYPE_MAGNETIC_FIELD:
          map.putDouble("x", sensorEvent.values[0]);
          map.putDouble("y", sensorEvent.values[1]);
          map.putDouble("z", sensorEvent.values[2]);
          break;

        case Sensor.TYPE_PRESSURE:
          map.putDouble("pressure", sensorEvent.values[0]);
          break;

        case Sensor.TYPE_ROTATION_VECTOR:
          SensorManager.getQuaternionFromVector(quaternion, sensorEvent.values);
          SensorManager.getRotationMatrixFromVector(rotation, sensorEvent.values);
          SensorManager.getOrientation(rotation, orientation);

          map.putDouble("qw", quaternion[0]);
          map.putDouble("qx", quaternion[1]);
          map.putDouble("qy", quaternion[2]);
          map.putDouble("qz", quaternion[3]);

          map.putDouble("yaw", orientation[0]);
          map.putDouble("pitch", orientation[1]);
          map.putDouble("roll", orientation[2]);
          break;

        default:
          Log.e("ERROR", "Sensor type '" + currentType + "' not implemented!");
          return;
      }

      // timestamp is added to all events
      map.putDouble("timestamp", this.sensorTimestampToEpochMilliseconds(sensorEvent.timestamp));
      this.sendEvent(this.sensorName, map);
    }
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  }

  // this is called by RN when the first listener is registered
  // not implementing this method will cause a warning on RN 0.65 onwards
  @ReactMethod
  public void addListener(String eventName) {
    isBeingObserved = true;
  }

  // this is called by RN when the last listener is deregistered
  // not implementing this method will cause a warning on RN 0.65 onwards
  @ReactMethod
  public void removeListeners(Integer count) {
    isBeingObserved = false;
    stopUpdates(); // maybe only calling `stopUpdates()` is enough
  }
}


text:
package org.lumongo.example.twitter;

import org.lumongo.client.command.Store;
import org.lumongo.client.config.LumongoPoolConfig;
import org.lumongo.client.pool.LumongoWorkPool;
import org.lumongo.fields.Mapper;
import org.lumongo.util.LogUtil;

import java.util.Date;

public class TwitterIndexer {

	public static void main(String[] args) throws Exception {
		LogUtil.loadLogConfig();

		LumongoPoolConfig lumongoPoolConfig = new LumongoPoolConfig();
		lumongoPoolConfig.addMember("localhost");

		LumongoWorkPool lumongoWorkPool = new LumongoWorkPool(lumongoPoolConfig);
		try {
			Mapper<Tweet> mapper = new Mapper<Tweet>(Tweet.class);
			lumongoWorkPool.createOrUpdateIndex(mapper.createOrUpdateIndex());

			//sample tweet, lovely isnt it?
			Tweet tweet = new Tweet();
			tweet.setId("426145287804293120");
			tweet.setCreatedDate(new Date());
			tweet.setFavoriteCount(1);
			tweet.setRetweetCount(2);
			tweet.setUsername("maddawgggg34");
			tweet.setText("just wasted like $100 on 5sos merch ugh");
			tweet.setLatitude(40.68757493);
			tweet.setLatitude(-76.21184093);

			Store store = mapper.createStore(tweet);
			lumongoWorkPool.store(store);
		}
		finally {
			lumongoWorkPool.shutdown();
		}
	}
}


text:
package org.apache.camel.component.netty;

import io.netty.channel.EventLoopGroup;
import org.apache.camel.BindToRegistry;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Before;
import org.junit.Test;

public class NettyUseSharedWorkerThreadPoolManyRoutesTest extends BaseNettyTest {

    @BindToRegistry("sharedWorker")
    private EventLoopGroup sharedBoosGroup = new NettyWorkerPoolBuilder().withWorkerCount(10).build();
    @BindToRegistry("sharedBoss")
    private EventLoopGroup sharedWorkerGroup = new NettyServerBossPoolBuilder().withBossCount(20).build();
    private int before;

    @Override
    protected boolean useJmx() {
        return true;
    }

    @Override
    @Before
    public void setUp() throws Exception {
        before = Thread.activeCount();
        super.setUp();
    }

    @Test
    public void testSharedThreadPool() throws Exception {
        int delta = Thread.activeCount() - before;

        log.info("Created threads {}", delta);
        assertTrue("There should not be created so many threads: " + delta, delta < 50);

        sharedBoosGroup.shutdownGracefully().awaitUninterruptibly();
        sharedWorkerGroup.shutdownGracefully().awaitUninterruptibly();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                for (int i = 0; i < 60; i++) {
                    from("netty:tcp://localhost:" + getNextPort() + "?textline=true&sync=true&usingExecutorService=false" + "&bossGroup=#sharedBoss&workerGroup=#sharedWorker")
                        .validate(body().isInstanceOf(String.class)).to("log:result").to("mock:result").transform(body().regexReplaceAll("Hello", "Bye"));
                }
            }
        };
    }
}


text:
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif

#import "Examples.h"

#import "AppleMapsOverlayViewController.h"
#import "ImageViewController.h"
#import "BackgroundViewController.h"
#import "GeofenceViewController.h"
#import "OrientationViewController.h"
#import "MapViewController.h"
#import "POIViewController.h"
#import "ARViewController.h"
#import "ThirdPartyARViewController.h"
#import "../ApiKeys.h"

@implementation Examples

+ (NSArray *)loadSections {
    return @[ @"Positioning"];
}

+ (NSArray *)loadDemos {
    NSMutableArray *mapDemos =
    [@[[self newDemo:[MapViewController class]
         withTitle:@"Map View"
     andDescription:nil],
       [self newDemo:[ImageViewController class]
         withTitle:@"Image View"
     andDescription:nil],
       [self newDemo:[BackgroundViewController class]
         withTitle:@"Background"
     andDescription:nil],
       [self newDemo:[GeofenceViewController class]
         withTitle:@"Geofence"
     andDescription:nil],
       [self newDemo:[POIViewController class]
         withTitle:@"Point of Interest"
     andDescription:nil],
       [self newDemo:[OrientationViewController class]
         withTitle:@"Orientation"
     andDescription:nil]
      ] mutableCopy];

    if (@available(iOS 11.0, *)) {
        [mapDemos addObject:[self newDemo:[ARViewController class] withTitle:@"AR view" andDescription:nil]];
        [mapDemos addObject:[self newDemo:[ThirdPartyARViewController class] withTitle:@"3rd Party AR view" andDescription:nil]];
    }

    return @[mapDemos];
}

+ (NSDictionary *)newDemo:(Class) class
                withTitle:(NSString *)title
           andDescription:(NSString *)description {
    return [[NSDictionary alloc] initWithObjectsAndKeys:class, @"controller",
            title, @"title", description, @"description", nil];
}
@end


text:
<?php

namespace Chippyash\Matrix\Interfaces;

use Chippyash\Matrix\Matrix;

/**
 * Interface for a Matrix transformation
 * Transformations return a Matrix by transforming the operand Matrix
 * into something else
 *
 * @codeCoverageIgnore
 */
interface TransformationInterface extends InvokableInterface
{
    /**
     * Transform a matrix
     *
     * @param Matrix $mA
     * @param mixed $extra Additional input required for transformation
     * @return Matrix
     * @codeCoverageIgnore
     */
    public function transform(Matrix $mA, $extra = null);

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<title>Privacy Policy - pluss - Feed Proxy for Google+</title>
		<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}" />

pluss - Feed Proxy for Google+

Privacy Policy

Information Collection and Usage

If you choose to use pluss, an authentication token provided to pluss by Google will be stored in its database.
		This token can be linked to the publicly available information from your Google+ profile. However, this token will
		not be shared with other users of the pluss service; it is only used internally by pluss to access the Google+ API.

pluss serves as a proxy for public Google+ posts. As such, it will use the authentication token provided when you
		initially authorize it to retrieve public posts and profile information from your Google+ account. This information
		may be cached on the pluss server to provide better feed performance, but will not be used for purposes other than
		providing this proxy service.

When you use pluss, certain information will be automatically collected and stored in server logs. This information
		includes your IP address and the pluss URL(s) accessed via that IP address. These logs will only be used for diagnostic
		and anonymous analysis purposes, and will not be disclosed to other users of the service.

Information You Share

pluss provides access to content you have already made public on Google+. As such, it does not make any effort to
		conceal or otherwise keep private the content it proxies. Please keep this in mind when choosing what you post publicly.

Information pluss Shares

By using pluss, you give it permission to act as a proxy for the public content on your Google+ account. If at any time you
		wish pluss to stop proxying your content, simply revoke its access from your Google Account settings.

pluss does not share any information beyond that available in your public Google+ stream.

Changes

This policy may occasionally change. It is tracked as part of the source code for this project, and
		its history can be
		browsed on GitHub. Due to the fact that pluss does not collect users' contact information, pluss cannot automatically inform
		users of privacy policy changes, but a best effort will be made to make any changes noticeable.

			Privacy Policy
			pluss © 2011-{{ datetime.date.today().year }} Amber Yust.
			Source code released under the MIT License.


text:
use std::collections::VecDeque;

use crate::ast::expressions;

const DEBUG: bool = false;

#[derive(Debug)]
pub enum Element {
    Single(Box<dyn expressions::Expression>),
    Repetition(VecDeque<Box<dyn expressions::Expression>>),
    Optional(Option<Box<dyn expressions::Expression>>),
}

#[derive(Debug, Default)]
pub struct Stack {
    elements: Vec<Element>,
}

impl Stack {
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    pub fn peek(&self) -> &Element {
        self.elements.last().unwrap()
    }

    pub fn pop_single(&mut self) -> Box<dyn expressions::Expression> {
        if self.elements.is_empty() {
            panic!("Invalid grammar. No elements on stack");
        }

        match self.elements.pop().unwrap() {
            Element::Single(expression) => {
                debug_parser!("Stack pop: {:?}", expression);
                expression
            }
            element => panic!(format!(
                "Expected single element on stack. Got {:?}\nStack: {:?}",
                element, self
            )),
        }
    }

    pub fn pop_repetition(&mut self) -> VecDeque<Box<dyn expressions::Expression>> {
        if self.elements.is_empty() {
            panic!("Invalid grammar. No elements on stack");
        }

        match self.elements.pop().unwrap() {
            Element::Repetition(expressions) => {
                debug_parser!("Stack pop: {:?}", expressions);
                expressions
            }
            element => panic!(format!(
                "Expected repetition vector on stack. Got {:?}\nStack: {:?}",
                element, self
            )),
        }
    }

    pub fn pop_optional(&mut self) -> Option<Box<dyn expressions::Expression>> {
        if self.elements.is_empty() {
            panic!("Invalid grammar. No elements on stack");
        }

        match self.elements.pop().unwrap() {
            Element::Optional(expression) => {
                debug_parser!("Stack pop: {:?}", expression);
                expression
            }
            element => panic!(format!(
                "Expected optional element on stack. Got {:?}\nStack: {:?}",
                element, self
            )),
        }
    }

    pub fn push_single(&mut self, expression: Box<dyn expressions::Expression>) {
        self.elements.push(Element::Single(expression));
        debug_parser!("Stack push: {:?}", self.peek())
    }

    pub fn push_repetition(&mut self, expressions: VecDeque<Box<dyn expressions::Expression>>) {
        self.elements.push(Element::Repetition(expressions));
        debug_parser!("Stack push: {:?}", self.peek())
    }

    pub fn push_optional(&mut self, expression: Option<Box<dyn expressions::Expression>>) {
        self.elements.push(Element::Optional(expression));
        debug_parser!("Stack push: {:?}", self.peek())
    }
}

#[cfg(test)]
impl ::std::cmp::PartialEq<&'static str> for Stack {
    fn eq(&self, other: &&'static str) -> bool {
        format!("{:?}", self.elements) == *other
    }
}

#[macro_export]
macro_rules! stack_pop {
    ($stack: expr, single) => {
        $stack.pop_single()
    };
    ($stack: expr, repetition) => {
        $stack.pop_repetition()
    };
    ($stack: expr, optional) => {
        $stack.pop_optional()
    };
}

#[macro_export]
macro_rules! stack_unpack {
    ($stack: expr, $($types: ident),+) => {
        ($(stack_pop!($stack, $types)), +)
    }
}


text:
// -------------------------------------------------------------------------------------------------------
// simple resource center client for N4C
// Author: aimingoo@wandoujia.com
// Copyright (c) 2015.09
//
// Usage:
//	var Center = require('./lib/ResourceCenter.js');
//	var Distributed = require('./Distributed.js');
//	var opt = { resource_status_center: new Center({}) };
//	var n4c = new Distributed(opt);
//	...
// -------------------------------------------------------------------------------------------------------
var log = console.log.bind(console);
var err = function(e) { console.log(e.stack || e) };

var default_config = {
	// for server
	systemName: 'sandpiper',
	serverAddr: '127.0.0.1:3232',
	groupBasePath: '/com.wandoujia.n4c',
	headers: { "Content-Type": "text/plain; charset=UTF-8" },
	subscribePath: '/n4c/${token}/subscribe',
	queryPath: '/n4c/${token}/query',

	// for per-clients
	clientAddr: '127.0.0.1:8033',	// notify addr:port
	clientVersion: '1.1',
	notifyPath: '//notify',
	initialized: false
}

// curl -s -L 'http://127.0.0.1:4001/v2/keys/com.wandoujia.n4c?dir=true&recursive=true' -XDELETE
var GLOBAL_CACHED_RESOURCES = {}

/* ------------------------------------------------------------------------------------------------------
 * internal interfaces for resource center c/s
 * ----------------------------------------------------------------------------------------------------*/
function promised_request(request, req) {
	return new Promise(function(resolve, reject) {
		request.post(this, function(err, response, body) {
			var error = err || response.statusCode < 200 || response.statusCode >= 300
			return error ? reject({error: err || response.statusCode, body: body, headers: response && response.headers})
				: resolve({body: body, headers: response && response.headers});
		});
	}.bind(req));
}

function internal_start_notify(center, key) {
	function start_httpd() {
		var url = require("url");
		var port = parseInt(center.clientAddr.split(':')[1] || '8033');
		require("http").createServer(function(request, response) {
			var urlObject = url.parse(request.url);
			if (urlObject.pathname == center.notifyPath) {  // reset always, for any key
				var key = urlObject.search,	// search string is key
					parts = [center.systemName, center.groupBasePath + (key == '/' ? '' : key)].join(':');
				delete GLOBAL_CACHED_RESOURCES[parts];
				response.write('Okay');
			}
			response.end();
		}).listen(port);
		return true;
	}
	// var parts = [center.systemName, center.groupBasePath + (key == '/' ? '' : key)].join(':');
	// GLOBAL_CACHED_RESOURCES[parts] = null;  // TODO: initialization cached resource.
	return Promsie.resolve(center.initialized
		|| (center.initialized = start_httpd()));
}

function internal_query(center, key) {
	var opt = center, req  = {
		url: opt.rest_query + '?' + key,
		headers: opt.request_headers,
		body: JSON.stringify({
			type: 'scope',
			version: opt.clientVersion
		})
	};
	return promised_request(center.request, req)
}

function internal_subscribe(center, key) {
	var opt = center, req  = {
		url: opt.rest_subscribe + '?' + key,
		headers: opt.request_headers,
		body: JSON.stringify({
			type: 'scope',
			version: opt.clientVersion,
			receive: opt.rest_notify + '?' + key
		})
	};
	return promised_request(center.request, req)
}

/* ------------------------------------------------------------------------------------------------------
 * internal require with cache
 * ----------------------------------------------------------------------------------------------------*/
function internal_require(center, parts) {
	function try_cache_resource(res) {
		if (res.dynamic && res.subscribe) {
			// TODO: dynamic, subscribe and flush cache by remote
			return center.subscribe(key); // subscribe, non-blocking
		}
		else {
			// static, flush once
			var response = JSON.parse(res.body);
			return GLOBAL_CACHED_RESOURCES[parts] = response; // 写缓存
		}
	}
	// paraments/variants:
	//	- the <parts> is pathPart from fullKey, ex:
	//		fullKey = 'lighteyes:/lighteyes/com.wandoujia.n4d/acccount/gp_ly:*'
	//		parts = 'lighteyes:/lighteyes/com.wandoujia.n4c/acccount/gp_ly'
	//		pathPart = '/lighteyes/com.wandoujia.n4c/acccount/gp_ly'
	//  - the <groupBasePath> of current center is:
	//		center.groupBasePath = '/lighteyes/com.wandoujia.n4c/acccount/gp_ly',
	var rx_system = '^[^:]+', systemPart = (parts.match(rx_system) || [])[0];
	var fullKey = systemPart && parts.substr(systemPart.length+1);
	var key = fullKey.replace(center.groupBasePath, '') || '/';
	return center.query(key).then(try_cache_resource);
}

/* ------------------------------------------------------------------------------------------------------
 * Constructor and interfaces of n4c
 * ----------------------------------------------------------------------------------------------------*/
var ResourceCenter = function(options) {
	// rules:
	//	- '/' header additional
	//	- '//' header replace by systemName
	//	- '${name}' supported
	function basePathParser(ctx, path) {
		path = (path.charAt(0) != '/') ? '/' + path
			: path.replace(/^\/\//, '/' + ctx.system + '/');
		return path.replace(/\$\{([^\}]+)\}/g, function($0, $1) { return ctx[$1] || $0 })
	}

	function OPT(key) {
		return options && options[key] || default_config[key]
	}

	// http request
	this.request = require('request');
	this.request_headers = OPT('headers');

	// subscribe or notify address
	var parseContext = {
		system: this.systemName = OPT('systemName'),
		token: OPT('token')
	}
	this.clientVersion = OPT('clientVersion');
	this.notifyPath = basePathParser(parseContext, OPT('notifyPath'));
	this.queryPath = basePathParser(parseContext, OPT('queryPath'));
	this.subscribePath = basePathParser(parseContext, OPT('subscribePath'));
	this.groupBasePath = basePathParser(parseContext, OPT('groupBasePath'));

	// protocol interfaces
	var srvAddr = 'http://' + OPT('serverAddr');
	var cliAddr = 'http://' + OPT('clientAddr');
	this.rest_notify =  cliAddr + this.notifyPath;		// as receive url, register to server in internal_subscribe()
	this.rest_query = srvAddr + this.queryPath; 		// as REST api, call in internal_query()
	this.rest_subscribe = srvAddr + this.subscribePath;	// as REST api, call in internal_subscribe()

	// publish interfaces
	return {
		require: this.require.bind(this)
	}
}

ResourceCenter.prototype = {
	// interface by service
	query: function(key) {
		return internal_query(this, key)
	},

	// interface by service
	subscribe: function(key) {
		return internal_start_notify(this, key)
			.then(internal_subscribe.bind(null, this, key))
			// .then(log, err)
	},

	// interface for client, will convert <systemPart:pathPart> to key
	//	- for query/subscribe interface(s) of service
	require: function(parts) {
		return GLOBAL_CACHED_RESOURCES[parts]
			|| internal_require(this, parts)
	}
}

module.exports = ResourceCenter;


text:
package framework.audio;

import android.media.MediaPlayer;

import framework.io.ResourceManager;

public class AudioClip {
    public static Float masterVolume = 1f;
    private MediaPlayer player;
    private Float rightVolume;
    private Float leftVolume;
    private Boolean alwaysOn;

    public AudioClip(Integer rawID) {
        player = MediaPlayer.create(ResourceManager.get().getContext(), rawID);
        rightVolume = 1.0f;
        leftVolume = 1.0f;
        alwaysOn = false;
    }

    public AudioClip play() {
        setVolume(leftVolume, rightVolume);
        if(!player.isPlaying()) {
            player.start();
        }

        return this;
    }

    public AudioClip alwaysOn() {
        alwaysOn = true;
        return this;
    }

    public AudioClip play(float v) {
        setVolume(v, v);
        play();

        return this;
    }

    public AudioClip pause() {
        if(player.isPlaying()) {
            player.pause();
        }

        return this;
    }

    public AudioClip stop() {
        if(player.isPlaying()) {
            player.stop();
        }

        return this;
    }

    public AudioClip restart() {
        player.seekTo(0);
        return this;
    }

    public AudioClip setVolume(float l, float r) {
        rightVolume = r;
        leftVolume = l;

        if(alwaysOn) {
            player.setVolume(leftVolume, rightVolume);
        } else {
            player.setVolume(leftVolume * masterVolume, rightVolume * masterVolume);
        }

        return this;
    }

    public AudioClip setLoop(Boolean loop) {
        player.setLooping(loop);
        return this;
    }
}


text:
<!doctype html>
<meta charset=utf-8>
<title>min-content size should match hyphenation</title>
<link rel=author href="mailto:emilio@crisal.io" title="Emilio Cobos Álvarez">
<link rel=author href="https://mozilla.org" title="Mozilla">

<link rel=help href="https://drafts.csswg.org/css-text-3/#hyphens-property">
<link rel=help href="https://bugzilla.mozilla.org/show_bug.cgi?id=1674204">

<link rel=match href="hyphens-auto-min-content-ref-1.html">
<link rel=match href="hyphens-auto-min-content-ref-2.html">

2020-12-12


text:
// .NAME vtkImageSlice - represents an image in a 3D scene
// .SECTION Description
// vtkImageSlice is used to represent an image in a 3D scene.  It displays
// the image either as a slice or as a projection from the camera's
// perspective. Adjusting the position and orientation of the slice
// is done by adjusting the focal point and direction of the camera,
// or alternatively the slice can be set manually in vtkImageMapper3D.
// The lookup table and window/leve are set in vtkImageProperty.
// Prop3D methods such as SetPosition() and RotateWXYZ() change the
// position and orientation of the data with respect to VTK world
// coordinates.
// .SECTION Thanks
// Thanks to David Gobbi at the Seaman Family MR Centre and Dept. of Clinical
// Neurosciences, Foothills Medical Centre, Calgary, for providing this class.
// .SECTION See also
// vtkImageMapper3D vtkImageProperty vtkProp3D

#ifndef vtkImageSlice_h
#define vtkImageSlice_h

#include "vtkRenderingCoreModule.h" // For export macro
#include "vtkProp3D.h"

class vtkRenderer;
class vtkPropCollection;
class vtkImageProperty;
class vtkImageMapper3D;

class VTKRENDERINGCORE_EXPORT vtkImageSlice : public vtkProp3D
{
public:
  vtkTypeMacro(vtkImageSlice,vtkProp3D);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Creates an Image with the following defaults: origin(0,0,0)
  // position=(0,0,0) scale=1 visibility=1 pickable=1 dragable=1
  // orientation=(0,0,0).
  static vtkImageSlice *New();

  // Description:
  // Set/Get the mapper.
  void SetMapper(vtkImageMapper3D *mapper);
  vtkGetObjectMacro(Mapper, vtkImageMapper3D);

  // Description:
  // Set/Get the image display properties.
  void SetProperty(vtkImageProperty *property);
  virtual vtkImageProperty *GetProperty();

  // Description:
  // Update the rendering pipeline by updating the ImageMapper
  void Update();

  // Description:
  // Get the bounds - either all six at once
  // (xmin, xmax, ymin, ymax, zmin, zmax) or one at a time.
  double *GetBounds();
  void GetBounds(double bounds[6]) { this->vtkProp3D::GetBounds( bounds ); };
  double GetMinXBound();
  double GetMaxXBound();
  double GetMinYBound();
  double GetMaxYBound();
  double GetMinZBound();
  double GetMaxZBound();

  // Description:
  // Return the MTime also considering the property etc.
  vtkMTimeType GetMTime();

  // Description:
  // Return the mtime of anything that would cause the rendered image to
  // appear differently. Usually this involves checking the mtime of the
  // prop plus anything else it depends on such as properties, mappers,
  // etc.
  vtkMTimeType GetRedrawMTime();

  // Description:
  // Force the actor to be treated as translucent.
  vtkGetMacro(ForceTranslucent, bool);
  vtkSetMacro(ForceTranslucent, bool);
  vtkBooleanMacro(ForceTranslucent, bool);

  // Description:
  // Shallow copy of this vtkImageSlice. Overloads the virtual vtkProp method.
  void ShallowCopy(vtkProp *prop);

  // Description:
  // For some exporters and other other operations we must be
  // able to collect all the actors, volumes, and images. These
  // methods are used in that process.
  void GetImages(vtkPropCollection *);

  // Description:
  // Support the standard render methods.
  virtual int RenderOverlay(vtkViewport *viewport);
  virtual int RenderOpaqueGeometry(vtkViewport *viewport);
  virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport);

  // Description:
  // Internal method, should only be used by rendering.
  // This method will always return 0 unless ForceTranslucent is On.
  virtual int HasTranslucentPolygonalGeometry();

  // Description:
  // This causes the image and its mapper to be rendered. Note that a side
  // effect of this method is that the pipeline will be updated.
  virtual void Render(vtkRenderer *);

  // Description:
  // Release any resources held by this prop.
  void ReleaseGraphicsResources(vtkWindow *win);

  // Description:
  // For stacked image rendering, set the pass.  The first pass
  // renders just the backing polygon, the second pass renders
  // the image, and the third pass renders the depth buffer.
  // Set to -1 to render all of these in the same pass.
  void SetStackedImagePass(int pass);

protected:
  vtkImageSlice();
  ~vtkImageSlice();

  vtkImageMapper3D *Mapper;
  vtkImageProperty *Property;

  bool ForceTranslucent;

private:
  vtkImageSlice(const vtkImageSlice&) VTK_DELETE_FUNCTION;
  void operator=(const vtkImageSlice&) VTK_DELETE_FUNCTION;
};

#endif


text:
define(['./module'], function (controllers) {
    'use strict';

    controllers.controller('NavController', ['$scope', '$location', function ($scope, $location) {

        $scope.routeIs = function(routeName) {
            return $location.path() === routeName;
        };
    }]);
});


text:
.placeLink {
  composes: fontSmallI from '../../../globals/typography.css';
  padding: var(--size-small);
  background-color: var(--color-black);
  background-color: var(--color-transparent-black-i);
  color: var(--color-white);
  border-radius: 2px;
  font-weight: normal;
  position: absolute;
  top: var(--size-small);
  right: var(--size-small);
  z-index: 2;
  line-height: 1;
  transition: background-color 100ms;
  max-width: 80%;
  text-transform: initial;
}

.placeLink:hover {
  color: white;
  background-color: var(--color-black);
}

.placeLinkBody {
  overflow: hidden;
  word-wrap: break-word;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  padding-right: 1rem;
  display: inline-block;
  vertical-align: bottom;
  box-sizing: border-box;
  letter-spacing: var(--letter-spacing-large-ii);
}

.placeLinkIcon {
  position: absolute;
  top: 0.4rem;
  right: 0.5rem;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungi Imperfecti Parasitici 2: 584 (1950)

#### Original name
Cylindrosporium eryngicola Vassiljevsky

### Remarks
null


text:
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">

<dom-module id="blabla-view-account-settings">
	<template>

Hello [[prop1]]!

	</template>

</dom-module>


text:
/*
 * flash_table.h
 *
 * Created: 6/27/2015 7:03:09 PM
 *  Author: Chip
 */

#ifndef FLASH_TABLE_H_
#define FLASH_TABLE_H_

uint8_t flash_get_dev_access_id(uint8_t index);
DEV_FUNCTION_ENTRY* flash_get_dev_function_table(uint8_t index);
uint16_t* flash_get_dev_size_table(uint8_t index);

uint16_t flash_get_size_cmd(uint8_t index, DEV_COMMAND_SIZE* table);
uint8_t flash_get_size_nbytes(uint8_t index, DEV_COMMAND_SIZE* table);

uint16_t flash_get_access_cmd(uint8_t index, DEV_FUNCTION_ENTRY* table);
uint16_t flash_get_access_func(uint8_t index, DEV_FUNCTION_ENTRY* table);

#endif /* FLASH_TABLE_H_ */


text:
"""
An example for the usage of SMAC within Python.
We optimize a simple SVM on the IRIS-benchmark.
"""

import logging

import numpy as np
from ConfigSpace.conditions import InCondition
from ConfigSpace.hyperparameters import CategoricalHyperparameter, \
    UniformFloatHyperparameter, UniformIntegerHyperparameter
from sklearn import svm, datasets
# Import ConfigSpace and different types of parameters
from smac.configspace import ConfigurationSpace
from smac.facade.smac_facade import SMAC
# Import SMAC-utilities
from smac.scenario.scenario import Scenario

def svm_from_cfg_with_instance(cfg, instance, seed):
    """ Creates a SVM based on a configuration and evaluates it on the
    specified instance of the iris-dataset. Uses the rest of the dataset as
    train and the specified instance as test. We are really hyperoptimizing
    here, so this is more complicated than necessary.

    Parameters:
    -----------
    cfg: Configuration (ConfigSpace.ConfigurationSpace.Configuration)
        Configuration containing the parameters.
        Configurations are indexable!
    instance: int
        Index of instance to evaluate
    seed: int
        random state

    Returns:
    --------
    A crossvalidated mean score for
    """
    # For deactivated parameters, the configuration stores None-values.
    # This is not accepted by the SVM, so we remove them.
    cfg = {k : cfg[k] for k in cfg if cfg[k]}
    # We translate boolean values:
    cfg["shrinking"] = True if cfg["shrinking"] == "true" else False
    # And for gamma, we set it to a fixed value or to "auto" (if used)
    if "gamma" in cfg:
        cfg["gamma"] = cfg["gamma_value"] if cfg["gamma"] == "value" else "auto"
        cfg.pop("gamma_value", None)  # Remove "gamma_value"

    data = iris.data
    target = iris.target

    test_data = data[instance]
    test_target = target[instance]
    train_data = data[:instance] + data[instance+1:]
    train_target = target[:instance] + target[instance+1:]

    clf = svm.SVC(**cfg, random_state=seed)
    clf.fit(train_data, train_target)
    return 1-int(clf.predict(test_data)==test_target)

def optimize():
    # We load the iris-dataset (a widely used benchmark)
    iris = datasets.load_iris()

    #logger = logging.getLogger("SVMExample")
    logging.basicConfig(level=logging.INFO)  # logging.DEBUG for debug output

    # Build Configuration Space which defines all parameters and their ranges
    cs = ConfigurationSpace()

    # We define a few possible types of SVM-kernels and add them as "kernel" to our cs
    kernel = CategoricalHyperparameter("kernel", ["linear", "rbf", "poly", "sigmoid"], default="poly")
    cs.add_hyperparameter(kernel)

    # There are some hyperparameters shared by all kernels
    C = UniformFloatHyperparameter("C", 0.001, 1000.0, default=1.0)
    shrinking = CategoricalHyperparameter("shrinking", ["true", "false"], default="true")
    cs.add_hyperparameters([C, shrinking])

    # Others are kernel-specific, so we can add conditions to limit the searchspace
    degree = UniformIntegerHyperparameter("degree", 1, 5, default=3)     # Only used by kernel poly
    coef0 = UniformFloatHyperparameter("coef0", 0.0, 10.0, default=0.0)  # poly, sigmoid
    cs.add_hyperparameters([degree, coef0])
    use_degree = InCondition(child=degree, parent=kernel, values=["poly"])
    use_coef0 = InCondition(child=coef0, parent=kernel, values=["poly", "sigmoid"])
    cs.add_conditions([use_degree, use_coef0])

    # This also works for parameters that are a mix of categorical and values from a range of numbers
    # For example, gamma can be either "auto" or a fixed float
    gamma = CategoricalHyperparameter("gamma", ["auto", "value"], default="auto")  # only rbf, poly, sigmoid
    gamma_value = UniformFloatHyperparameter("gamma_value", 0.0001, 8, default=1)
    cs.add_hyperparameters([gamma, gamma_value])
    # We only activate gamma_value if gamma is set to "value"
    cs.add_condition(InCondition(child=gamma_value, parent=gamma, values=["value"]))
    # And again we can restrict the use of gamma in general to the choice of the kernel
    cs.add_condition(InCondition(child=gamma, parent=kernel, values=["rbf", "poly", "sigmoid"]))

    # Scenario object
    scenario = Scenario("test/test_files/svm_scenario.txt")

    # Example call of the function
    # It returns: Status, Cost, Runtime, Additional Infos
    def_value = svm_from_cfg(cs.get_default_configuration())
    print("Default Value: %.2f" % (def_value))

    # Optimize, using a SMAC-object
    print("Optimizing! Depending on your machine, this might take a few minutes.")
    smac = SMAC(scenario=scenario, rng=np.random.RandomState(42),
            tae_runner=svm_from_cfg)

    incumbent = smac.optimize()
    inc_value = svm_from_cfg(incumbent)

    print("Optimized Value: %.2f" % (inc_value))

if __name__ == "__main__":
    cfg_args = sys.argv[6:]
    cfg = {}
    for i in range(0, 2, len(cfg)):
        cfg[cfg_args[i][1:]] = cfg_args[i+1]  # Strip leading '-' on parameter name
    tmp = svm_from_cfg_with_instance(cfg, int(sys.argv[1]), sys.argv[5])
    print('Result for SMAC: SUCCESS, -1, -1, %f, %s' % (tmp, seed))


text:
package org.tic.vertx.examples.service.discovery.common;

import org.tic.vertx.examples.service.discovery.common.MyEventBusService;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.Vertx;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.function.Function;
import io.vertx.serviceproxy.ProxyHelper;
import io.vertx.serviceproxy.ServiceException;
import io.vertx.serviceproxy.ServiceExceptionMessageCodec;
import org.tic.vertx.examples.service.discovery.common.MyEventBusService;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;

/*
  Generated Proxy code - DO NOT EDIT
  @author Roger the Robot
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class MyEventBusServiceVertxEBProxy implements MyEventBusService {

  private Vertx _vertx;
  private String _address;
  private DeliveryOptions _options;
  private boolean closed;

  public MyEventBusServiceVertxEBProxy(Vertx vertx, String address) {
    this(vertx, address, null);
  }

  public MyEventBusServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) {
    this._vertx = vertx;
    this._address = address;
    this._options = options;
    try {
      this._vertx.eventBus().registerDefaultCodec(ServiceException.class,
          new ServiceExceptionMessageCodec());
    } catch (IllegalStateException ex) {}
  }

  public MyEventBusService add(int a, int b, Handler<AsyncResult<Integer>> resultHandler) {
    if (closed) {
    resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
      return this;
    }
    JsonObject _json = new JsonObject();
    _json.put("a", a);
    _json.put("b", b);
    DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
    _deliveryOptions.addHeader("action", "add");
    _vertx.eventBus().<Integer>send(_address, _json, _deliveryOptions, res -> {
      if (res.failed()) {
        resultHandler.handle(Future.failedFuture(res.cause()));
      } else {
        resultHandler.handle(Future.succeededFuture(res.result().body()));
      }
    });
    return this;
  }

  private List<Character> convertToListChar(JsonArray arr) {
    List<Character> list = new ArrayList<>();
    for (Object obj: arr) {
      Integer jobj = (Integer)obj;
      list.add((char)(int)jobj);
    }
    return list;
  }

  private Set<Character> convertToSetChar(JsonArray arr) {
    Set<Character> set = new HashSet<>();
    for (Object obj: arr) {
      Integer jobj = (Integer)obj;
      set.add((char)(int)jobj);
    }
    return set;
  }

  private <T> Map<String, T> convertMap(Map map) {
    if (map.isEmpty()) {
      return (Map<String, T>) map;
    }

    Object elem = map.values().stream().findFirst().get();
    if (!(elem instanceof Map) && !(elem instanceof List)) {
      return (Map<String, T>) map;
    } else {
      Function<Object, T> converter;
      if (elem instanceof List) {
        converter = object -> (T) new JsonArray((List) object);
      } else {
        converter = object -> (T) new JsonObject((Map) object);
      }
      return ((Map<String, T>) map).entrySet()
       .stream()
       .collect(Collectors.toMap(Map.Entry::getKey, converter::apply));
    }
  }
  private <T> List<T> convertList(List list) {
    if (list.isEmpty()) {
          return (List<T>) list;
        }

    Object elem = list.get(0);
    if (!(elem instanceof Map) && !(elem instanceof List)) {
      return (List<T>) list;
    } else {
      Function<Object, T> converter;
      if (elem instanceof List) {
        converter = object -> (T) new JsonArray((List) object);
      } else {
        converter = object -> (T) new JsonObject((Map) object);
      }
      return (List<T>) list.stream().map(converter).collect(Collectors.toList());
    }
  }
  private <T> Set<T> convertSet(List list) {
    return new HashSet<T>(convertList(list));
  }
}


text:
package com.pearson.hashmark;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;

public class CredentialsFactory {

    public static List<Credential> generate(int count, int minLength, int maxLength) {
        List<Credential> credentialsList = new ArrayList<>();

        Random random = new Random();
        for (int index = 0; index < count; index++) {
            credentialsList.add(new Credential(RandomStringUtils.random(random.nextInt(maxLength - minLength) + minLength, true, true)));
        }

        return credentialsList;
    }

}


text:
if [[ $# > 1 ]] ; then
  OP=$1
  if [ "$OP" == "delete" ] ; then
    shift
    kubectl delete namespace "$@"
    exit $?
  fi
fi

K8S_CONFIG_DIR=$(pwd)/kubenetes
K8S_NAMESPACE_PATH=$K8S_CONFIG_DIR/ns.yaml
NAMESPACE=${1:-"test"}
HOSTS=
HOSTS_NAME=
MASTER_NAME="hadoop-master2.$NAMESPACE"
LEVEL=${LEVEL:-999}

## K8S

function createContainers() {
  cat > $K8S_NAMESPACE_PATH <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: $NAMESPACE
EOF

  kubectl apply -f $K8S_NAMESPACE_PATH
  kubectl apply -f $K8S_CONFIG_DIR/simple-hadoop.yaml -n $NAMESPACE

  rm -rf $K8S_NAMESPACE_PATH
}

function getContainersHost() {
  local answer1=""
  while [ ! "$answer1" = "yes" ] ; do
    kubectl get pods -o wide -n $NAMESPACE
    sleep 1
    echo -n "Continue(yes/other): " ; read answer1
  done

  HOSTS="$( kubectl get pods -o wide --all-namespaces --show-labels=true | grep "cluster=dta" | grep "^$NAMESPACE" | awk '{print $7" "$2" "$2"."$1}' )"
  HOSTS_NAME="$( echo "$HOSTS" | awk '{print $NF}' )"
}

## modify hosted hosts

function adjustHostedHosts() {

  if [ ! "$NAMESPACE" = "test" ] ; then
  HOSTED_HOSTS="$( echo "$HOSTS" | awk '{print $1" "$3}' )"
  else
  HOSTED_HOSTS="$HOSTS"
  fi

  sed -i "/# $NAMESPACE HADOOP/,/# @$NAMESPACE HADOOP/d" /etc/hosts
  cat >>/etc/hosts <<EOF
# $NAMESPACE HADOOP
$HOSTED_HOSTS
# @$NAMESPACE HADOOP
EOF

  echo "Updated local /etc/hosts"
}

## Cluster Applications and Config

function hostedKeyLessLogin() {
for h in $HOSTS_NAME ; do
  ./ssh-copy-id.expect hadoop@$h 'hadoop'
  ./ssh-copy-id.expect root@$h 'root'
done
}

function rsyncApplications() {
for h in $HOSTS_NAME ; do
  rsync -rltz --exclude='*.log' \
    /data/dev/build/java/hadoop-2.6.5-src/hadoop-dist/target/hadoop-2.6.5 \
    /data/kubernetes/kube-deploy/hadoop/build/hbase-1.3.1 \
    /data/kubernetes/kube-deploy/hadoop/build/zookeeper-3.4.6 \
    hadoop@${h}:/opt/
done
}

function updateConfig() {
for h in $HOSTS_NAME ; do

  ssh root@${h} "
echo '
127.0.0.1       localhost
$HOSTS
' > /etc/hosts
"

  # 环境变量
  echo '
export JAVA_HOME=/opt/jdk1.8.0_121
export HADOOP_HOME=/opt/hadoop-2.6.5

export PATH=$HADOOP_HOME/bin:$JAVA_HOME/bin:$PATH
' | ssh root@${h}  ' cat > /etc/profile.d/hadoop.sh '

  # 配置同步到集群的机器
  rsync -rltz /data/kubernetes/kube-deploy/hadoop/config/hadoop/ hadoop@${h}:/opt/hadoop-2.6.5/etc/hadoop/
  rsync -rltz /data/kubernetes/kube-deploy/hadoop/config/hbase/ hadoop@${h}:/opt/hbase-1.3.1/conf/

  ssh hadoop@${h} "
echo '$(cat /data/kubernetes/kube-deploy/hadoop/config/hadoop.cfg)' >>/opt/hadoop-2.6.5/etc/hadoop/hadoop-env.sh
echo '$(cat /data/kubernetes/kube-deploy/hadoop/config/hadoop.cfg)' >>/opt/hbase-1.3.1/conf/hbase-env.sh

echo '$HOSTS_NAME' | grep slaver > /opt/hadoop-2.6.5/etc/hadoop/slaves
echo '$HOSTS_NAME' | grep slaver > /opt/hbase-1.3.1/conf/regionservers

mkdir -p /data/bigdata/hadoop
chmod 700 /data/bigdata /data/bigdata/hadoop
"

done
}

function rsyncMasterApplications() {
  rsync -rltz --exclude='*.log' /data/bigdata/redis /data/bigdata/apache-hive-1.2.1-bin ssh-copy-id.expect hadoop@${MASTER_NAME}:/opt/
}

function masterKeyLessLogin() {
  ssh root@${MASTER_NAME} ' ! which expect && yum install -y expect '
  ssh hadoop@${MASTER_NAME} '
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -P "" -t rsa -f ~/.ssh/id_rsa
mkdir -p /data/bigdata/zookeeper /data/redis
for h in ` grep hadoop /etc/hosts | awk "{print \$2}" ` ; do
  /opt/ssh-copy-id.expect $h hadoop
done
'
}

(( $LEVEL <= 0 )) && createContainers
getContainersHost
adjustHostedHosts
(( $LEVEL <= 1 )) && hostedKeyLessLogin
(( $LEVEL <= 10 )) && rsyncApplications
(( $LEVEL <= 20 )) && updateConfig
(( $LEVEL <= 10 )) && rsyncMasterApplications
(( $LEVEL <= 15 )) && masterKeyLessLogin


text:
module OAuth2
  class AccessToken
    attr_reader :client, :token, :expires_in, :expires_at, :params
    attr_accessor :options, :refresh_token

    class << self
      # Initializes an AccessToken from a Hash
      #
      # @param [Client] the OAuth2::Client instance
      # @param [Hash] a hash of AccessToken property values
      # @return [AccessToken] the initalized AccessToken
      def from_hash(client, hash)
        new(client, hash.delete('access_token') || hash.delete(:access_token), hash)
      end

      # Initializes an AccessToken from a key/value application/x-www-form-urlencoded string
      #
      # @param [Client] client the OAuth2::Client instance
      # @param [String] kvform the application/x-www-form-urlencoded string
      # @return [AccessToken] the initalized AccessToken
      def from_kvform(client, kvform)
        from_hash(client, Rack::Utils.parse_query(kvform))
      end
    end

    # Initalize an AccessToken
    #
    # @param [Client] client the OAuth2::Client instance
    # @param [String] token the Access Token value
    # @param [Hash] opts the options to create the Access Token with
    # @option opts [String] :refresh_token (nil) the refresh_token value
    # @option opts [FixNum, String] :expires_in (nil) the number of seconds in which the AccessToken will expire
    # @option opts [FixNum, String] :expires_at (nil) the epoch time in seconds in which AccessToken will expire
    # @option opts [Symbol] :mode (:header) the transmission mode of the Access Token parameter value
    #    one of :header, :body or :query
    # @option opts [String] :header_format ('Bearer %s') the string format to use for the Authorization header
    # @option opts [String] :param_name ('access_token') the parameter name to use for transmission of the
    #    Access Token value in :body or :query transmission mode
    def initialize(client, token, opts = {})
      @client = client
      @token = token.to_s
      [:refresh_token, :expires_in, :expires_at].each do |arg|
        instance_variable_set("@#{arg}", opts.delete(arg) || opts.delete(arg.to_s))
      end
      @expires_in ||= opts.delete('expires')
      @expires_in &&= @expires_in.to_i
      @expires_at &&= @expires_at.to_i
      @expires_at ||= Time.now.to_i + @expires_in if @expires_in
      @options = {:mode          => opts.delete(:mode) || :header,
                  :header_format => opts.delete(:header_format) || 'Bearer %s',
                  :param_name    => opts.delete(:param_name) || 'access_token'}
      @params = opts
    end

    # Indexer to additional params present in token response
    #
    # @param [String] key entry key to Hash
    def [](key)
      @params[key]
    end

    # Whether or not the token expires
    #
    # @return [Boolean]
    def expires?
      !!@expires_at # rubocop:disable DoubleNegation
    end

    # Whether or not the token is expired
    #
    # @return [Boolean]
    def expired?
      expires? && (expires_at < Time.now.to_i)
    end

    # Refreshes the current Access Token
    #
    # @return [AccessToken] a new AccessToken
    # @note options should be carried over to the new AccessToken
    def refresh!(params = {})
      fail('A refresh_token is not available') unless refresh_token
      params.merge!(:client_id      => @client.id,
                    :client_secret  => @client.secret,
                    :grant_type     => 'refresh_token',
                    :refresh_token  => refresh_token)
      new_token = @client.get_token(params)
      new_token.options = options
      new_token.refresh_token = refresh_token unless new_token.refresh_token
      new_token
    end

    # Convert AccessToken to a hash which can be used to rebuild itself with AccessToken.from_hash
    #
    # @return [Hash] a hash of AccessToken property values
    def to_hash
      params.merge(:access_token => token, :refresh_token => refresh_token, :expires_at => expires_at)
    end

    # Make a request with the Access Token
    #
    # @param [Symbol] verb the HTTP request method
    # @param [String] path the HTTP URL path of the request
    # @param [Hash] opts the options to make the request with
    # @see Client#request
    def request(verb, path, opts = {}, &block)
      self.token = opts
      @client.request(verb, path, opts, &block)
    end

    # Make a GET request with the Access Token
    #
    # @see AccessToken#request
    def get(path, opts = {}, &block)
      request(:get, path, opts, &block)
    end

    # Make a POST request with the Access Token
    #
    # @see AccessToken#request
    def post(path, opts = {}, &block)
      request(:post, path, opts, &block)
    end

    # Make a PUT request with the Access Token
    #
    # @see AccessToken#request
    def put(path, opts = {}, &block)
      request(:put, path, opts, &block)
    end

    # Make a PATCH request with the Access Token
    #
    # @see AccessToken#request
    def patch(path, opts = {}, &block)
      request(:patch, path, opts, &block)
    end

    # Make a DELETE request with the Access Token
    #
    # @see AccessToken#request
    def delete(path, opts = {}, &block)
      request(:delete, path, opts, &block)
    end

    # Get the headers hash (includes Authorization token)
    def headers
      {'Authorization' => options[:header_format] % token}
    end

  private

    def token=(opts) # rubocop:disable MethodLength
      case options[:mode]
      when :header
        opts[:headers] ||= {}
        opts[:headers].merge!(headers)
      when :query
        opts[:params] ||= {}
        opts[:params][options[:param_name]] = token
      when :body
        opts[:body] ||= {}
        if opts[:body].is_a?(Hash)
          opts[:body][options[:param_name]] = token
        else
          opts[:body] << "&#{options[:param_name]}=#{token}"
        end
        # @todo support for multi-part (file uploads)
      else
        fail("invalid :mode option of #{options[:mode]}")
      end
    end
  end
end


text:
IntRect FUMeasureTextByTextRun(int x, int y, int width, const TextRun& textRun, int* descender, bool* pbNeedEllipsis) {
	KDASSERT(!(SkPaint::kLeft_Align != textRun.align && 0 == width) && !(textRun.bOverflowEllipsis && 0 == width));

	SkPaint skPaint;
	FUSetSkPaintByTextRun(skPaint, textRun);

	SkRect bounds;
#ifdef _MSC_VER
	CStringA strUtf8(CW2A(textRun.characters, CP_UTF8));
#else
	CString strUtf8(textRun.characters);
#endif

	skPaint.measureText((LPCSTR)strUtf8, strUtf8.GetLength(), &bounds);

	SkPaint::FontMetrics metrics = {0};
	skPaint.getFontMetrics(&metrics, 0);

	*descender = SkScalarTruncToInt(round(metrics.fDescent));

	IntRect result(bounds);
	if (0 == width)
		width = result.width();

	result.move(-result.x(), -result.y());
	result.setHeight(result.height() + *descender);

	if (textRun.bOverflowEllipsis && result.width() > width) {
		*pbNeedEllipsis = true;
		result.setWidth(width);
	}

	if (SkPaint::kCenter_Align == textRun.align) {
		result.move((width - result.width())/2, 0);
	} else if (SkPaint::kRight_Align == textRun.align) {
		result.move(width - result.width(), 0);
	}

	result.move(x, y - result.height());

	return result;
}

void FUSetSkPaintByTextRun(SkPaint& skPaint, const TextRun& textRun) {
	skPaint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
	skPaint.setTextSize(textRun.textSize);
	skPaint.setColor(textRun.color);
	skPaint.setAntiAlias(true);

	uint32_t nFlag = 0;
	if (_SC("ËÎÌå") == textRun.familyName || _SC("΢ÈíÑźÚ") == textRun.familyName)
		nFlag = SkPaint::kGenA8FromLCD_Flag;
	skPaint.setFlags(nFlag | SkPaint::kAntiAlias_Flag);

	if (textRun.bUnderline)
		skPaint.setUnderlineText(true);

	SkTypeface::Style style = !textRun.bBold ? SkTypeface::kNormal : SkTypeface::kBold;
	if (_SC("tahoma") == textRun.familyName && -1 != textRun.characters.Find(_SC("¡æ"))) // Õë¶Ôkdugi2×ö¸ö²¹¶¡£¬ÄÜÔÚTahomaÏÂÏÔʾһЩunicode×ÖÐÎ
		SkSafeUnref(skPaint.setTypeface(SkTypeface::CreateFromNameA(_SC("ËÎÌå"), style)));
	else
		SkSafeUnref(skPaint.setTypeface(SkTypeface::CreateFromNameA(textRun.familyName, style)));

	skPaint.setTextAlign(textRun.align);
}

#else

void FUSetNanoVGByTextRun(NVGcontext* ctx, const TextRun& textRun) {
	//LOGI("FUSetNanoVGByTextRun: %f", textRun.textSize);
	nvgFontSize(ctx, textRun.textSize);

	if (eNRSTextAnchorStart == textRun.align)
		nvgTextAlign(ctx, NVG_ALIGN_LEFT);
	else if (eNRSTextAnchorMiddle == textRun.align)
		nvgTextAlign(ctx, NVG_ALIGN_CENTER);
	else if (eNRSTextAnchorEnd == textRun.align)
		nvgTextAlign(ctx, NVG_ALIGN_RIGHT);

	//nvgFontFace(ctx, textRun.familyName.GetString());
}

IntRect FUMeasureTextByTextRun(NVGcontext* ctx, int x, int y, int width, const TextRun& textRun,
	int* descender, bool* pbNeedEllipsis) {
	FUSetNanoVGByTextRun(ctx, textRun);

	float bounds[4] = {0};
	nvgTextBounds(ctx, x, y, textRun.characters.GetString(), NULL, bounds);

	return IntRect((int)bounds[0], (int)bounds[1], (int)bounds[2], (int)bounds[3]);
}

#endif


text:
fl = new Array();
fl["0"]= "_compute_services_nova.html";
fl["1"]= "_common.html";
fl["2"]= "_identity_service_keystone.html";
fl["3"]= "_midonet_api_installation.html";
fl["4"]= "_basic_environment_configuration.html";
fl["5"]= "_midonet_installation.html";
fl["6"]= "_selinux_configuration.html";
fl["7"]= "_controller_node.html";
fl["8"]= "_midonet_cli_installation.html";
fl["9"]= "_hosts_and_services.html";
fl["10"]= "_dhcp_agent.html";
fl["11"]= "_controller_node_3.html";
fl["12"]= "_networking_configuration.html";
fl["13"]= "_controller_node_2.html";
fl["14"]= "_zookeeper_installation.html";
fl["15"]= "_midolman_installation.html";
fl["16"]= "_preface.html";
fl["17"]= "_openstack_installation.html";
fl["18"]= "_repository_configuration.html";
fl["19"]= "bgp_uplink_configuration.html";
fl["20"]= "_networking_services_neutron.html";
fl["21"]= "_midonet_host_registration.html";
fl["22"]= "_nsdb_nodes.html";
fl["23"]= "_cassandra_installation.html";
fl["24"]= "_metadata_agent.html";
fl["25"]= "_compute_node.html";
fl["26"]= "_architecture.html";
fl["27"]= "_further_steps.html";


text:
Usage
=====

This will help your Symfony app integrate with heroku a little bit easier.

Sample Procfile and app.json are included

If you nail it, you'll be able to add a sweet "Deploy to Heroku" button at the top of your readme :)

things to document:

AppKernel
config.yml
config_prod.yml
config_dev.yml
parameters.yml


text:
#ifndef __BUFFSTR_H__
#define __BUFFSTR_H__

/**
 * Buffered string structure.
 * @field	size	Total size of the buffer.
 * @field	used	Used space in the buffer.
 * @field	s	Allocated buffer.
 */
typedef struct {
	size_t size;
	size_t used;
	unsigned char *s;
} buffstr_t;

/**
 * Create a buffered string.
 * @param	size	Initial size of the buffer.
 * @return	A pointer to the buffered string.
 */
buffstr_t *new_buffstr(size_t size);

/**
 * Add data to a buffered string
 * @param	buf	Pointer to the buffered string.
 * @param	src	Pointer to the buffer to append.
 * @param	size	Size of the data to append.
 */
void buffstr_append(buffstr_t *buf, void *src, size_t size);

#endif // __BUFFSTR_H__


text:
const GET_USER = 'get_user';

export default function(state = {}, action) {
  switch (action.type) {
    case GET_USER:
      console.log(action.payload);
      return { user: action.payload };
    default:
      return state;
  }
}


text:
package com.intellij.execution;

import org.jetbrains.annotations.NotNull;

/**
 * @author nik
 */
public abstract class RunManagerAdapter implements RunManagerListener {
  @Override
  public void runConfigurationSelected() {
  }

  @Override
  public void beforeRunTasksChanged() {
  }

  @Override
  public void runConfigurationAdded(@NotNull RunnerAndConfigurationSettings settings) {
  }

  @Override
  public void runConfigurationRemoved(@NotNull RunnerAndConfigurationSettings settings) {
  }

  @Override
  public void runConfigurationChanged(@NotNull RunnerAndConfigurationSettings settings) {
  }
}


text:
<?php

namespace Everlution\FileJetBundle\Entity;

interface MutableFile extends File
{
    /**
     * @param string $identifier
     * @param string $storageName
     * @param string|null $mutation
     * @return $this
     */
    public function setFile($identifier, $storageName, $mutation = null);

    /**
     * @param string $mutation
     * @return $this
     */
    public function setFileMutation($mutation);
}


text:
cask "jtool2" do
  # NOTE: "2" is not a version number, but an intrinsic part of the product name
  version "2020.02.10"
  sha256 :no_check

  url "http://newosxbook.com/tools/jtool2.tgz"
  name "jtool2"
  desc "Tool to help out reverse engineering, security researchers, and tweak developers"
  homepage "http://newosxbook.com/tools/jtool.html"

  binary "jtool2"
end


text:
namespace libmv {
namespace essential {
namespace kernel {

struct FivePointSolver {
  enum { MINIMUM_SAMPLES = 5 };
  static void Solve(const Mat &x1, const Mat &x2, vector<Mat3> *Es) {
    FivePointsRelativePose(x1, x2, Es);
  }
};

// Kernel for five point essential matrix estimation.
typedef essential::kernel::EssentialKernel<FivePointSolver,
  fundamental::kernel::SampsonError, Mat3>  FivePointKernel;

}  // namespace kernel
}  // namespace essential
}  // namespace libmv

#endif  // LIBMV_MULTIVIEW_FIVE_POINT_KERNEL_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>BaseTransitionBuilder.DelayedEvaluator</title>
<meta name="date" content="2015-05-21">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.kaichunlin.transition

Interface BaseTransitionBuilder.DelayedEvaluator

Enclosing class:

BaseTransitionBuilder<T extends BaseTransitionBuilder,U extends ITransition>

public static interface BaseTransitionBuilder.DelayedEvaluator

This delays the evaluation to the time when transition is about to start, so the current state of the target view can be used in the evaluation

Method Summary

Methods

Modifier and Type
Method and Description

void
evaluate(View view,
        BaseTransitionBuilder builder)

Method Detail

evaluate

void evaluate(View view,
            BaseTransitionBuilder builder)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""
Provides various Exception classes to match HTTP error code responses.
"""

class HTTPResponseError(Exception):
    """Generic exception for http codes greater than 399 and less than 599 """
    def __init__(self, response=None, content=None):
        self.response = response
        self.content = content

class ServerError(HTTPResponseError):
    """ for http error codes 500 and up """
    pass

class NotAuthorised(HTTPResponseError):
    pass

class Forbidden(HTTPResponseError):
    pass

class RequestTimeOut(HTTPResponseError):
    pass

class NotFound(HTTPResponseError):
    pass

class PackagingFormatNotAvailable(HTTPResponseError):
    pass

class NotAcceptable(HTTPResponseError):
    pass


text:
First compile the project with:

```
$ make
```

Then run the ROT13 algorithm with options:

```
$ ./rot13 with a little text
# jvgu n yvggyr grkg

$ ./rot13 < test.txt
# Jul qvq gur puvpxra pebff gur ebnq?

$ echo "Jul qvq gur puvpxra pebff gur ebnq?" | ./rot13
# Why did the chicken cross the road?

```

## References

- [Wikipedia ROT13](https://en.wikipedia.org/wiki/ROT13)
- [Wikipedia ASCII](https://en.wikipedia.org/wiki/ASCII)