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

<TITLE>
EventEntry
</TITLE>

<META NAME="date" CONTENT="2011-07-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.phonegap.calendar.android.model

Class EventEntry

java.lang.Object
  com.phonegap.calendar.android.model.Entry
      com.phonegap.calendar.android.model.EventEntry

All Implemented Interfaces:
java.lang.Cloneable

public class EventEntry
extends Entry

Represents a base GData EventEntry.

Author:

Alain Vongsouvanh, Sergio Martinez Rodriguez

Field Summary

 Value
anyoneCanAddSelf

          TODO(alainv): Add description.

 Comments
comments

          Comments attribute, represents the gd:comments tag info in GData Event

 java.lang.String
content

          Content attribute, represents the content tag info in GData Event

static java.lang.String
EVENT_STATUS_CANCELED

          The event has been canceled

static java.lang.String
EVENT_STATUS_CONFIRMED

          The event is planned

static java.lang.String
EVENT_STATUS_TENTATIVE

          The event is only tentatively scheduled

 Value
eventStatus

          Status of the event.

 Value
guestsCanInviteOthers

          TODO(alainv): Add description.

 Value
guestsCanModify

          TODO(alainv): Add description.

 Value
guestsCanSeeGuests

          TODO(alainv): Add description.

 java.lang.String
recurrence

          Recurrence attribute, represents the gd:recurrence tag info in GData Event, is a string with rfc2445 Ical recurrence format

 Value
sendEventNotifications

          TODO(alainv): Add description.

 Value
sequence

          TODO(alainv): Add description.

 Value
transparency

          Transparency of the event. corresponding to the TRANSP property defined in
 RFC 2445.

static java.lang.String
TRANSPARENCY_OPAQUE

          Indicates event consumes time on calendar; event time will be marked as
 busy in a free/busy search.

static java.lang.String
TRANSPARENCY_TRANSPARENT

          Indicates event doesn't consume any time on calendar; event time will not
 be marked as busy in a free/busy search.

 Value
uid

          id attribute, represents the gCal:uid tag info in GData Event

 Value
visibility

          Visibility of the event.

static java.lang.String
VISIBILITY_CONFIDENTIAL

          Allow some readers to see the event

static java.lang.String
VISIBILITY_DEFAULT

          Inherit the behavior from the preferences of the owner of the calendar on
 which the event appears.

static java.lang.String
VISIBILITY_PRIVATE

          Allow fewest readers to see the event.

static java.lang.String
VISIBILITY_PUBLIC

          Allow most readers to see the event.

 java.util.List<When>
when

          When attribute, represents the gd:when tag info in GData Event

 java.util.List<Where>
where

          where attribute, represents the gd:where tag info in GData Event

 java.util.List<Who>
who

          who attribute, represents the gd:who tag info in GData Event

Fields inherited from class com.phonegap.calendar.android.model.Entry

author, id, links, summary, title, updated

Constructor Summary

EventEntry()

Method Summary

 void
addReminder(Reminder reminder)

          Adds a reminder into Event reminder list

 EventEntry
clone()

 java.lang.String
getEventFeedLink()

 java.util.List<Reminder>
getReminders()

          Returns the event reminder.

Methods inherited from class com.phonegap.calendar.android.model.Entry

getEditLink, getSelfLink

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

EVENT_STATUS_CANCELED

public static final java.lang.String EVENT_STATUS_CANCELED

The event has been canceled

See Also:
Constant Field Values

EVENT_STATUS_CONFIRMED

public static final java.lang.String EVENT_STATUS_CONFIRMED

The event is planned

See Also:
Constant Field Values

EVENT_STATUS_TENTATIVE

public static final java.lang.String EVENT_STATUS_TENTATIVE

The event is only tentatively scheduled

See Also:
Constant Field Values

TRANSPARENCY_OPAQUE

public static final java.lang.String TRANSPARENCY_OPAQUE

Indicates event consumes time on calendar; event time will be marked as
 busy in a free/busy search.

See Also:
Constant Field Values

TRANSPARENCY_TRANSPARENT

public static final java.lang.String TRANSPARENCY_TRANSPARENT

Indicates event doesn't consume any time on calendar; event time will not
 be marked as busy in a free/busy search.

See Also:
Constant Field Values

VISIBILITY_CONFIDENTIAL

public static final java.lang.String VISIBILITY_CONFIDENTIAL

Allow some readers to see the event

See Also:
Constant Field Values

VISIBILITY_DEFAULT

public static final java.lang.String VISIBILITY_DEFAULT

Inherit the behavior from the preferences of the owner of the calendar on
 which the event appears.

See Also:
Constant Field Values

VISIBILITY_PRIVATE

public static final java.lang.String VISIBILITY_PRIVATE

Allow fewest readers to see the event.

See Also:
Constant Field Values

VISIBILITY_PUBLIC

public static final java.lang.String VISIBILITY_PUBLIC

Allow most readers to see the event.

See Also:
Constant Field Values

content

public java.lang.String content

Content attribute, represents the content tag info in GData Event

comments

public Comments comments

Comments attribute, represents the gd:comments tag info in GData Event

eventStatus

public Value eventStatus

Status of the event. Possible values are EVENT_STATUS_CANCELED,
 EVENT_STATUS_CONFIRMED and EVENT_STATUS_TENTATIVE.

recurrence

public java.lang.String recurrence

Recurrence attribute, represents the gd:recurrence tag info in GData Event, is a string with rfc2445 Ical recurrence format

transparency

public Value transparency

Transparency of the event. corresponding to the TRANSP property defined in
 RFC 2445. Possible values are TRANSPARENCY_OPAQUE and
 TRANSPARENCY_TRANSPARENT.

visibility

public Value visibility

Visibility of the event. Possible values are
 VISIBILITY_CONFIDENTIAL, VISIBILITY_DEFAULT,
 VISIBILITY_PRIVATE and VISIBILITY_PUBLIC.

when

public java.util.List<When> when

When attribute, represents the gd:when tag info in GData Event

where

public java.util.List<Where> where

where attribute, represents the gd:where tag info in GData Event

who

public java.util.List<Who> who

who attribute, represents the gd:who tag info in GData Event

anyoneCanAddSelf

public Value anyoneCanAddSelf

TODO(alainv): Add description. Boolean, possible values are true or
 false.

guestsCanInviteOthers

public Value guestsCanInviteOthers

TODO(alainv): Add description. Boolean, possible values are true or
 false.

guestsCanModify

public Value guestsCanModify

TODO(alainv): Add description. Boolean, possible values are true or
 false.

sendEventNotifications

public Value sendEventNotifications

TODO(alainv): Add description. Boolean, possible values are true or
 false.

guestsCanSeeGuests

public Value guestsCanSeeGuests

TODO(alainv): Add description. Boolean, possible values are true or
 false.

sequence

public Value sequence

TODO(alainv): Add description. Integer.

uid

public Value uid

id attribute, represents the gCal:uid tag info in GData Event

Constructor Detail

EventEntry

public EventEntry()

Method Detail

getEventFeedLink

public java.lang.String getEventFeedLink()

clone

public EventEntry clone()

getReminders

public java.util.List<Reminder> getReminders()

Returns the event reminder.

Returns:
The event reminder

addReminder

public void addReminder(Reminder reminder)

Adds a reminder into Event reminder list

Parameters:
reminder - new reminder to be added

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package edu.umass.cs.iesl.author_coref.process

import java.text.Normalizer

import edu.umass.cs.iesl.author_coref._
import edu.umass.cs.iesl.author_coref.data_structures.PersonName

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
 * This file contains a variety of name processing steps
 */

trait NameProcessor {
  def process(name: PersonName): PersonName
}

class CompoundNameProcessor(processors: Iterable[NameProcessor]) extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    var res: PersonName = null
    processors.foreach(p => res = p.process(name))
    res
  }
}

object IdentityNameProcessor extends NameProcessor{
  def process(name: PersonName): PersonName = name
}

object FirstNameTrimmer extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    name.firstName.opt.foreach(n => name.firstName.set(n.trimBegEnd()))
    name
  }
}

object LastNameTrimmer extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    name.lastName.opt.foreach(n => name.lastName.set(n.trimBegEnd()))
    name
  }
}

object FirstMiddleSplitter extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    val fn = name.firstName.opt.getOrElse("")
    if (fn.length > 0) {
      if (fn.length == 2) {
        val isInitial = !(fn.charAt(0).isUpper && fn.charAt(1).isLower)
        if (isInitial) {
          name.firstName.set(fn.charAt(0).toString)
          name.middleNames.set(Seq(fn.charAt(1).toString))
        }
      } else {
        val split = name.firstName.opt.map(_.split("\\s")).getOrElse(Array())
        name.firstName.set(split.headOption)
        name.middleNames.set(name.middleNames.opt.getOrElse(Seq()) ++ split.drop(1))
      }
    }
    name
  }
}

object RemoveOverlappingMiddleNames extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    if (name.middleNames.isDefined && name.middleNames.value.nonEmpty) {
      val fn = name.firstName.opt.getOrElse("").toLowerCase
      val ln = name.lastName.opt.getOrElse("").toLowerCase
      val lcMn = new mutable.HashSet[String]()
      val middles = new ArrayBuffer[String]()
      name.middleNames.value.foreach {
        m =>
          val lcm = m.toLowerCase
          if (lcm != fn && lcm != ln && !lcMn.contains(lcm)) {
            lcMn += lcm
            middles += m
          }
      }
      name.middleNames.set(middles)
    }
    name
  }
}

object LastNameSuffixProcessor extends NameProcessor {
  override def process(name: PersonName): PersonName = {
    val (newLastname, newSuffixes) = processLastName(name.lastName.opt.getOrElse(""))
    name.lastName.set(newLastname)
    name.suffixes.set(name.suffixes.opt.getOrElse(Seq()) ++ newSuffixes)
    name
  }

  def processLastName(string: String) = {
    val splitOnComma = string.split(",").map(_.trimBegEnd())
    if (splitOnComma.isEmpty)
      println("WARNING: name is a single comma.")
    val name = splitOnComma.headOption.getOrElse("")
    val suffixes = splitOnComma.drop(1)
    (name,suffixes)
  }
}

trait AccentNameProcessor extends NameProcessor {

  val accentRegex = "\\{[a-zA-Z0-9]+ over \\(([a-zA-Z0-9\\s]+)\\)\\}".r

  def processString(stringName: String) = {
    accentRegex.replaceAllIn(stringName,regexMatch => regexMatch.group(1))
  }

}

object LastNameAccentNameProcessor extends AccentNameProcessor {
  override def process(name: PersonName): PersonName =
    name.lastName.set(name.lastName.opt.map(processString))
}

object FirstNameAccentNameProcessor extends AccentNameProcessor {
  override def process(name: PersonName): PersonName =
    name.firstName.set(name.firstName.opt.map(processString))
}

trait UnicodeCharacterAccentNameProcessor extends NameProcessor {
  def processString(stringName: String)= {
    Normalizer.normalize(stringName, Normalizer.Form.NFKD).replaceAll("[^\\p{ASCII}]", "")
  }
}

object LastNameUnicodeCharacterAccentNameProcessor extends UnicodeCharacterAccentNameProcessor {
  override def process(name: PersonName): PersonName =
    name.lastName.set(name.lastName.opt.map(processString))
}

object FirstNameUnicodeCharacterAccentNameProcessor extends UnicodeCharacterAccentNameProcessor {
  override def process(name: PersonName): PersonName =
    name.firstName.set(name.firstName.opt.map(processString))
}

trait AlphabeticOnlyNameProcessor extends NameProcessor {
  val regex = "[^a-zA-Z]"
  def processString(stringName: String) = {
    stringName.replaceAll(regex,"")
  }
}

object AlphabeticOnlyLastNameProcessor extends AlphabeticOnlyNameProcessor {
  override def process(name: PersonName): PersonName =
    name.lastName.set(name.lastName.opt.map(processString))
}

object AlphabeticOnlyMiddleNameProcessor extends AlphabeticOnlyNameProcessor {
  override def process(name: PersonName): PersonName =
    name.middleNames.set(name.middleNames.opt.map(c => c.map(processString)))
}

object AlphabeticOnlySuffixesProcessor extends AlphabeticOnlyNameProcessor {
  override def process(name: PersonName): PersonName =
    name.suffixes.set(name.suffixes.opt.map(c => c.map(processString)))
}

object AlphabeticOnlyFirstNameProcessor extends AlphabeticOnlyNameProcessor {
  override def process(name: PersonName): PersonName =
    name.firstName.set(name.firstName.opt.map(processString))
}

object AlphabeticOnlyAllNamesProcessor extends CompoundNameProcessor(Iterable(AlphabeticOnlyFirstNameProcessor,AlphabeticOnlyMiddleNameProcessor,AlphabeticOnlyLastNameProcessor,AlphabeticOnlySuffixesProcessor))

object LowerCaseFirstName extends NameProcessor {
  override def process(name: PersonName): PersonName = name.firstName.set(name.firstName.opt.map(_.toLowerCase))
}

object LowerCaseLastName extends NameProcessor {
  override def process(name: PersonName): PersonName = name.lastName.set(name.lastName.opt.map(_.toLowerCase))
}

object LowerCaseMiddleNames extends NameProcessor {
  override def process(name: PersonName): PersonName = name.middleNames.set(name.middleNames.opt.map(_.map(_.toLowerCase)))
}

object LowerCaseSuffixes extends NameProcessor {
  override def process(name: PersonName): PersonName = name.suffixes.set(name.suffixes.opt.map(_.map(_.toLowerCase)))
}

object LowerCaseAllNames extends CompoundNameProcessor(Iterable(LowerCaseFirstName,LowerCaseMiddleNames,LowerCaseLastName,LowerCaseSuffixes))

object ReEvaluatingNameProcessor extends CompoundNameProcessor(Iterable(FirstNameTrimmer,LastNameTrimmer,LastNameSuffixProcessor,LastNameAccentNameProcessor,FirstNameAccentNameProcessor,FirstMiddleSplitter,RemoveOverlappingMiddleNames))

object CaseInsensitiveReEvaluatingNameProcessor extends CompoundNameProcessor(Iterable(FirstNameTrimmer,LastNameTrimmer,LastNameSuffixProcessor,LastNameAccentNameProcessor,FirstNameAccentNameProcessor,FirstNameUnicodeCharacterAccentNameProcessor,LastNameUnicodeCharacterAccentNameProcessor,FirstMiddleSplitter,RemoveOverlappingMiddleNames,AlphabeticOnlyAllNamesProcessor,LowerCaseAllNames))

/**
  * Object to retrieve a name processor based on a string
  */
object NameProcessor {
  /**
    * Return the name processor associated with each string name. Matching is
    * case insensitive and ignores the "nameprocessor" part of the name
    *
    *   1) "identity" - a name processor which does nothing at all
    *   2) "CaseInsensitiveReEvaluatingNameProcessor" - normalizes names and might change middle & last names according to punctuation/spacing
    *   3) "LowerCaseAllNames" - lowercases the first, middle and last names
    *   4) "ReEvaluatingNameProcessor" - normalizes accent characters but keeps names case sensitive. might change middle & last names according to punctuation/spacing
    * @param string
    */
  def fromString(string: String):NameProcessor = string.toLowerCase.replaceAll("nameprocessor","") match {
    case "identity" => IdentityNameProcessor
    case "caseinsensitivereevaluating" => CaseInsensitiveReEvaluatingNameProcessor
    case "lowercaseallnames" => LowerCaseAllNames
    case "reevaluating" => ReEvaluatingNameProcessor
  }
}

redpajama_set_name: RedPajamaGithub


text:
This is a simple application (a ToDoList) developed using ReactJS

# Prerequisite
Node (^5) , webpack and webpack-dev-server

if you are having trouble with these follow the links to chekouts

- Node -> https://nodejs.org
- webpack -> npm install -g webpack
- webpack dev server -> npm install -g webpack-dev-server

# Run
- npm install
- npm start

# Test
http://localhost:7000


text:
- Fixed stack overflow error when using multiple levels of the parent() function
- Fixed platform dependent issues with junit tests
- Bug fix regarding the use of different data types passed to same template which broke an internal cache in the GetAttributeExpression

## v1.4.4
- Bug fix regarding NPE with internal cache
- Bug fix when using suffix with the file loader

## v1.4.3
- Bug fix for issue regarding multiple for loops only rendering first one

## v1.4.2
- Performance improvements

## v1.4.1
- Performance improvements

## v1.4.0
- Added ServletLoader which is the only built-in loader that works with JBoss/Wildfly
- Added "first" filter
- Added "last" filter
- Added "join" filter

## v1.3.1
- Fixed lexing issue on windows
- Fixed number comparison issue

## v1.3.0
- Added "filter" tag
- Added "abs" filter
- Added "sort" filter
- Pebble now uses the exact Map implementation provided by user instead of moving variables into it's own map implementation. This allows for custom "lazy" maps and other unique implementations.
- Arrays and lists can now be accessed by index

## v1.2.0
- Added verbatim tag
- Removed the LocaleAware interface; filters/functions/tests now get the locale via the EvaluationContext that is passed as a "_context" argument in the argument map
- Added a whitespace control character: "-"
- Fixed bug where macros were being secretly evaluated one too many times

## v1.1.0
- The ability to call bean methods that require arguments.
- For loop now works with primitive arrays (i.e. no longer just Iterable objects).
- Added "subscript syntax" support for accessing attributes.
- Continuous integration with travis-ci.
- Fixed NPE occurring in ternary expressions.
- Fixed issue with if-then-else expressions
- General code and testing improvements.

## v1.0.0
- Some code cleanup and fixed an incorrect unit test.

## v0.4.0-beta
- No more code generation, all nodes of the AST are rendered during template evaluation phase.

## v0.3.0-beta
- Autoescaping, more escaping strategies, autoescape tag, and raw filter.
- Extensions can now provide node visitors to traverse the AST.
- Macros can have default argument values.
- Implemented dynamic inheritance.
- Renamed 'message' function to 'i18n'
- Fixed issue where compilation failed in JBoss.
- Code cleanup and misc small bugs

## v0.2.0-beta (2014-02-08)
- Implemented named arguments.
- Added dependency on google guava for template cache.
- Split the default loader class into multiple discrete loaders.
- Added the `title` filter.
- Fixed issue where compilation mutex might not have been released.
- Fixed parsing issues if variable names were prefixed with operator names.
- Fixed issue where included templates didn't have access to context.
- Fixed issue where `if` tag could not be used directly on a boolean variable.
- Removed the `format` filter.
- Fixed misc other smaller bugs.

## v0.1.5-beta (2014-01-27)
- Fixed major bug from v0.1.4 that prevented macros from being invoked more than once.

## v0.1.4-beta (2014-01-27)
- The i18n extension is now enabled by default.
- Improved exception handling (storing cause where applicable).
- PebbleEngine now returns a PebbleTemplate interface with a small subset of original methods.
- Refactored function/filter/test interfaces into functional interfaces (preparation for Java 8).

## v0.1.3-beta (2014-01-25)
- More unit tests and minor bug fixes.
- Fixed issue where child templates were being inappropriately cached.
- All core filters now perform null checking.
- Performance optimization with variable attributes.
- Renamed the number_format filter to numberformat

## v0.1.2-beta (2014-01-19)
- Fixed issue where parent block didn't have access to context.
- Macros no longer have access to context (only local vars).
- Fixed issue where macro output coudn't be filtered/tested.
- Refactored how blocks and macros are implemented .
- Renamed number filter to number_format.
- Added a cache interface for user's to provide their own cache. Also removed the "cacheTemplates" setting.
- Default cache is now thread safe.
- Templates can now be evaluated concurrently.
- Users can now safely attempt a concurrent compilation.
- Fixed issue where provided writer was being closed by pebble engine.
- Fixed memory leak in file manager.
- Removed json filter.
- Removed some third party dependencies.
- Added parallel tag.
- More unit tests and misc code cleanup.

## v0.1.1-beta (2014-01-02)
- Fixed issue where templates of same name but different path were overriding each other in main template cache.
- Made sure byte code stored in memory in InMemoryJavaFileManager is cleared when no longer required.
- Removed caching of Reader objects from PebbleDefaultLoader which was causing more harm than good. This can be added back later if it is deemed necessary.
- Completely changed how operators are compiled into Java due to a bunch of bugs regarding operand types.
- Changed the behaviour of the == operator and added the equals operator as an alias.
- Extensions can now provide custom functions.
- Added source, min, and max functions.
- The setting, cacheTemplates, now defaults to true.
- Renamed the main entry points into the main Engine from "loadTemplate/render" to "compile/evaluate".
- Added i18n extension (disabled by default) and a default locale setting on the main pebble engine. The extension adds one new function: message()
- Small performance improvements when looking up variable attributes.

## v0.1.0-beta (2013-12-27)
- Refined PebbleEngine's available public methods.
- Added "strictVariables" setting to PebbleEngine.
- Cleaned up how pebble-spring is to be configured.
- More bug fixes and unit tests.

## v0.0.3-alpha (2013-11-17)
- Configuration changes in order to have the project hosted in the Maven Central Repository.

## v0.0.2-alpha (2013-11-16)
- Dedicated website with documentation.
- Code refactoring, more unit tests, bug fixes.
- Conditional (ternary) operator.
- Escape filter.
- Macro overloading.

## v0.0.1-alpha (2013-09-30)
This is the first functioning version of Pebble. The following has been implemented:
- tags: block, extends, for, if, import, include, macro, set
- filters: abbreviate, capitalize, date, default, format, json, lower, number, trim, upper, urlencode
- functions: block, parent
- tests: empty, even, null, odd, iterable, equalTo
- operators: in, is, is not, +, -, /, *, %, and, or, (), ==, !=, <, >, <=, >=, |, .
- unit tests


text:
import {
  innerHeight,
  innerWidth,
  getScrollLeft,
  getScrollTop,
  offset,
} from './../../../helpers/dom/element';
import { rangeEach, rangeEachReverse } from './../../../helpers/number';

/**
 * @class Scroll
 */
class Scroll {
  /**
   * @param {Walkontable} wotInstance
   */
  constructor(wotInstance) {
    this.wot = wotInstance;

    // legacy support
    this.instance = wotInstance;
  }

  /**
   * Scrolls viewport to a cell.
   *
   * @param {CellCoords} coords
   * @param {Boolean} [snapToTop]
   * @param {Boolean} [snapToRight]
   * @param {Boolean} [snapToBottom]
   * @param {Boolean} [snapToLeft]
   * @returns {Boolean}
   */
  scrollViewport(coords, snapToTop, snapToRight, snapToBottom, snapToLeft) {
    const scrolledHorizontally = this.scrollViewportHorizontally(coords.col, snapToRight, snapToLeft);
    const scrolledVertically = this.scrollViewportVertically(coords.row, snapToTop, snapToBottom);

    return scrolledHorizontally || scrolledVertically;
  }

  /**
   * Scrolls viewport to a column.
   *
   * @param {Number} column Visual column index.
   * @param {Boolean} [snapToRight]
   * @param {Boolean} [snapToLeft]
   * @returns {Boolean}
   */
  scrollViewportHorizontally(column, snapToRight, snapToLeft) {
    if (!this.wot.drawn) {
      return false;
    }

    const {
      fixedColumnsLeft,
      leftOverlay,
      totalColumns,
    } = this._getVariables();
    let result = false;

    if (column >= 0 && column <= Math.max(totalColumns - 1, 0)) {
      if (column >= fixedColumnsLeft && (column < this.getFirstVisibleColumn() || snapToLeft)) {
        result = leftOverlay.scrollTo(column);
      } else if (column > this.getLastVisibleColumn() || snapToRight) {
        result = leftOverlay.scrollTo(column, true);
      }
    }

    return result;
  }

  /**
   * Scrolls viewport to a row.
   *
   * @param {Number} row Visual row index.
   * @param {Boolean} [snapToTop]
   * @param {Boolean} [snapToBottom]
   * @returns {Boolean}
   */
  scrollViewportVertically(row, snapToTop, snapToBottom) {
    if (!this.wot.drawn) {
      return false;
    }

    const {
      fixedRowsBottom,
      fixedRowsTop,
      topOverlay,
      totalRows,
    } = this._getVariables();
    let result = false;

    if (row >= 0 && row <= Math.max(totalRows - 1, 0)) {
      if (row >= fixedRowsTop && (row < this.getFirstVisibleRow() || snapToTop)) {
        result = topOverlay.scrollTo(row);
      } else if ((row > this.getLastVisibleRow() && row < totalRows - fixedRowsBottom) || snapToBottom) {
        result = topOverlay.scrollTo(row, true);
      }
    }

    return result;
  }

  /**
   * Get first visible row based on virtual dom and how table is visible in browser window viewport.
   *
   * @returns {Number}
   */
  getFirstVisibleRow() {
    const {
      topOverlay,
      wtTable,
      wtViewport,
      totalRows,
      fixedRowsTop,
    } = this._getVariables();

    let firstVisibleRow = wtTable.getFirstVisibleRow();

    if (topOverlay.mainTableScrollableElement === window) {
      const rootElementOffset = offset(wtTable.wtRootElement);
      const totalTableHeight = innerHeight(wtTable.hider);
      const windowHeight = innerHeight(window);
      const windowScrollTop = getScrollTop(window);

      // Only calculate firstVisibleRow when table didn't filled (from up) whole viewport space
      if (rootElementOffset.top + totalTableHeight - windowHeight <= windowScrollTop) {
        let rowsHeight = wtViewport.getColumnHeaderHeight();

        rowsHeight += topOverlay.sumCellSizes(0, fixedRowsTop);

        rangeEachReverse(totalRows, 1, (row) => {
          rowsHeight += topOverlay.sumCellSizes(row - 1, row);

          if (rootElementOffset.top + totalTableHeight - rowsHeight <= windowScrollTop) {
            // Return physical row + 1
            firstVisibleRow = row;

            return false;
          }
        });
      }
    }

    return firstVisibleRow;
  }

  /**
   * Get last visible row based on virtual dom and how table is visible in browser window viewport.
   *
   * @returns {Number}
   */
  getLastVisibleRow() {
    const {
      topOverlay,
      wtTable,
      wtViewport,
      totalRows,
    } = this._getVariables();

    let lastVisibleRow = wtTable.getLastVisibleRow();

    if (topOverlay.mainTableScrollableElement === window) {
      const rootElementOffset = offset(wtTable.wtRootElement);
      const windowHeight = innerHeight(window);
      const windowScrollTop = getScrollTop(window);

      // Only calculate lastVisibleRow when table didn't filled (from bottom) whole viewport space
      if (rootElementOffset.top > windowScrollTop) {
        let rowsHeight = wtViewport.getColumnHeaderHeight();

        rangeEach(1, totalRows, (row) => {
          rowsHeight += topOverlay.sumCellSizes(row - 1, row);

          if (rootElementOffset.top + rowsHeight - windowScrollTop >= windowHeight) {
            // Return physical row - 1 (-2 because rangeEach gives row index + 1 - sumCellSizes requirements)
            lastVisibleRow = row - 2;

            return false;
          }
        });
      }
    }

    return lastVisibleRow;
  }

  /**
   * Get first visible column based on virtual dom and how table is visible in browser window viewport.
   *
   * @returns {Number}
   */
  getFirstVisibleColumn() {
    const {
      leftOverlay,
      wtTable,
      wtViewport,
      totalColumns,
    } = this._getVariables();

    let firstVisibleColumn = wtTable.getFirstVisibleColumn();

    if (leftOverlay.mainTableScrollableElement === window) {
      const rootElementOffset = offset(wtTable.wtRootElement);
      const totalTableWidth = innerWidth(wtTable.hider);
      const windowWidth = innerWidth(window);
      const windowScrollLeft = getScrollLeft(window);

      // Only calculate firstVisibleColumn when table didn't filled (from left) whole viewport space
      if (rootElementOffset.left + totalTableWidth - windowWidth <= windowScrollLeft) {
        let columnsWidth = wtViewport.getRowHeaderWidth();

        rangeEachReverse(totalColumns, 1, (column) => {
          columnsWidth += leftOverlay.sumCellSizes(column - 1, column);

          if (rootElementOffset.left + totalTableWidth - columnsWidth <= windowScrollLeft) {
            // Return physical column + 1
            firstVisibleColumn = column;

            return false;
          }
        });
      }
    }

    return firstVisibleColumn;
  }

  /**
   * Get last visible column based on virtual dom and how table is visible in browser window viewport.
   *
   * @returns {Number}
   */
  getLastVisibleColumn() {
    const {
      leftOverlay,
      wtTable,
      wtViewport,
      totalColumns,
    } = this._getVariables();

    let lastVisibleColumn = wtTable.getLastVisibleColumn();

    if (leftOverlay.mainTableScrollableElement === window) {
      const rootElementOffset = offset(wtTable.wtRootElement);
      const windowWidth = innerWidth(window);
      const windowScrollLeft = getScrollLeft(window);

      // Only calculate lastVisibleColumn when table didn't filled (from right) whole viewport space
      if (rootElementOffset.left > windowScrollLeft) {
        let columnsWidth = wtViewport.getRowHeaderWidth();

        rangeEach(1, totalColumns, (column) => {
          columnsWidth += leftOverlay.sumCellSizes(column - 1, column);

          if (rootElementOffset.left + columnsWidth - windowScrollLeft >= windowWidth) {
            // Return physical column - 1 (-2 because rangeEach gives column index + 1 - sumCellSizes requirements)
            lastVisibleColumn = column - 2;

            return false;
          }
        });
      }
    }

    return lastVisibleColumn;
  }

  /**
   * Returns collection of variables used to rows and columns visibility calculations.
   *
   * @returns {Object}
   * @private
   */
  _getVariables() {
    const wot = this.wot;
    const topOverlay = wot.wtOverlays.topOverlay;
    const leftOverlay = wot.wtOverlays.leftOverlay;
    const wtTable = wot.wtTable;
    const wtViewport = wot.wtViewport;
    const totalRows = wot.getSetting('totalRows');
    const totalColumns = wot.getSetting('totalColumns');
    const fixedRowsTop = wot.getSetting('fixedRowsTop');
    const fixedRowsBottom = wot.getSetting('fixedRowsBottom');
    const fixedColumnsLeft = wot.getSetting('fixedColumnsLeft');

    return {
      topOverlay,
      leftOverlay,
      wtTable,
      wtViewport,
      totalRows,
      totalColumns,
      fixedRowsTop,
      fixedRowsBottom,
      fixedColumnsLeft
    };
  }
}

export default Scroll;


text:
'use strict';

$(function () {
    var canvas = new Canvas($('canvas')[0]),
        waterfall = new Waterfall(canvas),
        startPage = new StartPage(canvas);
    this.gameController = new GameController(canvas);

});


text:
[![Documentation Status](https://readthedocs.org/projects/taf-docs/badge/?version=latest)](http://taf-docs.readthedocs.io/en/latest/?badge=latest)
[![Travis](https://img.shields.io/travis/rust-lang/rust.svg)](https://travis-ci.org/taf3/taf)

**TAF** is an integrated cross-platform system that sets the guidelines and provides tools for automation testing. The function libraries, test data sources, test object details, and various reusable modules are all integrated in one system. The platform provides an outline of the test automation process and reduces automation efforts. With this framework, an automation or validation engineer may run testing suites in different environments and obtain test results with detailed reports.

The [Python](https://www.python.org/) programming language was chosen for the Framework, due to its high development speed and great maintainability. In addition, it has an XML-RPC library. [Py.test](http://pytest.org/latest/) was chosen as it has several advantages over other available test libraries. We follow the principle of maximum usage of existing components and systems. The framework has some components which use threading which should be considered when looking for components to extend the system. The system is built in way that allows users to see all errors that occur during test execution and to trace the full path to the initial point where the defect appeared to simplify root cause analysis. There is no external storage required except integration with Test Case Management System(s) using a database via API to update test case execution results and any related information (automation status, automation owner, automated script location, etc).

### Design considerations

**System Requirements and Dependencies**

The framework is designed for use in Linux systems which have Python programming tools and the necessary libraries installed. The framework has been tested on following systems:

* Ubuntu 14.04.1 LTS running Python 3.4.0, py.test 2.9.2 and higher versions.
* Ubuntu 16.04.1 LTS running Python 3.4.0, py.test 2.9.2 and higher versions.

Test cases running with TAF might require additional software packages such as Ixia or Jira, depending upon test scenarios, which can be downloaded from internet or company website.

**Constraints**

The framework is originally intended to work with remote systems, so quality of network may affect testing results. In its original testing environment, **TAF** uses an Ixia traffic generator via Tcl API which may cause to slow down overall system performance, since **TAF** must use the Tkinter Python library to bind Tcl and Python. Furthermore, Ixia is a Windows-based system, however it does include a Tcl server component which allows access from Linux hosts. Ixia Tcl library (IxTclHAL) is not thread-safe which may add difficulties in future.

**Goals and Guidelines**

The **TAF** framework follows the "principle of atomicity" by splitting complex test cases into parts if possible and the DRY (Don't Repeat Yourself) principle by moving shared parts of code into helper functions and modules. **TAF** will define testing along the development phase, which will enable testers to configure the test environment, execute tests, and measure success/failure and coverage. The modular approach of **TAF** enables development of new tests without impacting existing ones, increasing reusability of developed tests.

### System architecture

![TAF architecture](https://github.com/taf3/taf/blob/master/docs/images/taf_architecture.png "Test Automation Framework Architecture")

The **TAF** is based on [py.test](http://pytest.org/latest/). The basic concept is to create libraries with all necessary functionality, to define how the environment configuration will be supplied to test suites, and to create a reporting processing functionality.

**TAF** package consists of two folders: **./taf** and **./testcases**. **taf** folder holds library modules (or plugins) for [py.test](http://pytest.org/latest/), and **testcases** contains test cases including test configuration and test scenarios. **./taf/testlib** contains of the following modules.

**Common functionality and helper functions:**

* `loggers` - integration of standard python logging library into framework;
* `helpers*` - contains different helper functions which can be used from test suites;
* `common3` - contains base class to handle test environment.

**Groups of modules to handle environment-specific functionality:**

* `environment` - functions for manipulation the operating system environment variables etc.

**Hardware-related libraries:**

* `dev_*` - modules which contain classes to handle particular environment type;
* `powerboard`  - startup/shutdown of the devices using SNMP via APC power boards.

**Typical sequence of actions and operations:**

1. Execution starts from calling py.test with necessary command line arguments.
2. Py.test collects test cases according to its discovery rules.
3. Py.test analyses conftest.py file(s) according to its discovery rules.
4. Py.test performs setup procedure defined in conftest.py file.
5. Py.test starts test suites execution one by one.
6. Py.test performs tear down procedure defined in conftest.py file.
7. Logs are stored and ready for further processing.

## Installation

### Docker container

**TAF** is very easy to install and deploy as a Docker container.

**Docker** can build images automatically by reading instructions from a Dockerfile, a text document that contains all the commands a user can call on the command line to assemble an image. Using Docker build, users can create an automated build that executes several command-line instructions in succession. **TAF** has a configuration file, called Dockerfile, located in the root of the **TAF**  directory. It is based on Ubuntu 16.04 and Python 3.4.0.

**Install and configure Docker**

In order to install Docker, refer [Docker](https://docs.docker.com/engine/installation/linux/ubuntulinux/) .

**Build image**

To build **TAF** image you need to execute command:
```
    docker build -t <image_name>:<tag> -f Dockerfile .
    E.g. :root@14-04:~/taf# docker build -t ubuntu:taf3 -f Dockerfile .
```

Building the **TAF** image from Dockerfile can take over 15 minutes.

**Run container**

To run the **TAF** image and login to the container, execute command:
```
    docker run -i -t  <image_name>:<tag>
    E.g.: root@14-04:~# docker run -i -t ubuntu:taf3
```

After execution of previous command, the prompt should changed to:
```
    root@<container_id>:~#
    E.g.: root@fa3ced1fdcbf:~#
```

The **TAF** repository can be found in the root directory. Once in the **TAF** container, sample testcases can be run:
```
    $ cd unittests
    $ /root/taf/unittests/ py.test test_common3.py
```

### Simple test execution

* **Git clone testcases repository**

Link to repository [testcases](https://github.com/taf3/testcases)

* **Run test**

    Command line used to execute specified test case:
```
 /<host>/:~ /testcases$ env PYTHONPATH=/root/taf/taf py.test --env=config/env/environment_examples.json
  --setup_file=config/setup/linuxhost_standalone.json general/ -m lhost_sample --logdir=demo_logs --xml_html=demo.html
```
> Note:

> Test example requires to install and configure OpenSSH server. Appropriate ssh credentials need to be specified in environment_examples.json file with "entry_type" linux_host.

     env PYTHONPATH – set up PYTHONPATH variable with path to TAF repository;

     env – provide path to the environment*.json file;

     setup – provide path to the setup*.json file.

 * More **detailed information** can be found by the following link: [Test execution preconfiguration](http://taf-docs.readthedocs.io/en/latest/test_execution_preconfiguration.html)

## Support and contact

Link to wiki [Сontribution guidelines](http://taf-docs.readthedocs.io/en/latest/contribution_guidelines.html).

## License

Apache 2.0. See [LICENSE](https://github.com/taf3/taf/blob/master/LICENSE) for more details.


text:
package de.daxu.swamp.api.server.dto;

import de.daxu.swamp.api.location.dto.LocationDTO;

import static de.daxu.swamp.core.location.LocationType.SERVER;

public class ServerDTO extends LocationDTO {

    private String ip;

    @SuppressWarnings("unused")
    private ServerDTO() {
    }

    private ServerDTO(String id, String name, String ip) {
        super(id, name, SERVER);
        this.ip = ip;
    }

    public String getIp() {
        return ip;
    }

    public static class Builder extends LocationDTO.Builder<Builder> {

        private String ip;

        public Builder withIp(String ip) {
            this.ip = ip;
            return this;
        }

        public ServerDTO build() {
            return new ServerDTO(id, name, ip);
        }
    }
}


text:
namespace {
static const char kGoogleBreakpadKey[] = "google-breakpad";
static const char kMicrodumpBegin[] = "-----BEGIN BREAKPAD MICRODUMP-----";
static const char kMicrodumpEnd[] = "-----END BREAKPAD MICRODUMP-----";
static const char kOsKey[] = ": O ";
static const char kCpuKey[] = ": C ";
static const char kCrashReasonKey[] = ": R ";
static const char kGpuKey[] = ": G ";
static const char kMmapKey[] = ": M ";
static const char kStackKey[] = ": S ";
static const char kStackFirstLineKey[] = ": S 0 ";
static const char kArmArchitecture[] = "arm";
static const char kArm64Architecture[] = "arm64";
static const char kX86Architecture[] = "x86";
static const char kMipsArchitecture[] = "mips";
static const char kMips64Architecture[] = "mips64";
static const char kGpuUnknown[] = "UNKNOWN";

template<typename T>
T HexStrToL(const string& str) {
  uint64_t res = 0;
  std::istringstream ss(str);
  ss >> std::hex >> res;
  return static_cast<T>(res);
}

std::vector<uint8_t> ParseHexBuf(const string& str) {
  std::vector<uint8_t> buf;
  for (size_t i = 0; i < str.length(); i += 2) {
    buf.push_back(HexStrToL<uint8_t>(str.substr(i, 2)));
  }
  return buf;
}

bool GetLine(std::istringstream* istream, string* str) {
  if (std::getline(*istream, *str)) {
    // Trim any trailing newline from the end of the line. Allows us
    // to seamlessly handle both Windows/DOS and Unix formatted input. The
    // adb tool generally writes logcat dumps in Windows/DOS format.
    if (!str->empty() && str->at(str->size() - 1) == '\r') {
      str->erase(str->size() - 1);
    }
    return true;
  }
  return false;
}

}  // namespace

namespace google_breakpad {

//
// MicrodumpModules
//

void MicrodumpModules::Add(const CodeModule* module) {
  linked_ptr<const CodeModule> module_ptr(module);
  if (!map_.StoreRange(module->base_address(), module->size(), module_ptr)) {
    BPLOG(ERROR) << "Module " << module->code_file() <<
                    " could not be stored";
  }
}

void MicrodumpModules::SetEnableModuleShrink(bool is_enabled) {
  map_.SetMergeStrategy(is_enabled ? MergeRangeStrategy::kTruncateUpper
                                   : MergeRangeStrategy::kExclusiveRanges);
}

//
// MicrodumpContext
//

void MicrodumpContext::SetContextARM(MDRawContextARM* arm) {
  DumpContext::SetContextFlags(MD_CONTEXT_ARM);
  DumpContext::SetContextARM(arm);
  valid_ = true;
}

void MicrodumpContext::SetContextARM64(MDRawContextARM64* arm64) {
  DumpContext::SetContextFlags(MD_CONTEXT_ARM64);
  DumpContext::SetContextARM64(arm64);
  valid_ = true;
}

void MicrodumpContext::SetContextX86(MDRawContextX86* x86) {
  DumpContext::SetContextFlags(MD_CONTEXT_X86);
  DumpContext::SetContextX86(x86);
  valid_ = true;
}

void MicrodumpContext::SetContextMIPS(MDRawContextMIPS* mips32) {
  DumpContext::SetContextFlags(MD_CONTEXT_MIPS);
  DumpContext::SetContextMIPS(mips32);
  valid_ = true;
}

void MicrodumpContext::SetContextMIPS64(MDRawContextMIPS* mips64) {
  DumpContext::SetContextFlags(MD_CONTEXT_MIPS64);
  DumpContext::SetContextMIPS(mips64);
  valid_ = true;
}

//
// MicrodumpMemoryRegion
//

MicrodumpMemoryRegion::MicrodumpMemoryRegion() : base_address_(0) { }

void MicrodumpMemoryRegion::Init(uint64_t base_address,
                                 const std::vector<uint8_t>& contents) {
  base_address_ = base_address;
  contents_ = contents;
}

uint64_t MicrodumpMemoryRegion::GetBase() const { return base_address_; }

uint32_t MicrodumpMemoryRegion::GetSize() const { return contents_.size(); }

bool MicrodumpMemoryRegion::GetMemoryAtAddress(uint64_t address,
                                               uint8_t* value) const {
  return GetMemoryLittleEndian(address, value);
}

bool MicrodumpMemoryRegion::GetMemoryAtAddress(uint64_t address,
                                               uint16_t* value) const {
  return GetMemoryLittleEndian(address, value);
}

bool MicrodumpMemoryRegion::GetMemoryAtAddress(uint64_t address,
                                               uint32_t* value) const {
  return GetMemoryLittleEndian(address, value);
}

bool MicrodumpMemoryRegion::GetMemoryAtAddress(uint64_t address,
                                               uint64_t* value) const {
  return GetMemoryLittleEndian(address, value);
}

template<typename ValueType>
bool MicrodumpMemoryRegion::GetMemoryLittleEndian(uint64_t address,
                                                  ValueType* value) const {
  if (address < base_address_ ||
      address - base_address_ + sizeof(ValueType) > contents_.size())
    return false;
  ValueType v = 0;
  uint64_t start = address - base_address_;
  // The loop condition is odd, but it's correct for size_t.
  for (size_t i = sizeof(ValueType) - 1; i < sizeof(ValueType); i--)
    v = (v << 8) | static_cast<uint8_t>(contents_[start + i]);
  *value = v;
  return true;
}

void MicrodumpMemoryRegion::Print() const {
  // Not reached, just needed to honor the base class contract.
  assert(false);
}

//
// Microdump
//
Microdump::Microdump(const string& contents)
  : context_(new MicrodumpContext()),
    stack_region_(new MicrodumpMemoryRegion()),
    modules_(new MicrodumpModules()),
    system_info_(new SystemInfo()),
    crash_reason_(),
    crash_address_(0u) {
  assert(!contents.empty());

  bool in_microdump = false;
  string line;
  uint64_t stack_start = 0;
  std::vector<uint8_t> stack_content;
  string arch;

  std::istringstream stream(contents);
  while (GetLine(&stream, &line)) {
    if (line.find(kGoogleBreakpadKey) == string::npos) {
      continue;
    }
    if (line.find(kMicrodumpBegin) != string::npos) {
      in_microdump = true;
      continue;
    }
    if (!in_microdump) {
      continue;
    }
    if (line.find(kMicrodumpEnd) != string::npos) {
      break;
    }

    size_t pos;
    if ((pos = line.find(kOsKey)) != string::npos) {
      string os_str(line, pos + strlen(kOsKey));
      std::istringstream os_tokens(os_str);
      string os_id;
      string num_cpus;
      string os_version;
      // This reflect the actual HW arch and might not match the arch emulated
      // for the execution (e.g., running a 32-bit binary on a 64-bit cpu).
      string hw_arch;

      os_tokens >> os_id;
      os_tokens >> arch;
      os_tokens >> num_cpus;
      os_tokens >> hw_arch;
      GetLine(&os_tokens, &os_version);
      os_version.erase(0, 1);  // remove leading space.

      system_info_->cpu = arch;
      system_info_->cpu_count = HexStrToL<uint8_t>(num_cpus);
      system_info_->os_version = os_version;

      if (os_id == "L") {
        system_info_->os = "Linux";
        system_info_->os_short = "linux";
      } else if (os_id == "A") {
        system_info_->os = "Android";
        system_info_->os_short = "android";
        modules_->SetEnableModuleShrink(true);
      }

      // OS line also contains release and version for future use.
    } else if ((pos = line.find(kStackKey)) != string::npos) {
      if (line.find(kStackFirstLineKey) != string::npos) {
        // The first line of the stack (S 0 stack header) provides the value of
        // the stack pointer, the start address of the stack being dumped and
        // the length of the stack. We could use it in future to double check
        // that we received all the stack as expected.
        continue;
      }
      string stack_str(line, pos + strlen(kStackKey));
      std::istringstream stack_tokens(stack_str);
      string start_addr_str;
      string raw_content;
      stack_tokens >> start_addr_str;
      stack_tokens >> raw_content;
      uint64_t start_addr = HexStrToL<uint64_t>(start_addr_str);

      if (stack_start != 0) {
        // Verify that the stack chunks in the microdump are contiguous.
        assert(start_addr == stack_start + stack_content.size());
      } else {
        stack_start = start_addr;
      }
      std::vector<uint8_t> chunk = ParseHexBuf(raw_content);
      stack_content.insert(stack_content.end(), chunk.begin(), chunk.end());

    } else if ((pos = line.find(kCpuKey)) != string::npos) {
      string cpu_state_str(line, pos + strlen(kCpuKey));
      std::vector<uint8_t> cpu_state_raw = ParseHexBuf(cpu_state_str);
      if (strcmp(arch.c_str(), kArmArchitecture) == 0) {
        if (cpu_state_raw.size() != sizeof(MDRawContextARM)) {
          std::cerr << "Malformed CPU context. Got " << cpu_state_raw.size()
                    << " bytes instead of " << sizeof(MDRawContextARM)
                    << std::endl;
          continue;
        }
        MDRawContextARM* arm = new MDRawContextARM();
        memcpy(arm, &cpu_state_raw[0], cpu_state_raw.size());
        context_->SetContextARM(arm);
      } else if (strcmp(arch.c_str(), kArm64Architecture) == 0) {
        if (cpu_state_raw.size() == sizeof(MDRawContextARM64)) {
          MDRawContextARM64* arm = new MDRawContextARM64();
          memcpy(arm, &cpu_state_raw[0], cpu_state_raw.size());
          context_->SetContextARM64(arm);
        } else if (cpu_state_raw.size() == sizeof(MDRawContextARM64_Old)) {
          MDRawContextARM64_Old old_arm;
          memcpy(&old_arm, &cpu_state_raw[0], cpu_state_raw.size());
          MDRawContextARM64* new_arm = new MDRawContextARM64();
          ConvertOldARM64Context(old_arm, new_arm);
          context_->SetContextARM64(new_arm);
        } else {
          std::cerr << "Malformed CPU context. Got " << cpu_state_raw.size()
                    << " bytes instead of " << sizeof(MDRawContextARM64)
                    << std::endl;
          continue;
        }
      } else if (strcmp(arch.c_str(), kX86Architecture) == 0) {
        if (cpu_state_raw.size() != sizeof(MDRawContextX86)) {
          std::cerr << "Malformed CPU context. Got " << cpu_state_raw.size()
                    << " bytes instead of " << sizeof(MDRawContextX86)
                    << std::endl;
          continue;
        }
        MDRawContextX86* x86 = new MDRawContextX86();
        memcpy(x86, &cpu_state_raw[0], cpu_state_raw.size());
        context_->SetContextX86(x86);
      } else if (strcmp(arch.c_str(), kMipsArchitecture) == 0) {
        if (cpu_state_raw.size() != sizeof(MDRawContextMIPS)) {
          std::cerr << "Malformed CPU context. Got " << cpu_state_raw.size()
                    << " bytes instead of " << sizeof(MDRawContextMIPS)
                    << std::endl;
          continue;
        }
        MDRawContextMIPS* mips32 = new MDRawContextMIPS();
        memcpy(mips32, &cpu_state_raw[0], cpu_state_raw.size());
        context_->SetContextMIPS(mips32);
      } else if (strcmp(arch.c_str(), kMips64Architecture) == 0) {
        if (cpu_state_raw.size() != sizeof(MDRawContextMIPS)) {
          std::cerr << "Malformed CPU context. Got " << cpu_state_raw.size()
                    << " bytes instead of " << sizeof(MDRawContextMIPS)
                    << std::endl;
          continue;
        }
        MDRawContextMIPS* mips64 = new MDRawContextMIPS();
        memcpy(mips64, &cpu_state_raw[0], cpu_state_raw.size());
        context_->SetContextMIPS64(mips64);
      } else {
        std::cerr << "Unsupported architecture: " << arch << std::endl;
      }
    } else if ((pos = line.find(kCrashReasonKey)) != string::npos) {
      string crash_reason_str(line, pos + strlen(kCrashReasonKey));
      std::istringstream crash_reason_tokens(crash_reason_str);
      string signal;
      string address;
      crash_reason_tokens >> signal;
      crash_reason_tokens >> crash_reason_;
      crash_reason_tokens >> address;
      crash_address_ = HexStrToL<uint64_t>(address);
    } else if ((pos = line.find(kGpuKey)) != string::npos) {
      string gpu_str(line, pos + strlen(kGpuKey));
      if (strcmp(gpu_str.c_str(), kGpuUnknown) != 0) {
        std::istringstream gpu_tokens(gpu_str);
        std::getline(gpu_tokens, system_info_->gl_version, '|');
        std::getline(gpu_tokens, system_info_->gl_vendor, '|');
        std::getline(gpu_tokens, system_info_->gl_renderer, '|');
      }
    } else if ((pos = line.find(kMmapKey)) != string::npos) {
      string mmap_line(line, pos + strlen(kMmapKey));
      std::istringstream mmap_tokens(mmap_line);
      string addr, offset, size, identifier, filename;
      mmap_tokens >> addr;
      mmap_tokens >> offset;
      mmap_tokens >> size;
      mmap_tokens >> identifier;
      mmap_tokens >> filename;

      modules_->Add(new BasicCodeModule(
          HexStrToL<uint64_t>(addr),  // base_address
          HexStrToL<uint64_t>(size),  // size
          filename,                   // code_file
          identifier,                 // code_identifier
          filename,                   // debug_file
          identifier,                 // debug_identifier
          ""));                       // version
    }
  }
  stack_region_->Init(stack_start, stack_content);
}

}  // namespace google_breakpad


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:background="#AA000000" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_info" />

    <TextView
        android:paddingLeft="10dp"
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="TextView" />

</LinearLayout>


text:
		Diagnosis Reference Number
		Disease Date
		Diagnosis Patron Code
		Diagnosis Comment
		Diagnosis Physician Code
		Actions

	<?php foreach($diagnosis_summary as $d){ ?>

		<?php echo $d['diagnosis_reference_number']; ?>
		<?php echo $d['disease_date']; ?>
		<?php echo $d['diagnosis_patron_code']; ?>
		<?php echo $d['diagnosis_comment']; ?>
		<?php echo $d['diagnosis_physician_code']; ?>

            <a href="<?php echo site_url('diagnosis_summary/edit/'.$d['diagnosis_reference_number']); ?>">Edit |
            <a href="<?php echo site_url('diagnosis_summary/remove/'.$d['diagnosis_reference_number']); ?>">Delete

	<?php } ?>


text:
namespace url_rewrite {
namespace {

constexpr char kMixedCaseCorsExemptHeader[] = "CoRs-ExEmPt";
constexpr char kUpperCaseCorsExemptHeader[] = "CORS-EXEMPT";
constexpr char kMixedCaseCorsExemptHeader2[] = "Another-CoRs-ExEmPt-2";
constexpr char kUpperCaseCorsExemptHeader2[] = "ANOTHER-CORS-EXEMPT-2";
constexpr char kRequiresCorsHeader[] = "requires-cors";

}  // namespace

class URLLoaderThrottleTest : public testing::Test {
 public:
  URLLoaderThrottleTest()
      : task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
  ~URLLoaderThrottleTest() override = default;

  URLLoaderThrottle::IsHeaderCorsExemptCallback CreateCorsExemptHeadersCallback(
      std::vector<std::string> cors_exempt_headers) {
    return base::BindLambdaForTesting(
        [cors_exempt_headers](base::StringPiece header) {
          LOG(INFO) << "HEADER: " << header;
          for (const auto& exempt_header : cors_exempt_headers) {
            if (base::EqualsCaseInsensitiveASCII(header, exempt_header)) {
              return true;
            }
          }
          return false;
        });
  }

 protected:
  base::test::SingleThreadTaskEnvironment task_environment_;
};

// Tests rules are properly applied when wildcard-filtering is used on hosts.
TEST_F(URLLoaderThrottleTest, WildcardHosts) {
  mojom::UrlRequestRewriteAddHeadersPtr add_headers =
      mojom::UrlRequestRewriteAddHeaders::New();
  add_headers->headers.push_back(mojom::UrlHeader::New("Header", "Value"));
  mojom::UrlRequestActionPtr rewrite =
      mojom::UrlRequestAction::NewAddHeaders(std::move(add_headers));
  std::vector<mojom::UrlRequestActionPtr> actions;
  actions.push_back(std::move(rewrite));
  mojom::UrlRequestRulePtr rule = mojom::UrlRequestRule::New();
  rule->hosts_filter = absl::optional<std::vector<std::string>>({"*.test.net"});
  rule->actions = std::move(actions);
  mojom::UrlRequestRewriteRulesPtr rules = mojom::UrlRequestRewriteRules::New();
  rules->rules.push_back(std::move(rule));

  URLLoaderThrottle throttle(
      base::MakeRefCounted<UrlRequestRewriteRules>(std::move(rules)),
      CreateCorsExemptHeadersCallback({}));
  bool defer = false;

  network::ResourceRequest request1;
  request1.url = GURL("http://test.net");
  throttle.WillStartRequest(&request1, &defer);
  EXPECT_TRUE(request1.headers.HasHeader("Header"));

  network::ResourceRequest request2;
  request2.url = GURL("http://subdomain.test.net");
  throttle.WillStartRequest(&request2, &defer);
  EXPECT_TRUE(request2.headers.HasHeader("Header"));

  network::ResourceRequest request3;
  request3.url = GURL("http://domaintest.net");
  throttle.WillStartRequest(&request3, &defer);
  EXPECT_FALSE(request3.headers.HasHeader("Header"));

  network::ResourceRequest request4;
  request4.url = GURL("http://otherdomain.net");
  throttle.WillStartRequest(&request4, &defer);
  EXPECT_FALSE(request4.headers.HasHeader("Header"));
}

// Verifies that injected headers are correctly exempted from CORS checks if
// their names are registered as CORS exempt.
TEST_F(URLLoaderThrottleTest, CorsAwareHeaders) {
  mojom::UrlRequestRewriteAddHeadersPtr add_headers =
      mojom::UrlRequestRewriteAddHeaders::New();
  add_headers->headers.push_back(
      mojom::UrlHeader::New(kRequiresCorsHeader, "Value"));

  // Inject the uppercased form for CORS exempt header #1, and the mixed case
  // form of header #2.
  add_headers->headers.push_back(
      mojom::UrlHeader::New(kUpperCaseCorsExemptHeader, "Value"));
  add_headers->headers.push_back(
      mojom::UrlHeader::New(kMixedCaseCorsExemptHeader2, "Value"));

  mojom::UrlRequestActionPtr rewrite =
      mojom::UrlRequestAction::NewAddHeaders(std::move(add_headers));
  std::vector<mojom::UrlRequestActionPtr> actions;
  actions.push_back(std::move(rewrite));
  mojom::UrlRequestRulePtr rule = mojom::UrlRequestRule::New();
  rule->hosts_filter = absl::optional<std::vector<std::string>>({"*.test.net"});
  rule->actions = std::move(actions);

  mojom::UrlRequestRewriteRulesPtr rules = mojom::UrlRequestRewriteRules::New();
  rules->rules.push_back(std::move(rule));

  // Use the mixed case form for CORS exempt header #1, and the uppercased form
  // of header #2.
  URLLoaderThrottle throttle(
      base::MakeRefCounted<UrlRequestRewriteRules>(std::move(rules)),
      CreateCorsExemptHeadersCallback(
          {kMixedCaseCorsExemptHeader, kUpperCaseCorsExemptHeader2}));

  network::ResourceRequest request;
  request.url = GURL("http://test.net");
  bool defer = false;
  throttle.WillStartRequest(&request, &defer);
  EXPECT_FALSE(defer);

  // Verify that the cors-exempt and cors-required headers were partitioned into
  // the "cors_exempt_headers" and "headers" arrays, respectively.
  EXPECT_TRUE(
      request.cors_exempt_headers.HasHeader(kUpperCaseCorsExemptHeader));
  EXPECT_TRUE(
      request.cors_exempt_headers.HasHeader(kMixedCaseCorsExemptHeader2));
  EXPECT_TRUE(request.headers.HasHeader(kRequiresCorsHeader));

  // Verify that the headers were not also placed in the other array.
  EXPECT_FALSE(request.cors_exempt_headers.HasHeader(kRequiresCorsHeader));
  EXPECT_FALSE(request.headers.HasHeader(kUpperCaseCorsExemptHeader));
  EXPECT_FALSE(request.headers.HasHeader(kMixedCaseCorsExemptHeader2));
}

// Tests URL replacement rules that replace to a data URL do not append query or
// ref from the original URL.
TEST_F(URLLoaderThrottleTest, DataReplacementUrl) {
  const char kCssDataURI[] = "data:text/css,";

  mojom::UrlRequestRewriteReplaceUrlPtr replace_url =
      mojom::UrlRequestRewriteReplaceUrl::New();
  replace_url->url_ends_with = ".css";
  replace_url->new_url = GURL(kCssDataURI);
  mojom::UrlRequestActionPtr rewrite =
      mojom::UrlRequestAction::NewReplaceUrl(std::move(replace_url));
  std::vector<mojom::UrlRequestActionPtr> actions;
  actions.push_back(std::move(rewrite));
  mojom::UrlRequestRulePtr rule = mojom::UrlRequestRule::New();
  rule->hosts_filter = absl::optional<std::vector<std::string>>({"*.test.net"});
  rule->actions = std::move(actions);

  mojom::UrlRequestRewriteRulesPtr rules = mojom::UrlRequestRewriteRules::New();
  rules->rules.push_back(std::move(rule));

  URLLoaderThrottle throttle(
      base::MakeRefCounted<UrlRequestRewriteRules>(std::move(rules)),
      CreateCorsExemptHeadersCallback({}));
  bool defer = false;

  network::ResourceRequest request;
  request.url = GURL("http://test.net/style.css?query#ref");
  throttle.WillStartRequest(&request, &defer);
  EXPECT_EQ(request.url, base::StringPiece(kCssDataURI));
}

class TestThrottleDelegate : public blink::URLLoaderThrottle::Delegate {
 public:
  TestThrottleDelegate() = default;
  ~TestThrottleDelegate() override = default;

  bool canceled() const { return canceled_; }
  base::StringPiece cancel_reason() const { return cancel_reason_; }

  void Reset() {
    canceled_ = false;
    cancel_reason_.clear();
  }

  // URLLoaderThrottle::Delegate implementation.
  void CancelWithError(int error_code,
                       base::StringPiece custom_reason) override {
    canceled_ = true;
    cancel_reason_ = std::string(custom_reason);
  }
  void Resume() override {}

 private:
  bool canceled_ = false;
  std::string cancel_reason_;
};

// Tests that resource loads can be allowed or blocked based on the
// UrlRequestAction policy.
TEST_F(URLLoaderThrottleTest, AllowAndDeny) {
  mojom::UrlRequestRewriteRulesPtr rules = mojom::UrlRequestRewriteRules::New();

  {
    mojom::UrlRequestRulePtr rule = mojom::UrlRequestRule::New();
    rule->hosts_filter = absl::optional<std::vector<std::string>>({"test.net"});
    rule->actions.push_back(mojom::UrlRequestAction::NewPolicy(
        mojom::UrlRequestAccessPolicy::kAllow));
    rules->rules.push_back(std::move(rule));
  }
  {
    mojom::UrlRequestRulePtr rule = mojom::UrlRequestRule::New();
    rule->actions.push_back(mojom::UrlRequestAction::NewPolicy(
        mojom::UrlRequestAccessPolicy::kDeny));
    rules->rules.push_back(std::move(rule));
  }

  URLLoaderThrottle throttle(
      base::MakeRefCounted<UrlRequestRewriteRules>(std::move(rules)),
      CreateCorsExemptHeadersCallback({}));
  bool defer = false;

  TestThrottleDelegate delegate;
  throttle.set_delegate(&delegate);

  network::ResourceRequest request1;
  request1.url = GURL("http://test.net");
  throttle.WillStartRequest(&request1, &defer);
  EXPECT_FALSE(delegate.canceled());

  delegate.Reset();

  network::ResourceRequest request2;
  request2.url = GURL("http://blocked.net");
  throttle.WillStartRequest(&request2, &defer);
  EXPECT_TRUE(delegate.canceled());
  EXPECT_EQ(delegate.cancel_reason(),
            "Resource load blocked by embedder policy.");
}

}  // namespace url_rewrite


text:
describe('SFTP', function(tnv) {
  var scope = {};

  describe('connect', function() {

    describe('connect to real sftp', function() {

      after(function(done) {
        scope.sftp && scope.sftp.disconnect(done);
      });

      it('test connection to host with wrong private key file', function(done) {
        scope.sftp = new tnv.Sftp({
          host: tnv.host,
          username: tnv.username,
          privateKey: ''
        }, function(err) {
          should.exist(err);
          err.message.should.eql('permission denied');
          done();
        });
      });

      it('test connection to host with private key file', function(done) {
        scope.sftp = new tnv.Sftp({
          host: tnv.host,
          username: tnv.username,
          privateKey: tnv.privateKey
        }, function(err) {
          should.not.exist(err);
          done();
        });
      });

      it('test connection to host with home dir set', function(done) {
        scope.sftp = new tnv.Sftp({
          host: tnv.host,
          username: tnv.username,
          home: "/home/" + tnv.username,
          privateKey: tnv.privateKey
        }, function(err) {
          should.not.exist(err);

          scope.sftp.pwd(function(err, path) {
            assert.equal(err, null);
            assert.equal(path, "/home/" + tnv.username);
            done();
          });
        });
      });
    });

    describe('connection msg errors with mocked sftp', function() {

      before(function(done) {
        scope.pty = require('pty.js');
        scope.EventEmitter = require('events').EventEmitter;

        sinon.stub(scope.pty, 'spawn', function() {
          scope.emitter = new scope.EventEmitter();
          return scope.emitter;
        });

        done();
      });

      after(function() {
        scope.pty.spawn.restore();
      });

      it('Operation timed out', function(done) {
        scope.sftp = new tnv.Sftp({}, function(err) {
          err.message.should.eql('Operation timed out');
          done();
        });

        setTimeout(function() {
          scope.emitter.emit('data', 'Operation timed out');
        }, 100)
      });

      it('Connection closed', function(done) {
        scope.sftp = new tnv.Sftp({}, function(err) {
          err.message.should.eql('Connection closed');
          done();
        });

        setTimeout(function() {
          scope.emitter.emit('data', 'Connection closed');
        }, 100)
      });

      it('Connection timed out', function(done) {
        scope.sftp = new tnv.Sftp({}, function(err) {
          err.message.should.eql('Connection timed out');
          done();
        });

        setTimeout(function() {
          scope.emitter.emit('data', 'Connection timed out');
        }, 100)
      });

      it('Connection reset by peer', function(done) {
        scope.sftp = new tnv.Sftp({}, function(err) {
          err.message.should.eql('Connection reset by peer');
          done();
        });

        setTimeout(function() {
          scope.emitter.emit('data', 'Connection reset by peer');
        }, 100)
      });
    });
  });

  describe('sftp commands after connection', function() {

    before(function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);
        done();
      });
    });

    after(function(done) {
      scope.sftp && scope.sftp.disconnect(done);
    });

    it('test disconnecting from remote host', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        home: "/home/" + tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.disconnect(function(err) {
          should.not.exist(err);
          done();
        });
      });
    });

    it('test sending CD command to localhost', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.cd("/tmp", function(err) {
          should.not.exist(err);
          done();
        });
      });
    });

    it('read non-existing file', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readFile('thisfiledoesnotexist.js', 'utf-8', function(err) {
          err.code.should.eql('ENOENT');
          done();
        });
      });
    });

    it('read root dir', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readdir('/', function(err, list) {
          should.not.exist(err);
          list.length.should.be.gt(1);
          done();
        });
      });
    });

    it('read non-existing dir', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readdir('/tmp/xyz', function(err, dir) {
          should.not.exist(err);
          dir.length.should.eql(0);
          done();
        });
      });
    });

    it('read existing dir', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readdir('/tmp', function(err) {
          should.not.exist(err);
          done();
        });
      });
    });

    it('write file', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        var filePath = __dirname + '/assets/a.js',
          file = tnv.fs.readFileSync(filePath, "utf8");

        scope.sftp.writeFile('a.js', file, 'utf8', true, function(err) {
          should.not.exist(err);

          scope.sftp.stat('a.js', function(err, stat) {
            should.not.exist(err);

            tnv.fs.statSync(filePath).size.should.eql(stat.size);
            stat.isFile().should.eql(true);
            stat.isDirectory().should.eql(false);

            done();
          });
        });
      });
    });

    it('write file (check that file exists is false)', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        var filePath = __dirname + '/assets/a.js',
          file = tnv.fs.readFileSync(filePath, "utf8");

        scope.sftp.writeFile('a.js', file, 'utf8', false, function(err) {
          should.not.exist(err);
          done();
        });
      });
    });

    it('read existing file (utf8)', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readFile('a.js', 'utf-8', function(err, data) {
          should.not.exist(err);
          Buffer.isBuffer(data).should.eql(false);
          done();
        });
      });
    });

    it('read existing file (buffer)', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.readFile('a.js', null, function(err, data) {
          should.not.exist(err);
          Buffer.isBuffer(data).should.eql(true);
          done();
        });
      });
    });

    it('write dir', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.mkdir('/tmp/test', true, function(err) {
          should.not.exist(err);

          scope.sftp.stat('/tmp/test', function(err, stat) {
            should.not.exist(err);

            stat.isFile().should.eql(false);
            stat.isDirectory().should.eql(true);

            done();
          });
        });
      });
    });

    it('remove file', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);
        scope.sftp.unlink("a.js", done);
      });
    });

    it('remove dir', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);
        scope.sftp.rmdir("/tmp/test", done);
      });
    });

    it('pwd', function(done) {
      scope.sftp = new tnv.Sftp({
        host: tnv.host,
        username: tnv.username,
        privateKey: tnv.privateKey
      }, function(err) {
        should.not.exist(err);

        scope.sftp.pwd(function(err, dir) {
          should.not.exist(err);
          dir.should.eql("/home/" + tnv.username);
          done();
        });
      });
    });
  });
});


text:
using IntelliTect.Coalesce.CodeGeneration.Generation;
using IntelliTect.Coalesce.Tests.Util;
using IntelliTect.Coalesce.Validation;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace IntelliTect.Coalesce.CodeGeneration.Tests
{
    public class CodeGenTestBase
    {
        protected GenerationExecutor BuildExecutor()
        {
            return new GenerationExecutor(
                new Configuration.CoalesceConfiguration
                {
                    WebProject = new Configuration.ProjectConfiguration
                    {
                        RootNamespace = "MyProject"
                    }
                },
                Microsoft.Extensions.Logging.LogLevel.Information
            );
        }

        protected async Task AssertSuiteOutputCompiles(IRootGenerator suite)
        {
            var project = new DirectoryInfo(Directory.GetCurrentDirectory())
                .FindFileInAncestorDirectory("IntelliTect.Coalesce.CodeGeneration.Tests.csproj")
                .Directory;

            var suiteName = suite.GetType().Name;

            var tfmAttr = Assembly.GetExecutingAssembly().GetCustomAttribute<TargetFrameworkAttribute>();

            suite = suite
                .WithOutputPath(Path.Combine(project.FullName, "out", tfmAttr.FrameworkName, suiteName));

            var validationResult = ValidateContext.Validate(suite.Model);
            Assert.Empty(validationResult.Where(r => r.IsError));

            // While not needed for any test assertions,
            // we actually generate the output to disk so that we can look at it
            // in case we need to diagnose a failure or something.
            await suite.GenerateAsync();

            var generators = suite
                .GetGeneratorsFlattened()
                .OfType<IFileGenerator>()
                .Where(g => g.EffectiveOutputPath.EndsWith(".cs"))
                .ToList();

            var tasks = generators.Select(gen => (Generator: gen, Output: gen.GetOutputAsync()));
            await Task.WhenAll(tasks.Select(t => t.Output ));

            var dtoFiles = tasks
                .Select((task) => CSharpSyntaxTree.ParseText(
                    SourceText.From(new StreamReader(task.Output.Result).ReadToEnd()),
                    path: task.Generator.EffectiveOutputPath
                ))
                .ToArray();

            var comp = ReflectionRepositoryFactory.GetCompilation(dtoFiles);
            AssertSuccess(comp);
        }

        protected void AssertSuccess(CSharpCompilation comp)
        {
            var errors = comp
                .GetDiagnostics()
                .Where(d => d.Severity >= Microsoft.CodeAnalysis.DiagnosticSeverity.Error);

            Assert.All(errors, error =>
            {
                var loc = error.Location;

                Assert.False(true, "\"" + error.ToString() +
                    $"\" near:```\n" +
                    loc.SourceTree.ToString().Substring(loc.SourceSpan.Start, loc.SourceSpan.Length) +
                    "\n```"
                );
            });
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3(2): 518 (1898)

#### Original name
Polyporus geotropus Cooke, 1884

### Remarks
null


text:
(function() {
    'use strict';

    angular
        .module('ohmageApp')
        .config(stateConfig);

    stateConfig.$inject = ['$stateProvider'];

    function stateConfig($stateProvider) {
        $stateProvider.state('jhi-health', {
            parent: 'admin',
            url: '/health',
            data: {
                authorities: ['ROLE_ADMIN'],
                pageTitle: 'Health Checks'
            },
            views: {
                'content@': {
                    templateUrl: 'app/admin/health/health.html',
                    controller: 'JhiHealthCheckController',
                    controllerAs: 'vm'
                }
            }
        });
    }
})();


text:
import { Rooms, Subscriptions, Messages } from '../../../models';
import { callbacks } from '../../../callbacks';

export const addUserToDefaultChannels = function(user, silenced) {
	callbacks.run('beforeJoinDefaultChannels', user);
	const defaultRooms = Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch();
	defaultRooms.forEach((room) => {
		if (!Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)) {
			// Add a subscription to this user
			Subscriptions.createWithRoomAndUser(room, user, {
				ts: new Date(),
				open: true,
				alert: true,
				unread: 1,
				userMentions: 1,
				groupMentions: 0,
				...room.favorite && { f: true },
			});

			// Insert user joined message
			if (!silenced) {
				Messages.createUserJoinWithRoomIdAndUser(room._id, user);
			}
		}
	});
};


text:
package weekendhacks.com.kahahaibosedk;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.widget.TextView;

/**
 * Created by nishantr on 8/13/16.
 */
public class Utility {

    String mPhoneNumber;
    public String getPhoneNumber(Context context) {
        TelephonyManager phoneManager = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        mPhoneNumber = phoneManager.getLine1Number();
        return mPhoneNumber;
    }
}


text:
'use strict';

RegisterController.$inject = ['$rootScope', '$state', 'AuthService'];

function RegisterController($rootScope, $state, AuthService) {
    let controller = this;

    controller.invalidUsername = false;
    controller.invalidEmail = false;

    controller.register = register;

	init();

    ////////////////////////////

	function init() {
		if (AuthService.isAuthenticated) {
			$state.go('dashboard');
		}
	}

    function register(credentials) {
        return AuthService.register(credentials)
            .then(function(response) {
                $state.go('dashboard');
            })
            .catch(function(response) {
				if (response.data.message === "Username taken") {
					controller.invalidUsername = true;
				    controller.invalidEmail = false;
				} else if (response.data.message === 'Email taken') {
					controller.invalidUsername = false;
				    controller.invalidEmail = true;
				}
				return response;
            });
    }
}

module.exports = RegisterController;


text: NASA Space Apps Sydney 2017 hackathon - Spotting migratory bird species in real-time


text:
<!DOCTYPE html>

	<meta charset=utf-8>
	<title>Get the number of all car brands listed as NEW</title>


text:
from __future__ import division, absolute_import, print_function

from numpy.testing import TestCase, run_module_suite, assert_array_equal
from f2py_ext import fib2

class TestFib2(TestCase):

    def test_fib(self):
        assert_array_equal(fib2.fib(6), [0, 1, 1, 2, 3, 5])

if __name__ == "__main__":
    run_module_suite()


text:
module RelayPlay
  module Types
    RegionType = GraphQL::ObjectType.define do
      name 'Region'

      field :name, !types.String
      connection :fairies, -> { RelayPlay::Types::FairyConnection }
    end
  end
end


text:
from bitHopper.Website import app, flask
import btcnet_info
import bitHopper.Configuration.Workers
from bitHopper.Logic.ServerLogic import get_current_servers, valid_scheme
from bitHopper.Tracking.Tracking import get_hashrate
import logging
import json
import btcnet_info
from flask import Response

def transform_data(servers):
    for server in servers:
        item = {}
        for value in ['name', 'shares', 'coin']:
            if getattr(server, value) != None:
                item[value] = getattr(server, value)
            else:
                item[value] = 'undefined'
        item['shares'] = float(item.get('shares',0)) if item['shares'] != 'undefined' else 'undefined'
        item['payout'] = 0.0
        item['expected_payout'] = 0.0
        item['role'] = 'mine/backup' if server in valid_scheme([server]) else 'info'
        yield item

@app.route("/data", methods=['POST', 'GET'])
def data():
    response = {}
    response['current'] = ', '.join([s.name for s in get_current_servers()])
    response['mhash'] = get_hashrate()
    response['diffs'] = dict([(coin.name, float(coin.difficulty)) for coin in btcnet_info.get_coins() if coin.difficulty])
    response['sliceinfo'] = None
    response['servers'] = list(transform_data(btcnet_info.get_pools()))
    response['user'] = None

    return Response(json.dumps(response), mimetype='text/json')


text:
/* eslint-disable */

$(document).ready(init)

function init() {
  $('.otherResidentsInput').append(
    'Add resident'
  )
  $('.otherResidentsInput a').on('click', addResidentFields)
}

function addResidentFields() {
  var numberRegEx = /\d+/g
  var indexRegEx = /dents\]\[(.*?)\[/g

  var group = $(this).closest('.otherResidentsInput')
  var finalResident = group.find('.resident:last')

  var indexContainingSegment = finalResident
    .find('input.residentName')
    .attr('name')
    .match(indexRegEx)
  var indexes = indexContainingSegment[0].match(numberRegEx)
  var newIndex = parseInt(indexes[indexes.length - 1]) + 1

  var newName = finalResident
    .find('input.residentName')
    .attr('name')
    .replace(indexRegEx, 'dents][' + newIndex + '][')
  var newAge = finalResident
    .find('input.residentAge')
    .attr('name')
    .replace(indexRegEx, 'dents][' + newIndex + '][')
  var newRelation = finalResident
    .find('input.residentRelation')
    .attr('name')
    .replace(indexRegEx, 'dents][' + newIndex + '][')

  var newResident = finalResident.clone()
  newResident
    .find('input.residentName')
    .attr('name', newName)
    .val('')
  newResident
    .find('input.residentAge')
    .attr('name', newAge)
    .val('')
  newResident
    .find('input.residentRelation')
    .attr('name', newRelation)
    .val('')

  $(finalResident).after(newResident)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for PaymentPay
/// </summary>
public class PaymentPay
{
    public PaymentPay(string paymentID, string stripeRefNum)
    {
        PaymentID = paymentID;
        StripeRefNum = stripeRefNum;
    }

    public PaymentPay() { }

    public string PaymentID { get; set; }
    public string StripeRefNum { get; set; }
}


text:
from splinter import Browser
from django.contrib.auth.models import Group, User
from rapidsms.models import Connection, Backend, Contact
from poll.models import Poll
from rapidsms_httprouter.models import Message
from rapidsms_httprouter.router import get_router
from ureport.models import PollAttribute, PollAttributeValue
from ureport_project.rapidsms_ureport.ureport.models import UPoll

def create_group(group_name):
    group = Group.objects.create(name=group_name)
    return group

def create_user(username, email, group):
    user1 = User.objects.create(username=username, email=email)
    user1.groups.add(group)
    user1.save()
    return user1

def create_connection(identity, contact, backend):
    connection = Connection.objects.create(identity=identity, backend=backend)
    connection.contact = contact
    connection.save()
    return connection

def create_poll(user, name, question):
    poll_name = name
    question = question
    poll = Poll.objects.create(name=poll_name, question=question, user=user, type=Poll.TYPE_TEXT)

    if not PollAttribute.objects.filter(key='viewable').exists():
        PollAttribute.objects.create(key='viewable', key_type='bool', default=True)

    upoll = UPoll.objects.get(pk=poll.pk)
    upoll.set_attr('viewable', True)
    upoll.save()

    return poll

def add_contacts_to_poll(poll, contacts):
    for contact in contacts:
        poll.contacts.add(contact)
    poll.save()

def simulate_response(connection, incoming_message):
    router = get_router()
    incoming = router.handle_incoming(connection.backend.name, connection.identity, incoming_message)
    return incoming

def if_exists_delete_group(groupname):
    try:
        group = Group.objects.get(name=groupname)
        Group.delete(group)
    except Group.DoesNotExist:
        pass

def if_exists_delete_user(username):
    try:
        user = User.objects.get(username=username)
        User.delete(user)
    except User.DoesNotExist:
        pass

def if_exists_delete_contact(name):
    try:
        contact = Contact.objects.get(name=name)
        Contact.delete(contact)
    except Contact.DoesNotExist:
        pass

def if_it_exists_delete_poll_called(poll_name):
    try:
        poll = Poll.objects.get(name=poll_name)
        Poll.delete(poll)
    except Poll.DoesNotExist:
        pass

    if_exists_delete_group()
    if_exists_delete_user()

def if_exists_delete_backend(name):
    try:
        backend = Backend.objects.get(name=name)
        Backend.delete(backend)
    except Backend.DoesNotExist:
        pass

def create_poll_called(poll_name):
    group = create_group(group_name='Pagination Group')
    user = create_user(username="foo", email='foo@bar.com', group=group)
    poll = Poll.objects.create(name=poll_name, question="question", user=user, type=Poll.TYPE_TEXT)
    return poll


text:
import express from 'express'
const router = express.Router()

import stats from './stats'

router.post('/stats', stats)

export default router


text:
import React from 'react';
import { render } from '@testing-library/react-native';
import { NativeBaseProvider } from '../../../../core/NativeBaseProvider';

import Switch from '../index';

jest.useFakeTimers();
describe('Switch', () => {
  it('can be default checked', () => {
    let { getAllByRole } = render(
      <NativeBaseProvider
        initialWindowMetrics={{
          frame: { x: 0, y: 0, width: 0, height: 0 },
          insets: { top: 0, left: 0, right: 0, bottom: 0 },
        }}
      >
        <Switch defaultIsChecked />
      </NativeBaseProvider>
    );
    let switches = getAllByRole('switch');
    expect(switches[0].props.value).toBe(true);
  });

  it('can be disabled', () => {
    let { getAllByRole } = render(
      <NativeBaseProvider
        initialWindowMetrics={{
          frame: { x: 0, y: 0, width: 0, height: 0 },
          insets: { top: 0, left: 0, right: 0, bottom: 0 },
        }}
      >
        <Switch isDisabled />
      </NativeBaseProvider>
    );
    let switches = getAllByRole('switch');
    expect(switches[0].props.disabled).toBe(true);
  });
});


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/pci.h>
#include <linux/spinlock.h>

#define PMBASE_OFFSET 0xb0
#define PMBASE_SIZE   0x30

#define AMD_REG_GPIO(i) (0x10 + (i))

#define AMD_GPIO_LTCH_STS	0x40 /* Latch status, w1 */
#define AMD_GPIO_RTIN		0x20 /* Real Time in, ro */
#define AMD_GPIO_DEBOUNCE	0x10 /* Debounce, rw */
#define AMD_GPIO_MODE_MASK	0x0c /* Pin Mode Select, rw */
#define AMD_GPIO_MODE_IN	0x00
#define AMD_GPIO_MODE_OUT	0x04
/* Enable alternative (e.g. clkout, IRQ, etc) function of the pin */
#define AMD_GPIO_MODE_ALTFN	0x08 /* Or 0x09 */
#define AMD_GPIO_X_MASK		0x03 /* In/Out specific, rw */
#define AMD_GPIO_X_IN_ACTIVEHI	0x01 /* Active High */
#define AMD_GPIO_X_IN_LATCH	0x02 /* Latched version is selected */
#define AMD_GPIO_X_OUT_LOW	0x00
#define AMD_GPIO_X_OUT_HI	0x01
#define AMD_GPIO_X_OUT_CLK0	0x02
#define AMD_GPIO_X_OUT_CLK1	0x03

/*
 * Data for PCI driver interface
 *
 * This data only exists for exporting the supported
 * PCI ids via MODULE_DEVICE_TABLE.  We do not actually
 * register a pci_driver, because someone else might one day
 * want to register another driver on the same PCI id.
 */
static const struct pci_device_id pci_tbl[] = {
	{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS), 0 },
	{ 0, },	/* terminate list */
};
MODULE_DEVICE_TABLE(pci, pci_tbl);

struct amd_gpio {
	struct gpio_chip	chip;
	u32			pmbase;
	void __iomem		*pm;
	struct pci_dev		*pdev;
	spinlock_t		lock; /* guards hw registers and orig table */
	u8			orig[32];
};

static int amd_gpio_request(struct gpio_chip *chip, unsigned offset)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);

	agp->orig[offset] = ioread8(agp->pm + AMD_REG_GPIO(offset)) &
		(AMD_GPIO_DEBOUNCE | AMD_GPIO_MODE_MASK | AMD_GPIO_X_MASK);

	dev_dbg(&agp->pdev->dev, "Requested gpio %d, data %x\n", offset, agp->orig[offset]);

	return 0;
}

static void amd_gpio_free(struct gpio_chip *chip, unsigned offset)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);

	dev_dbg(&agp->pdev->dev, "Freed gpio %d, data %x\n", offset, agp->orig[offset]);

	iowrite8(agp->orig[offset], agp->pm + AMD_REG_GPIO(offset));
}

static void amd_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);
	u8 temp;
	unsigned long flags;

	spin_lock_irqsave(&agp->lock, flags);
	temp = ioread8(agp->pm + AMD_REG_GPIO(offset));
	temp = (temp & AMD_GPIO_DEBOUNCE) | AMD_GPIO_MODE_OUT | (value ? AMD_GPIO_X_OUT_HI : AMD_GPIO_X_OUT_LOW);
	iowrite8(temp, agp->pm + AMD_REG_GPIO(offset));
	spin_unlock_irqrestore(&agp->lock, flags);

	dev_dbg(&agp->pdev->dev, "Setting gpio %d, value %d, reg=%02x\n", offset, !!value, temp);
}

static int amd_gpio_get(struct gpio_chip *chip, unsigned offset)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);
	u8 temp;

	temp = ioread8(agp->pm + AMD_REG_GPIO(offset));

	dev_dbg(&agp->pdev->dev, "Getting gpio %d, reg=%02x\n", offset, temp);

	return (temp & AMD_GPIO_RTIN) ? 1 : 0;
}

static int amd_gpio_dirout(struct gpio_chip *chip, unsigned offset, int value)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);
	u8 temp;
	unsigned long flags;

	spin_lock_irqsave(&agp->lock, flags);
	temp = ioread8(agp->pm + AMD_REG_GPIO(offset));
	temp = (temp & AMD_GPIO_DEBOUNCE) | AMD_GPIO_MODE_OUT | (value ? AMD_GPIO_X_OUT_HI : AMD_GPIO_X_OUT_LOW);
	iowrite8(temp, agp->pm + AMD_REG_GPIO(offset));
	spin_unlock_irqrestore(&agp->lock, flags);

	dev_dbg(&agp->pdev->dev, "Dirout gpio %d, value %d, reg=%02x\n", offset, !!value, temp);

	return 0;
}

static int amd_gpio_dirin(struct gpio_chip *chip, unsigned offset)
{
	struct amd_gpio *agp = gpiochip_get_data(chip);
	u8 temp;
	unsigned long flags;

	spin_lock_irqsave(&agp->lock, flags);
	temp = ioread8(agp->pm + AMD_REG_GPIO(offset));
	temp = (temp & AMD_GPIO_DEBOUNCE) | AMD_GPIO_MODE_IN;
	iowrite8(temp, agp->pm + AMD_REG_GPIO(offset));
	spin_unlock_irqrestore(&agp->lock, flags);

	dev_dbg(&agp->pdev->dev, "Dirin gpio %d, reg=%02x\n", offset, temp);

	return 0;
}

static struct amd_gpio gp = {
	.chip = {
		.label		= "AMD GPIO",
		.owner		= THIS_MODULE,
		.base		= -1,
		.ngpio		= 32,
		.request	= amd_gpio_request,
		.free		= amd_gpio_free,
		.set		= amd_gpio_set,
		.get		= amd_gpio_get,
		.direction_output = amd_gpio_dirout,
		.direction_input = amd_gpio_dirin,
	},
};

static int __init amd_gpio_init(void)
{
	int err = -ENODEV;
	struct pci_dev *pdev = NULL;
	const struct pci_device_id *ent;

	/* We look for our device - AMD South Bridge
	 * I don't know about a system with two such bridges,
	 * so we can assume that there is max. one device.
	 *
	 * We can't use plain pci_driver mechanism,
	 * as the device is really a multiple function device,
	 * main driver that binds to the pci_device is an smbus
	 * driver and have to find & bind to the device this way.
	 */
	for_each_pci_dev(pdev) {
		ent = pci_match_id(pci_tbl, pdev);
		if (ent)
			goto found;
	}
	/* Device not found. */
	goto out;

found:
	err = pci_read_config_dword(pdev, 0x58, &gp.pmbase);
	if (err)
		goto out;
	err = -EIO;
	gp.pmbase &= 0x0000FF00;
	if (gp.pmbase == 0)
		goto out;
	if (!request_region(gp.pmbase + PMBASE_OFFSET, PMBASE_SIZE, "AMD GPIO")) {
		dev_err(&pdev->dev, "AMD GPIO region 0x%x already in use!\n",
			gp.pmbase + PMBASE_OFFSET);
		err = -EBUSY;
		goto out;
	}
	gp.pm = ioport_map(gp.pmbase + PMBASE_OFFSET, PMBASE_SIZE);
	if (!gp.pm) {
		dev_err(&pdev->dev, "Couldn't map io port into io memory\n");
		release_region(gp.pmbase + PMBASE_OFFSET, PMBASE_SIZE);
		err = -ENOMEM;
		goto out;
	}
	gp.pdev = pdev;
	gp.chip.parent = &pdev->dev;

	spin_lock_init(&gp.lock);

	printk(KERN_INFO "AMD-8111 GPIO detected\n");
	err = gpiochip_add_data(&gp.chip, &gp);
	if (err) {
		printk(KERN_ERR "GPIO registering failed (%d)\n",
		       err);
		ioport_unmap(gp.pm);
		release_region(gp.pmbase + PMBASE_OFFSET, PMBASE_SIZE);
		goto out;
	}
out:
	return err;
}

static void __exit amd_gpio_exit(void)
{
	gpiochip_remove(&gp.chip);
	ioport_unmap(gp.pm);
	release_region(gp.pmbase + PMBASE_OFFSET, PMBASE_SIZE);
}

module_init(amd_gpio_init);
module_exit(amd_gpio_exit);

MODULE_AUTHOR("The Linux Kernel team");
MODULE_DESCRIPTION("GPIO driver for AMD chipsets");
MODULE_LICENSE("GPL");


text:
namespace Three {
    CaseNode* CaseNode::parse(Parser& parser) {
        assert(parser.helper()->nextIf(Token::Type::KeywordCase));

        CaseNode* node = new CaseNode();

        node->_argumentNode = parser.parseExpression();

        if (!parser.helper()->parseNewline()) {
            assert(0 && "Message: case argument must be followed by a newline");
            return node;
        }

        bool success = parser.helper()->parseUntil(false, [&] (const Token& token) {
            switch (token.type()) {
                case Token::Type::KeywordEnd:
                case Token::Type::KeywordCase:
                case Token::Type::KeywordElse:
                    return true;
                default:
                    node->addChild(parser.parseStatement());
                    return false;
                }
        });

        if (!success) {
            assert(0 && "Message: unable to parse case body");
        }

        return node;
    }

    std::string CaseNode::nodeName() const {
        return "Case";
    }

    std::string CaseNode::name() const {
        return "Case";
    }

    ASTNode* CaseNode::argument() const {
        return this->_argumentNode;
    }
}


text:
<?php

namespace Solarium\Tests;
use Solarium\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{

    public function testVersion()
    {
        $version = Client::VERSION;
        $this->assertNotNull($version);
    }

    public function testCheckExact()
    {
        $this->assertTrue(
            Client::checkExact(Client::VERSION)
        );
    }

    public function testCheckExactPartial()
    {
        $this->assertTrue(
            Client::checkExact(substr(Client::VERSION,0,1))
        );
    }

    public function testCheckExactLower()
    {
        $this->assertFalse(
            Client::checkExact('0.1')
        );
    }

    public function testCheckExactHigher()
    {
        $this->assertFalse(
            Client::checkExact('99.0')
        );
    }

    public function testCheckMinimal()
    {
        $this->assertTrue(
            Client::checkMinimal(Client::VERSION)
        );
    }

    public function testCheckMinimalPartial()
    {
        $version = substr(Client::VERSION,0,1);

        $this->assertTrue(
            Client::checkMinimal($version)
        );
    }

    public function testCheckMinimalLower()
    {
        $this->assertTrue(
            Client::checkMinimal('0.1.0')
        );
    }

    public function testCheckMinimalHigher()
    {
        $this->assertFalse(
            Client::checkMinimal('99.0')
        );
    }

}


text:
@interface JMContainerController : UIViewController

@end


text:
'use strict';

var Router = require('./router'),
    Route = require('./route'),
    methods = require('./methods');

module.exports = {
    Router: Router,
    Route: Route,
    methods: methods,

    /**
     *
     * @return {Router}
     */
    router: function router() {
        return new Router();
    },

    /**
     *
     * @param {String} method
     * @param {String} path
     * @param {Function} handler
     * @return {Route}
     */
    route: function route(method, path, handler) {
        return new Route(method, path, handler);
    }
};