text:
#include <sys/types.h>
#include <string.h>
#include <sys/resource.h>

#include "java/io/FileDescriptor.h"
#include "java/lang/UnsupportedOperationException.h"
#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
#include "jlong.h"
#include "java_lang_Integer.h"
#include "nio.h"
#include "nio_util.h"

/* J2ObjC: unused.
#define NATIVE_METHOD(className, functionName, signature) \
{ #functionName, signature, (void*)(className ## _ ## functionName) }

static jfieldID fd_fdID;        // for jint 'fd' in java.io.FileDescriptor

static void IOUtil_initIDs(JNIEnv *env)
{
    jclass clazz = (*env)->FindClass(env, "java/io/FileDescriptor");
    fd_fdID = (*env)->GetFieldID(env, clazz, "descriptor", "I");
}
*/

JNIEXPORT jboolean JNICALL
Java_sun_nio_ch_IOUtil_randomBytes(JNIEnv *env, jclass clazz,
                                  jbyteArray randArray)
{
    J2ObjCThrowByName(JavaLangUnsupportedOperationException, nil);
    return JNI_FALSE;
}

JNIEXPORT jint JNICALL
Java_sun_nio_ch_IOUtil_fdVal(JNIEnv *env, jclass clazz, jobject fdo)
{
    return ((JavaIoFileDescriptor *)fdo)->descriptor_;
}

JNIEXPORT void JNICALL
Java_sun_nio_ch_IOUtil_setfdVal(JNIEnv *env, jclass clazz, jobject fdo, jint val)
{
    ((JavaIoFileDescriptor *)fdo)->descriptor_ = val;
}

static int
configureBlocking(int fd, jboolean blocking)
{
    int flags = fcntl(fd, F_GETFL);
    int newflags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);

    return (flags == newflags) ? 0 : fcntl(fd, F_SETFL, newflags);
}

JNIEXPORT void JNICALL
Java_sun_nio_ch_IOUtil_configureBlocking(JNIEnv *env, jclass clazz,
                                         jobject fdo, jboolean blocking)
{
    if (configureBlocking(fdval(env, fdo), blocking) < 0)
        JNU_ThrowIOExceptionWithLastError(env, "Configure blocking failed");
}

JNIEXPORT jlong JNICALL
Java_sun_nio_ch_IOUtil_makePipe(JNIEnv *env, jobject this, jboolean blocking)
{
    int fd[2];

    if (pipe(fd) < 0) {
        JNU_ThrowIOExceptionWithLastError(env, "Pipe failed");
        return 0;
    }
    if (blocking == JNI_FALSE) {
        if ((configureBlocking(fd[0], JNI_FALSE) < 0)
            || (configureBlocking(fd[1], JNI_FALSE) < 0)) {
            JNU_ThrowIOExceptionWithLastError(env, "Configure blocking failed");
            close(fd[0]);
            close(fd[1]);
            return 0;
        }
    }
    return ((jlong) fd[0] << 32) | (jlong) fd[1];
}

JNIEXPORT jboolean JNICALL
Java_sun_nio_ch_IOUtil_drain(JNIEnv *env, jclass cl, jint fd)
{
    char buf[128];
    int tn = 0;

    for (;;) {
        int n = (int)read(fd, buf, sizeof(buf));
        tn += n;
        if ((n < 0) && (errno != EAGAIN))
            JNU_ThrowIOExceptionWithLastError(env, "Drain");
        if (n == (int)sizeof(buf))
            continue;
        return (tn > 0) ? JNI_TRUE : JNI_FALSE;
    }
}

JNIEXPORT jint JNICALL
Java_sun_nio_ch_IOUtil_fdLimit(JNIEnv *env, jclass this)
{
    struct rlimit rlp;
    if (getrlimit(RLIMIT_NOFILE, &rlp) < 0) {
        JNU_ThrowIOExceptionWithLastError(env, "getrlimit failed");
        return -1;
    }
    // Android-changed: Remove the rlimit < 0 check.
    if (rlp.rlim_max > java_lang_Integer_MAX_VALUE) {
        return java_lang_Integer_MAX_VALUE;
    } else {
        return (jint)rlp.rlim_max;
    }
}

/* Declared in nio_util.h for use elsewhere in NIO */

jint
convertReturnVal(JNIEnv *env, jint n, jboolean reading)
{
    if (n > 0) /* Number of bytes written */
        return n;
    else if (n == 0) {
        if (reading) {
            return IOS_EOF; /* EOF is -1 in javaland */
        } else {
            return 0;
        }
    }
    else if (errno == EAGAIN)
        return IOS_UNAVAILABLE;
    else if (errno == EINTR)
        return IOS_INTERRUPTED;
    else {
        const char *msg = reading ? "Read failed" : "Write failed";
        JNU_ThrowIOExceptionWithLastError(env, msg);
        return IOS_THROWN;
    }
}

JNIEXPORT jint JNICALL
Java_sun_nio_ch_IOUtil_iovMax(JNIEnv *env, jclass this)
{
    jlong iov_max = sysconf(_SC_IOV_MAX);
    if (iov_max == -1)
        iov_max = 16;
    return (jint)iov_max;
}

/* Declared in nio_util.h for use elsewhere in NIO */

jlong
convertLongReturnVal(JNIEnv *env, jlong n, jboolean reading)
{
    if (n > 0) /* Number of bytes written */
        return n;
    else if (n == 0) {
        if (reading) {
            return IOS_EOF; /* EOF is -1 in javaland */
        } else {
            return 0;
        }
    }
    else if (errno == EAGAIN)
        return IOS_UNAVAILABLE;
    else if (errno == EINTR)
        return IOS_INTERRUPTED;
    else {
        const char *msg = reading ? "Read failed" : "Write failed";
        JNU_ThrowIOExceptionWithLastError(env, msg);
        return IOS_THROWN;
    }
}

jint
fdval(JNIEnv *env, jobject fdo)
{
    return ((JavaIoFileDescriptor *)fdo)->descriptor_;
}

/* J2ObjC unused.
static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(IOUtil, iovMax, "()I"),
  NATIVE_METHOD(IOUtil, fdLimit, "()I"),
  NATIVE_METHOD(IOUtil, drain, "(I)Z"),
  NATIVE_METHOD(IOUtil, makePipe, "(Z)J"),
  NATIVE_METHOD(IOUtil, configureBlocking, "(Ljava/io/FileDescriptor;Z)V"),
  NATIVE_METHOD(IOUtil, setfdVal, "(Ljava/io/FileDescriptor;I)V"),
  NATIVE_METHOD(IOUtil, fdVal, "(Ljava/io/FileDescriptor;)I"),
  NATIVE_METHOD(IOUtil, randomBytes, "([B)Z"),
};

void register_sun_nio_ch_IOUtil(JNIEnv* env) {
  jniRegisterNativeMethods(env, "sun/nio/ch/IOUtil", gMethods, NELEM(gMethods));

  IOUtil_initIDs(env);
}
*/

redpajama_set_name: RedPajamaGithub


text:
@interface MyMainViewController ()

@end

@implementation MyMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self buildLayout];
}

- (void)buildLayout{
    [self.view setFrame:CGRectMake(0, 108, self.view.frame.size.width, self.view.frame.size.height-140)];
    [self.view setBackgroundColor:UIColorFromRGB(0xF4F8FB)];
    [self.tableView setTableFooterView:[[UIView alloc] init]];
    [self.tableView setScrollEnabled:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                [self.collectController setTitle:@"收藏"];
                [self.navController pushViewController:self.collectController animated:YES];
            }
                break;
            case 1:{

            }
                break;
            case 2:{

            }
                break;
            case 3:{
                [self.feedbackController setTitle:@"反馈"];
                [self.feedbackController.feedbackTextView setText:@""];
                [self.navController pushViewController:self.feedbackController animated:YES];
            }
                break;
            case 4:{
                [self.settingController setTitle:@"设置"];
                [self.navController pushViewController:self.settingController animated:YES];
            }
                break;
            default:
                break;
        }
    }
    if (indexPath.section == 1) {
        [self logout];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *mycellidentifier = @"MyMainCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mycellidentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mycellidentifier];
    }
    [cell.textLabel setTextColor:UIColorFromRGB(0x5b5b5b)];
    [cell.textLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:16]];
    if (indexPath.section == 0) {
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        switch (indexPath.row) {
            case 0:
                [cell.textLabel setText:@"收藏"];
                break;
            case 1:
                [cell.textLabel setText:@"活动"];
                break;
            case 2:
                [cell.textLabel setText:@"消息"];
                break;
            case 3:
                [cell.textLabel setText:@"反馈"];
                break;
            case 4:
                [cell.textLabel setText:@"设置"];
                break;
            default:
                break;
        }
    }else{
        [cell.textLabel setText:@"退出登录"];
        [cell.textLabel setTextAlignment:NSTextAlignmentCenter];
    }

    return cell;
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}
//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view;
    if (section == 0) {
        view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 15)];
    }else{
        view = [[UIView alloc] init];
    }
    return view;
}

- (void) logout{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate setWeiboInfo:[NSMutableDictionary dictionary]];
    [[NSUserDefaults standardUserDefaults] setObject:delegate.weiboInfo forKey:@"WB_INFO"];
    [delegate setWeixinInfo:[NSMutableDictionary dictionary]];
    [[NSUserDefaults standardUserDefaults] setObject:delegate.weixinInfo forKey:@"WX_INFO"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [delegate.rootTabController setSelectedIndex:0];
    [delegate setIsLogin:NO];
}

- (MySettingsViewController *)settingController{
    if (!_settingController) {
        _settingController = [[MySettingsViewController alloc] init];
    }
    return _settingController;
}

- (CollectViewController *)collectController{
    if (!_collectController) {
        _collectController = [[CollectViewController alloc] init];
    }
    return _collectController;
}

- (FeedbackViewController *)feedbackController{
    if (!_feedbackController) {
        _feedbackController = [[FeedbackViewController alloc] init];
    }
    return _feedbackController;
}

@end


text:
blurr
-----

blurr is simple and flexible tool for database benchmarking. It's written in Go and supports custom database drivers and workloads.

Prerequisites
-------------

* go
* bzr

Installation
------------

    go get github.com/couchbaselabs/blurr

Usage
-----

    blurr workload.conf

Configuration files
-------------------

blurr uses JSON format for configuration. There are two groups of parameters, example is below:

    {
        "Database": {
            "Driver": "MongoDB",
            "Name": "default",
            "Table": "default",
            "Addresses": [
                "10.2.2.1:27017",
                "10.2.2.2:27017",
                "10.2.2.3:27017"
            ]
        },
        "Workload": {
            "Type": "N1QL",
            "CreatePercentage": 4,
            "ReadPercentage": 60,
            "UpdatePercentage": 32,
            "DeletePercentage": 4,
            "Records": 100000,
            "Operations": 100000,
            "ValueSize": 2048,
            "Workers": 16,
            "Throughput": 2000,
            "HotDataPercentage": 20,
            "HotSpotAccessPercentage": 95,
            "RunTime": 3600,
            "QueryWorkers": 10,
            "QueryThroughput": 100,
            "Indexes": [
        		"coins_stats_by_state_and_year",
        		"street_by_year_and_coins",
        		"distinct_years"
        	]
        }
    }

Basic parameters:

* Database.Driver - database driver for benchmark (MongoDB, Couchbase, Tuq or Cassandra)
* Database.Name - name of database
* Database.Table - name of table, collection, bucket and etc.
* Database.Addresses - list of host:port string to use in connection pool
* Workload.Type - workload type (Default, HotSpot or N1QL)
* Workload.(Create|Read|Update|Delete)Percentage - CRUD operations ratio, sum must be equal 100
* Workload.Records - number of existing records(rows, documents) in database before benchmark
* Workload.Operations - total number of operations to perform, defines benchmark run time
* Workload.ValueSize - size of synthetic values
* Workload.Workers - number of concurrent CRUD workers (threads, clients, and etc.)
* Workload.Throughput - enable limited throughput of CRUD ops if provided
* Workload.HotDataPercentage - percentage of hot records in dataset (HotSpot workload)
* Workload.HotSpotAccessPercentage - percentage of operations that hit hot subset (HotSpot workload)
* Workload.RunTime - optional benchmark run time in seconds

Additional parameters for [secondary indexes](https://github.com/couchbaselabs/blurr/wiki/Queries-on-secondary-indexes):

* Workload.QueryWorkers - number of concurrent query workers
* Workload.QueryThroughput - enable limited throughput of queries if provided
* Workload.Indexes - [optional] list of secondary indexes


text:
module NetCDFOutputModule
!------------------------------------------------------------------------------
! Lagrangian Particle / Panel Method - Spherical Model
!------------------------------------------------------------------------------
!> @author
!> Peter Bosler, Department of Mathematics, University of Michigan
!
!
!> @defgroup NetCDFOut NetCDF Output
!> Provides data structures and methods for outputting data from SphereMesh objects into NetCDF file format.
!
!
! DESCRIPTION:
!> @file
!> Provides data structures and methods for outputting data from SphereMesh objects into NetCDF file format.
!
!------------------------------------------------------------------------------
use NumberKindsModule
use SphereGeomModule
use IntegerListModule
use LoggerModule
use ParticlesModule
use EdgesModule
use PanelsModule
use SphereMeshModule
use STRIPACKInterfaceModule
use SSRFPACKInterfaceModule
use netcdf

implicit none
private
public NetCDFSource
public New, Delete
public OutputNetCDF, UpdateFilename

type NetCDFSource
	character(len=MAX_STRING_LENGTH) :: filename
end type

!
!----------------
! Interfaces
!----------------
!
interface New
	module procedure NewPrivate
end interface

interface Delete
	module procedure DeletePrivate
end interface

interface UpdateFilename
	module procedure UpdateFilenamePrivate
end interface

contains
!
!----------------
! Standard methods : Constructor / Destructor, Copy
!----------------
!
subroutine NewPrivate(self, aMesh, filename )
	type(NetCDFSource), intent(out) :: self
	type(SphereMesh), intent(in) :: aMesh
	character(len=*), intent(in) :: filename
	self%filename = trim(filename)
end subroutine

subroutine DeletePrivate(self)
	type(NetCDFSource), intent(inout) :: self
end subroutine

!
!----------------
! Public functions
!----------------
!
subroutine UpdateFilenamePrivate(self, filename)
	type(NetCDFSource), intent(inout) :: self
	character(len=*), intent(in) :: filename
	self%filename = trim(filename)
end subroutine

subroutine OutputNativeDataToNetCDF(self, aMesh)
	type(NetCDFSource), intent(in) :: self
	type(SphereMesh), intent(in) :: aMesh
	!
	type(Particles), pointer :: aParticles
	type(Panels), pointer :: aPanels
	integer(kint) :: ncID
	integer(kint) :: nParticles
	integer(kint) :: nActive
	integer(kint) :: passiveXID, passiveYID, passiveZID, activeXId, activeYId, activeZID
	character(len=*), parameter :: latName = "latitude"
	character(len=*), parameter :: lonName = "longitude"
	character(len=*), parameter :: xName = "x"
	character(len=*), parameter :: yName = "y"
	character(len=*), parameter :: zName = "z"
	character(len=*), parameter :: alpha_xName = "alpha_x"
	character(len=*), parameter :: alpha_yName = "alpha_y"
	character(len=*), parameter :: alpha_zName = "alpha_z"
	character(len=*), parameter :: units = "units"
	character(len=*), parameter :: relVortUnits = "seconds^{-1}"
	character(len=*), parameter :: absVortUnits = "seconds^{-1}"
	character(len=*), parameter :: streamUnits = "metersSquared_per_seconds"
	character(len=*), parameter :: velocityUnits = "metersPerSecond"
	character(len=*), parameter :: tracerUnits = "tracerUnits"
	character(len=*), parameter :: xUnits = "earthRadii"
	character(len=*), parameter :: yUnits = "earthRadii"
	character(len=*), parameter :: zUnits = "earthRadii"
	character(len=*), parameter :: latUnits = "degrees_north"
	character(len=*), parameter :: lonUnits = "degrees_east"
	real(kreal), allocatable :: passiveLon(:), passiveLat(:), activeLon(:), activeLat(:)

	aParticles => aMesh%particles
	aPanels=>aMesh%panels
	nParticles = aParticles%n
	nActive = aPanels%N_Active

	call check( NF90_Create(self%filename, NF90_NETCDF4, ncID) )

	!
	! Define the coordinate variables
	!
!	call check( NF90_Def_Dim(ncID, "passive_x ", nParticles, passiveXID)
!	call check( NF90_Def_Dim(ncID, "passive_y ", nParticles, passiveYID)
!	call check( NF90_Def_Dim(ncID, "passive_z ", nParticles, passiveZID)
!	call check( NF90_Def_Dim(ncID, "active_x ", nActive, activeXID)
!	call check( NF90_Def_Dim(ncID, "active_y ", nActive, activeYID)
!	call check( NF90_Def_Dim(ncID, "active_z ", nActive, activeZID)
	call check( NF90_Def_Dim(ncID, "passive_Lon ", nParticles, passiveLonID)
	call check( NF90_Def_Dim(ncID, "passive_Lat ", nParticles, passiveLatID)
	call check( NF90_Def_Dim(ncID, "active_Lon ", nActive, activeLonID)
	call check( NF90_Def_Dim(ncID, "active_Lat ", nActive, activeLatID)

	!
	! Define the field variables
	!

end subroutine

subroutine check(status)
	 integer, intent ( in) :: status
	 if(status /= nf90_noerr) then
	   !print *, trim(nf90_strerror(status))
	   call LogMessage(log, ERROR_LOGGING_LEVEL,"NetCDF ERROR : ", status)
	 end if
end subroutine check

end module


text:
namespace render_framework
{
	// Forward declarations
	struct cube_map;
	struct effect;

	// Structure representing a skybox in the scene
	struct skybox
	{
		// Texture used by the sky box
		std::shared_ptr<cube_map> tex;
		// Effect used by the sky box
		std::shared_ptr<effect> eff;
	};
}


text:
/* $Id $*/
/* Copyright 2000, 2001, Compaq Computer Corporation */

package javafe.parser;

import java.io.IOException;
import java.util.Hashtable;

import javafe.ast.Identifier;
import javafe.ast.PrettyPrint;
import javafe.ast.LexicalPragma;
import javafe.ast.LexicalPragmaVec;
import javafe.ast._SpecialParserInterface;

import javafe.util.Assert;
import javafe.util.ErrorSet;
import javafe.util.CorrelatedReader;
import javafe.util.Location;

//@ model import javafe.tc.TagConstants;

/**

 A <TT>Lex</TT> object generates a sequence of Java "input elements"
 (that is, tokens) by converting the sequence of input characters and
 line terminators generated by an underlying
 CorrelatedReader.

 The conversion of input characters occurs according to the lexical
 rules in Chapter Three of the Java Language
 Specification.  This specification describes three lexical
 translation steps: the first two steps translate a raw Unicode input
 stream into a "cooked" one in which Unicode escape characters from the
 raw stream have been processed and in which line terminators have been
 identified; the last step translates this cooked stream into a
 sequence of Java "input elements" (comments, white space, identifiers,
 tokens, literals, and punctuation).  Lex objects perform
 the last of these translations steps; the first two are performed by
 an underlying CorrelatedReader that is given to the
 Lex object as the source of input characters.

 Before a newly-created Lex object can be used, its
 restart method must be called giving a
 CorrelatedReader to scan.  At any point, a
 Lex can be restarted on a different underlying reader.

 The <TT>Lex</TT> class is thread safe, but instances of
 <TT>Lex</TT> are not.  That is, two different threads may safely
 access two different instances of <TT>Lex</TT> concurrently, but they
 may not access the same instance of <TT>Lex</TT> concurrently.

 Simple scanning

 The getNextToken method of Lex objects
 returns the translated token sequence, one token at a time.  It
 discards white space, and it processes comments as described below.
 In addition, getNextToken fills in the Token
 fields of this (Lex is a subclass of
 Token); for example, ttype gets an integer
 code defining the type of token returned and startingLoc
 gives the location of the first character making up the token.  If the
 token is an identifier, identifierVal indicates which
 one; if the token is a literal, auxVal gives its value.

 Lex objects report errors by calling both the
 fatal and error methods of
 ErrorSet.  The fatal errors are unexpected characters,
 unterminated comments and string and character literals, and IO errors
 in the underlying input stream.  Recoverable errors are overflows in
 literals (including overflows in octal escape sequences), non-octal
 digits in integer literals, the string 0x (interpreted as
 a malformed integer literal), missing digits in a floating-point
 exponent, bad escape sequences in character and string literals,
 character literals containing no or multiple characters, and the
 character literal ''' (interpreted as '\'').

 Lookahead

 Lex objects allow their clients to peek ahead into the
 token stream by calling lookahead.  This method returns
 the token code for the future token, but it does not affect the
 Token fields of this.

 If a call to lookahead needs to look past the set of
 tokens already scanned, and those tokens have errors, then the errors
 are reported immediately.

 Extensibility: Keywords, punctuation

 A keyword is a Java identifier with a special token code.
 Ordinarily, identifiers are associated with the code
 TagConstants.IDENT.  Keywords, while matching the lexical
 grammar of identifiers, are associated with different codes.  In fact,
 each keyword is typically associated with its own code.

 The set of identifiers that a Lex object recognizes
 as keywords is extensible.  A keyword is added to a Lex
 object by calling the addKeyword method.  As a
 convenience, a boolean given to the Lex constructor
 indicates whether a newly-constructed Lex object should
 automatically have all Java keywords added to it.

 A punctuation string is a string of punctuation characters
 recognized by a Lex object to be a token.  (Punctuation
 characters are non-alphanumeric ASCII characters whose ASCII codes are
 between 33 ('!')  and 126 ('~') inclusive.)  As with keywords, the set
 of punctuation strings recognized by a Lex object is
 extensible.  A punctuation string is added to a Lex
 object by calling the addPunctuation method.  A boolean
 given to the Lex constructor indicates whether a
 newly-constructed Lex object should automatically have
 all Java punctuation strings added to it.

 Extensibility: comments and pragmas

 The handling of comments is special in two ways: the punctuation
 strings that start comments is extensible, the text of comments can be
 parsed for pragmas.

 Comment recognition

 Ordinarily, keywords and punctuation strings are mapped to token
 codes that are returned by calls to getNextToken.
 However, two token codes are treated specially:
 TagConstants.C_COMMENT and TagConstants.EOL_COMMENT.
 These codes are used to indicate the start of C-like comments
 (/*...*/) and end-of-line comments
 (//...), respectively.  When a keyword or punctuation
 string is mapped to these codes, it is handled like a comment
 initiator rather than a regular token.

 For all newly-created Lex objects, /* is
 mapped to TagConstants.C_COMMENT and // is mapped
 to TagConstants.EOL_COMMENT.  Other punctuation strings can be
 made comment initiators by mapping them to comment-initiating codes.
 This is more useful for TagConstants.EOL_COMMENT than for
 TagConstants.C_COMMENT, since the string
 */ is hard-wired as the terminator of C-like
 comments.

 Pragma parsing

 Lex objects are designed to support annotation of Java
 programs through pragmas.  A
 separate document  describes our overall aproach to pragmas.  In
 brief, our front-end supports two kinds of pragmas: control pragmas
 that can appear anywhere in an input file and are collected in a list
 apart from the parse tree, and syntax pragmas that can only appear in
 certain grammatical contexts and become part of the parse tree.
 Pragmas always appear in Java comments, at most one pragma per
 comment.  These comments must have one of the following forms:

 <menu>

 /*tag white-space pragma-text*/

 //tag white-space-minus-EOL pragma-text EOL
 </menu>

 When a Lex object is created, it can optionally be
 associated with a PragmaParser object.  If a
 Lex object has no PragmaParser, it discards
 all comments.  Otherwise, the Lex object passes the first
 character of the comment (or -1 if the comment is empty) to the
 checkTag method of the PragmaParser object,
 which returns false if the comment definitely does not
 contain any pragmas.  If the comment may contain pragmas, the
 Lex object bundles the text between the delimiters of a
 comment into a CorrelatedReader which it passes to the
 restart method of its PragmaParser.  (This
 text excludes both the opening /* or // and
 the closing */ or line terminator.)

 The Lex object then calls getNextPragma
 to read the pragmas out of the comment one at a time.  The
 Lex object does this in a lazy manner; that is, it reads
 a pragma, returns it to the parser, and waits until the parser calls
 for the next token before it attempts to read another pragma.  The
 getNextPragma method returns a boolean, returning
 false if there are no more pragmas to be parsed.  The
 getNextPragma method takes a Token as an
 argument, storing information about the pragma parsed into this
 argument.

 When PragmaParser.getNextPragma returns a
 LexicalPragma, the Lex object puts it in an
 internal list rather than returning it to the parser.  The list of
 collected lexical pragmas can be retrieved by calling
 getLexicalPragmas.

 @see javafe.util.CorrelatedReader
 @see javafe.parser.ParserTagConstants
 @see javafe.parser.ParserToken
 @see javafe.parser.PragmaParser

 */

public class Lex extends ParserToken
{
    //// Underlying input stream

    /**
     * Current state of input stream underlying the scanner minus the
     * first character.  See m_nextchr.

     *
     * This is null iff we are closed.
     */

    /*@ spec_public @*/ protected CorrelatedReader m_in = null;

    /** Each call to getNextToken reads ahead one character
     and leaves the result in m_nextchr.  In other words,
     between calls to getNextToken, the stream of
     characters yet-to-scanned consists of the character in
     m_nextchr followed by the characters remaining in
     m_in. */

    protected int m_nextchr;

    //// Buffer used to hold the actual char's making up a token.

    // The exact characters making up a token are copied into this array
    // for all tokens.  Although in some cases this isn't needed (e.g.,
    // for string literals), we do it anyway in case someday we want to
    // export that ability of getting a token's exact text rather than
    // its interpretation, esp. in the case of literals.

    /** The characters that constitute the current token.  Only the
     first <TT>textlen</TT> characters are part of the current token;
     the actual length of <TT>text</TT> may be bigger.  The lexer may
     occasionally need to resize <TT>text</TT>, so the same array might
     not be used throughout the lifetime of the lexer.  */

    //@ invariant text != null;
    //@ invariant text.length > 4;
    protected char[] text = new char[64]; // Invariant: text.length > 4
    // 64 should be large enough that overflows won't happen for most inputs

    /** The number of characters in the current token.  The "current
     token" is the one parsed by the previous call to
     <TT>getNextToken</TT> (there is no "current token" between
     creation of a lexer and the first call to getNextToken).  */

    //@ invariant 0 <= textlen &&  textlen <= text.length;
    protected int textlen = 0;

    /** Append 'c' to text, expanding if necessary. */
    //@ modifies text, textlen;
    //@ ensures textlen == \old(textlen)+1;
    protected void append(int c) {
        try {
            text[textlen] = (char)c;		//@ nowarn IndexTooBig;  // caught
        } catch (ArrayIndexOutOfBoundsException e) {
            //@ assume textlen>=text.length;
            char[] newtext = new char[textlen + 128];
            System.arraycopy(text, 0, newtext, 0, textlen);
            text = newtext;
            text[textlen] = (char)c;
        }
        textlen++;
    }

    //// Instance variables for token queue and pragma parsing

    protected final TokenQueue lookaheadq = new TokenQueue();

    public /*@ non_null @*/ LexicalPragmaVec lexicalPragmas;

    //@ invariant inPragma ==> pragmaParser != null;
    protected PragmaParser pragmaParser;
    protected boolean inPragma;

    //// Constructors

    /**
     * Creates a lexical analyzer that will tokenize the characters
     * read from an underlying CorrelatedReader.  Before
     * the newly-created scanner can be used, its restart
     * method must be called on a CorrelatedReader.  The
     * pragmaParser object is used to parse pragmas out
     * of comments; if it is null, all comments are
     * discarded.  The isJava flag controls the initial
     * set of keywords and punctuation strings; if true,
     * the new scanner will recognize Java's keywords and punctuation
     * strings, if false, the new scanner will recognize
     * no keywords or punctuation strings.  If
     * isJava is true, the token codes used for the
     * Java's keywords and punctuation strings are those defined by
     * the TagConstants class.
     */

    //@ ensures m_in==null;
    public Lex(PragmaParser pragmaParser, boolean isJava) {
	this.pragmaParser = pragmaParser;
	lexicalPragmas = LexicalPragmaVec.make();

	inPragma = false;
	if (isJava) {
	    addJavaKeywords();
	    addJavaPunctuation();
	} else {
	    addPunctuation("/*", ParserTagConstants.C_COMMENT);
	    addPunctuation("//", ParserTagConstants.EOL_COMMENT);
	}
    }

    /** Start scaning a new CorrelatedReader.  First closes
     the old CorrelatedReader associated with
     this (if there was one), and clears out the set of
     collected lexical pragms.  In addition to (re)-seting the
     underlying input stream, this method scans the first token,
     returning the token kind of the result and setting the
     Token fields of this.  If a
     CorrelatedReader is already underlying
     this, it is closed before the new reader is
     installed.  Note: The argument in is "captured" in
     the internal, private state of the resulting scanner and should
     not be used by other parts of the program. */
    //@ public normal_behavior
    //@ modifies m_in, ttype, auxVal, identifierVal, lexicalPragmas;
    //@ ensures m_in != null;
    //@ also
    //@ protected normal_behavior
    //@ modifies m_nextchr;
    public int restart(/*@ non_null @*/ CorrelatedReader in) {
	close();
	try {
	    m_in = in;
	    m_nextchr = m_in.read();
	} catch (IOException e) {
	    ErrorSet.fatal(m_in.getLocation(), e.toString());
	    return ParserTagConstants.NULL; // Dummy
	}
	return getNextToken();
    }

    /** Closes the CorrelatedReader underlying
     this, clears the set of collected lexical pragmas,
     and in other ways frees up resources associated with
     this.  After being closed, a Lex object
     can be restarted by calling restart.  (An IO
     exception raised by closing the underlying input stream will be
     converted into a javafe.util.FatalError runtime
     exception.) */
    //@ public normal_behavior
    //@ modifies m_in, lexicalPragmas;
    //@ ensures m_in==null;
    //@ also
    //@ protected normal_behavior
    //@ modifies inPragma;
    public void close() {
        if (m_in != null) {
	    m_in.close();
	}
	m_in = null;
	lookaheadq.clear();
	if (pragmaParser != null) {
	    pragmaParser.close();
	    lexicalPragmas = LexicalPragmaVec.make();
	}
	inPragma = false;
    }

    //// Public members for scanning

    public void replaceLookaheadToken(int k, ParserToken t) {
	lookaheadq.setElementAt(k,t);
    }

    /** Scans next token from input stream.  Returns the code of the
     next token in the token stream and fills in the Token
     fields of this.  Note that the
     startingLoc and endingLoc fields of
     this are not accurate for the end-of-file token. */

    //@ public normal_behavior
    //@ requires m_in != null;
    //@ modifies ttype, auxVal, identifierVal;
    //@ also
    //@ protected normal_behavior
    //@ modifies inPragma, m_nextchr;
    public int getNextToken() {
        if (lookaheadq.notempty) {
            lookaheadq.dequeue(this);
            return ttype;
        }

        for(;;) {
            if (inPragma)
                if (! pragmaParser.getNextPragma(this)) {
                    inPragma = false;
                } else if (ttype != ParserTagConstants.LEXICALPRAGMA) {
                    return ttype;
                } else {
                    lexicalPragmas.addElement((LexicalPragma)this.auxVal);
                    continue;
                }

            int t = scanToken();
            if (t != ParserTagConstants.C_COMMENT &&
                t != ParserTagConstants.EOL_COMMENT) {
                return t;
            }
            else {
		scanComment(t);
	    }
        }
    }

    /** Returns token type of the <TT>k</TT>th future token, where k=0
     is the current token.  If k is past the end of the
     token stream, TagConstants.EOF is returned. */

    //@ requires k>=0;
    //@ requires m_in != null;
    public int lookahead(int k) {
        if (k == 0) return ttype;
        int lookahead_count = lookaheadq.size();

        if (lookahead_count < k) { // Need to add more tokens in lookahead buffer
            this.copyInto(savedState);
            try {
                for(int deficit = k - lookahead_count; 0 < deficit; deficit--) {
                    for(;;) {
                        if (inPragma)
                            if (! pragmaParser.getNextPragma(this))
                                inPragma = false;
                            else if (ttype != ParserTagConstants.LEXICALPRAGMA)
                                break;
                            else {
                                lexicalPragmas.addElement((LexicalPragma)this.auxVal);
                                continue;
                            }

                        int t = scanToken();
                        if (t != ParserTagConstants.C_COMMENT
                            && t != ParserTagConstants.EOL_COMMENT)
                            break;
                        else scanComment(t);
                    }
                    lookaheadq.enqueue(this);
                }
            } finally {
                savedState.copyInto(this);
                savedState.clear();
            }
        }
        return lookaheadq.elementAt(k-1).ttype;
    }
    //@ invariant savedState != null;
    protected ParserToken savedState = new ParserToken();

    public ParserToken lookaheadToken(int k) {
	if (k==0) return this;
	lookahead(k);
	return lookaheadq.elementAt(k-1);
    }

    /** Returns the set of lexical pragmas collected.  It also clears
     the set of lexical pragmas so that the next call will not include
     them.  (If this lexer has no PragmaParser, then an
     empty vector is returned.) */

    //@ ensures \result != null;
    public LexicalPragmaVec getLexicalPragmas() {
        return lexicalPragmas.copy();
    }

    /**
     * Remove the first LexicalPragma from our set of lexical pragmas
     * collected, returning it or null if our set is empty.
     */
    public LexicalPragma popLexicalPragma() {
	if (lexicalPragmas.size()>0)
	    return lexicalPragmas.pop();

	return null;
    }

    //// Internal scanning routines

    /** Returns the code of the next token in the token stream, updating
     the Token fields of this along the way.
     Advances underlying stream to the character just past the last
     character of the token returned, and changes the internal buffer
     used by getTokenText to contain the text of this
     token.

 In most cases, this method leaves m_nextchr
     holding the character just after the token scanned and
     m_in pointing to the character after that.  However,
     if TagConstants.C_COMMENT or
     TagConstants.EOL_COMMENT is returned, it leaves
     m_in pointing to the character just after the token
     scanned and m_nextchr undefined.  This aids in pragma
     processing. */

    //@ requires m_in != null;
    private int scanToken() {
        // The following "assert" is obvious from the program text, because
        // the two arrays are non-null and their types do not coincide in any
        // other way.  ESC/Java can figure this out, too, so therefore the
        // following "assert" produces no warning.  This property is also
        // cruicial to figuring out that the updates to "text[...]" in this
        // body do not destroy the invariants declared in TagConstants about
        // "punctuationCodes[...]".  However, oddly enough, without being
        // prompted to first prove this property, ESC/Java isn't able to
        // prove the necessary thing about the updates to "text[...]".
        //@ assert (Object)text != (Object)TagConstants.punctuationCodes;

        try {
            int nextchr = m_nextchr;
            textlen = 0;

            while (Character.isWhitespace((char)nextchr)) {
                m_in.mark();
                nextchr = m_in.read();
            }
            startingLoc = m_in.getLocation();

            // Inline the identifier-handling code because it's the common case
            if (Character.isJavaIdentifierStart((char)nextchr)) {
                int h = 0;
                do {
                    try {
                        text[textlen] = (char)nextchr;
                        textlen++;
                    } catch (ArrayIndexOutOfBoundsException e) { this.append(nextchr);}
                    h = _SpecialParserInterface.HC*h + nextchr;
                    nextchr = m_in.read();
                } while (Character.isJavaIdentifierPart((char)nextchr));
                m_nextchr = nextchr;
                auxVal = null;
                identifierVal = _SpecialParserInterface.intern(text, textlen, h);
                if (onlyjavakeywords) {
                    ttype = _SpecialParserInterface.getTokenType(identifierVal);
                } else if (keywords != null) {
                    Object val = keywords.get(identifierVal);
                    if (val != null) {
                        ttype = ((Integer)val).intValue();
                        // From the Unenforceable invariant on keyword:
                        /*@ assume ttype != TagConstants.BOOLEANLIT &&
                         ttype != TagConstants.INTLIT &&
                         ttype != TagConstants.LONGLIT &&
                         ttype != TagConstants.FLOATLIT &&
                         ttype != TagConstants.DOUBLELIT &&
                         ttype != TagConstants.STRINGLIT &&
                         ttype != TagConstants.CHARLIT &&
                         ttype != TagConstants.LEXICALPRAGMA &&
                         ttype != TagConstants.MODIFIERPRAGMA &&
                         ttype != TagConstants.STMTPRAGMA &&
                         ttype != TagConstants.TYPEDECLELEMPRAGMA &&
                         ttype != TagConstants.TYPEMODIFIERPRAGMA;  */
                    } else if (javakeywords)
                        ttype = _SpecialParserInterface.getTokenType(identifierVal);
                    else ttype = ParserTagConstants.IDENT;
                } else ttype = ParserTagConstants.IDENT;
		endingLoc = m_in.getLocation(); // Chalin: trying to satisfy Token inv.
                return ttype;
            }
            ttype = ParserToken.CLEAR;      // keep Token invariants happy
            identifierVal = null;

            if (Character.isDigit((char)nextchr))
                return scanNumber(nextchr);
            if (nextchr == '\'' || nextchr == '\"')
                return scanCharOrString(nextchr);

            scanJavaExtensions(nextchr);
            if (ttype != ParserTagConstants.NULL) return ttype;

            scanPunctuation(nextchr);
            if (ttype != ParserTagConstants.NULL) return ttype;

            if (nextchr == -1) {
                m_nextchr = nextchr;
                return ttype = ParserTagConstants.EOF;
            }

            String s = PrettyPrint.toCanonicalString(ParserTagConstants.CHARLIT,
                                                     new Integer(nextchr));
            ErrorSet.fatal(m_in.getLocation(), "Unexpected character " + s);

            //@ unreachable;
            return ttype;

        } catch (IOException e) {
            ErrorSet.fatal(m_in.getLocation(), e.toString());
            return ParserTagConstants.NULL; // Dummy
        }
    }

    /** Handle a comment.  m_in points to the character just after the
     "//" or "/*".  The mark is set at the last character read.  */

    //@ requires m_in != null;
    //@ requires !inPragma;
    //@ modifies inPragma, m_nextchr;
    private void scanComment(int commentKind) {
	try {
	    m_in.mark();
	    int firstchr = m_in.read();
	    // System.out.println("scanComment: firstchr = '"+(char)firstchr+"'");

	    /* Decide if this comment contains a pragma. */

	    if (pragmaParser != null) {
		if (pragmaParser.checkTag(firstchr)) {
		    Assert.notFalse(! inPragma);
		    inPragma = true;
		}
	    }

	    // Scan the comment
	    boolean nonEmptyComment = false; // For empty multi-line comment

	    int locStartComment = m_in.getLocation();
	    int nextchr = firstchr;
	    if (commentKind == ParserTagConstants.EOL_COMMENT) {
		nonEmptyComment = true;
		while (nextchr != -1 && nextchr != '\n')
		    nextchr = m_in.read();
	    } else {
		for(;;) {
		    if (nextchr == -1) {
			ErrorSet.fatal(
			   startingLoc,
			   "Unterminated or improperly nested comment or pragma");
		    }
		    int oldchr = nextchr;
		    nextchr = m_in.read();
		    if (oldchr == '*' && nextchr == '/') break;
		    nonEmptyComment = true;
		}
	    }

	    // If the comment contains a pragma, set up the pragma parser
	    if (inPragma) {
		if(nonEmptyComment) {
                    boolean eolComment = commentKind == ParserTagConstants.EOL_COMMENT;
                    int discard = !eolComment ? 2 :
                        nextchr == '\n' ? 1 : 0;
                    CorrelatedReader nu = m_in.createReaderFromMark(discard);
                    pragmaParser.restart(nu, eolComment);
		} else {
		    // Is an empty multi-line comment
		    inPragma = false;
		}
	    }
	    if (!inPragma) {
                m_in.clearMark();
	    }

	    // Clean up and return
	    m_nextchr = m_in.read();
	} catch (IOException e) {
	    m_in.clearMark();
	    ErrorSet.fatal(m_in.getLocation(), "IO error");
	}
    }	//@ nowarn Exception;	// ignore Index... from createReaderFromMark

    // Notes.  The routines below all assume that the input stream to be
    // scanned consist of their input parameter nextchr plus the characters
    // in m_in; that is, the nextchr argument is playing the role that
    // m_nextchr plays between calls to getNextToken.  These routines also
    // assume that textlen = 0 and startingLoc has already been filled in
    // with the location of the character in nextchr.
    // Unless otherwise noted, the routines below fill in all fields except
    // startingLoc, that is, they fill in m_nextchr, text & textlen,
    // plus the Token fields ttype, endingLoc, and auxVal.
    // Errors are handled internally by these routines.  Either the
    // error is fatal, or the error is recoverable and recovery is done
    // by the routines.

    /** Scan a character or string constant. */

    //@ requires m_in != null;
    private int scanCharOrString(int nextchr) {
        try {
            int endquote = nextchr;
            this.append(endquote);
            boolean chr = (endquote == '\'');
            nextchr = m_in.read();
            stringLitLen = 0;
            for(;;) {
                if (nextchr != '\\' && nextchr != '\n' && nextchr != -1) {
                    // Normal case
                    this.append(nextchr);
                    if (nextchr == endquote) { nextchr = m_in.read(); break; }
                    this.stringLitAppend(nextchr);
                    nextchr = m_in.read();
                    continue;
                }

                if (nextchr == -1 || nextchr == '\n') {
                    if (chr) ErrorSet.fatal(startingLoc,
                                            "Unterminated character literal");
                    else ErrorSet.fatal(startingLoc, "Unterminated string literal");
                    break;
                }

                // At this point, we know we're at the start of an escape sequence
                this.append(nextchr);
                nextchr = m_in.read();
                if ('0' <= nextchr && nextchr <= '7') { // Octal sequence
                    int firstdigit = nextchr - '0';
                    int result = firstdigit;
                    this.append(nextchr);
                    nextchr = m_in.read();
                    if ('0' <= nextchr && nextchr <= '7') {
                        this.append(nextchr); result = 8*result + (nextchr - '0');
                        nextchr = m_in.read();
                        if (0 <= firstdigit && firstdigit <= 3
                            && '0' <= nextchr && nextchr <= '7') {
                            this.append(nextchr); result = 8*result + (nextchr - '0');
                            nextchr = m_in.read();
                        }
                    }
                    if (255 < result) {
                        ErrorSet.error(m_in.getLocation(),
                                       "Octal escape sequence overflow");
                        this.stringLitAppend('\0');
                    } else this.stringLitAppend(result);
                } else {
                    if (nextchr == 'b') this.stringLitAppend('\b');
                    else if (nextchr == 't')  this.stringLitAppend('\t');
                    else if (nextchr == 'n')  this.stringLitAppend('\n');
                    else if (nextchr == 'f')  this.stringLitAppend('\f');
                    else if (nextchr == 'r')  this.stringLitAppend('\r');
                    else if (nextchr == '\"') this.stringLitAppend('\"');
                    else if (nextchr == '\'') this.stringLitAppend('\'');
                    else if (nextchr == '\\') this.stringLitAppend('\\');
                    else {
                        ErrorSet.error(startingLoc, "Bad escape sequence");
                        continue;
                    }
                    this.append(nextchr);
                    nextchr = m_in.read();
                }
            }

            if (chr) {
                if (1 < stringLitLen)
                    ErrorSet.error(startingLoc,
                                   "Character literal with multiple characters.");
                else if (stringLitLen == 0)
                    if (nextchr == '\'') {
                        this.append(nextchr);
                        nextchr = m_in.read();
                        stringLit[0] = '\'';
                        ErrorSet.error(startingLoc, "Unquoted \' in character literal.");
                    } else {
                        stringLit[0] = '\0';
                        ErrorSet.error(startingLoc, "Empty character literal.");
                    }
                ttype = ParserTagConstants.CHARLIT;
                auxVal = new Integer(stringLit[0]);  // CF
            } else {
                ttype = ParserTagConstants.STRINGLIT;
                auxVal = String.valueOf(stringLit, 0, stringLitLen);
            }
            m_nextchr = nextchr;
            endingLoc = m_in.getLocation();
            return ttype;
        } catch (IOException e) {
            ErrorSet.fatal(m_in.getLocation(), e.toString());
            return ParserTagConstants.NULL; // Dummy
        }
    }

    /** Scans a numeric literal.  Requires nextchr is a
     decimal digit.  Reads a numeric literal into text.
     Depending on the kind of literal found, will return one of
     TagConstants.INTLIT,
     TagConstants.LONGLIT,
     TagConstants.FLOATLIT or
     TagConstants.DOUBLELIT.  If an error is detected, a
     message is sent to ErrorSet, m_in is
     advanced to what appears to be the end of the erroneous token, and
     a legal literal is left in text. */

    //@ requires m_in != null;
    //@ modifies endingLoc, ttype, auxVal, m_nextchr, text, textlen;
    //@ ensures \result==ttype;
    /*@ ensures \result==TagConstants.INTLIT || \result==TagConstants.LONGLIT ||
     \result==TagConstants.FLOATLIT || \result==TagConstants.DOUBLELIT ||
     \result==TagConstants.MAX_INT_PLUS_ONE ||
     \result==TagConstants.MAX_LONG_PLUS_ONE ; */
    private int scanNumber(int nextchr) {
        try {
            // Get the first chunk of digits
            int tentativeResult = 0;
            while (Character.isDigit((char)nextchr)) {
                this.append(nextchr);
                tentativeResult = 10*tentativeResult + (nextchr - '0');
                nextchr = m_in.read();
            }
            //@ assume textlen>0; // because know nextchar was initially a digit...

            // Handle floating point literals in another subtroutine
            if (nextchr == '.') {
		m_in.mark();
		int nextnextchr = m_in.read();
		if (nextnextchr == '.') {
		    // Two . in a row - cannot be a double so
		    // back up
		    m_in.reset();
		    // fall through and let the text so far be handled as
		    // a integer literal
		} else {
		    this.append(nextchr);
		    return finishFloatingPointLiteral(nextnextchr);
		}
            } else if (nextchr == 'e' || nextchr == 'E'
                       || nextchr == 'F' || nextchr == 'f'
                       || nextchr == 'd' || nextchr == 'D')
                return finishFloatingPointLiteral(nextchr);

            long result = 0;
            if (text[0] != '0' || (textlen == 1 && nextchr != 'x' && nextchr != 'X'))
                // Handle base-ten literal
                if (textlen <= 9) result = tentativeResult;
                else {
                    // Parse as negative value to avoid problems w/ -Long.MIN_VALUE
                    long mullimit = Long.MIN_VALUE / 10;
                    for(int i = 0; i < textlen; i++) {
                        int d = text[i] - '0';
                        long r2 = 10*result;
                        if (result < mullimit || r2 < Long.MIN_VALUE + d) {
                            ErrorSet.error(startingLoc, "Integer literal overflow");
                            result = 0;
                            break;
                        } else result = r2 - d;
                    }
                    if (nextchr == 'L' || nextchr == 'l') {
                        if (result == Long.MIN_VALUE) {
                            this.append(nextchr);
                            m_nextchr = m_in.read();
                            endingLoc = m_in.getLocation();
                            auxVal = null;
                            return ttype = ParserTagConstants.MAX_LONG_PLUS_ONE;
                        }
                    } else if (result == Integer.MIN_VALUE) {
                        m_nextchr = nextchr;
                        endingLoc = m_in.getLocation();
                        auxVal = null;
                        return ttype = ParserTagConstants.MAX_INT_PLUS_ONE;
                    }
                    result = -result;
                }

            else if (nextchr != 'x' && nextchr != 'X') {
                // Handle octal literal
                for(int i = 1; i < textlen; i++) {
                    int d = text[i] - '0';
                    if (0 <= d && d <= 7) {
                        if ((result >>> 61) != 0) {
                            ErrorSet.error(startingLoc, "Integer literal overflow");
                            result = 0;
                            break;
                        }
                        result = (result << 3) + d;
                    } else {
                        ErrorSet.error(startingLoc,
                                       "Non-octal digit found in octal literal.");
                        result = 0;
                        break;
                    }
                }

            } else {
                // Handle hex literal
                this.append(nextchr);
                boolean overflow = false;
                for(nextchr = m_in.read(); ; nextchr = m_in.read()) {
                    int d = Character.digit((char)nextchr, 16);
                    if (d == -1) break;
                    this.append(nextchr);
                    if (! overflow)
                        if ((result >>> 60) != 0) overflow = true;
                        else result = (result << 4) + d;
                }
                if (textlen <= 2)
                    ErrorSet.error(startingLoc, "Too few digits in a hex literal.");
                else if (overflow) {
                    ErrorSet.error(startingLoc, "Integer literal overflow");
                    result = 0;
                }
            }

            if (nextchr == 'L' || nextchr == 'l') {
                this.append(nextchr);
                m_nextchr = m_in.read();
                endingLoc = m_in.getLocation();
                auxVal = new Long(result);
                return ttype = ParserTagConstants.LONGLIT;
            }
            if ((result & 0xffffffff00000000L) != 0) {
                ErrorSet.error(startingLoc, "Integer literal overflow");
                result = 0;
            }
            m_nextchr = nextchr;
            endingLoc = m_in.getLocation();
            auxVal = new Integer((int)result);
            return ttype = ParserTagConstants.INTLIT;
        } catch (IOException e) {
            ErrorSet.fatal(m_in.getLocation(), e.toString());
            return ParserTagConstants.NULL; // Dummy
        }
    }

    /** Finishes scanning a floating-point literal.

 Requires: text contains a possibly empty sequence
     of decimal digits followed by an optional '.'; also,
     text cannot be empty.  Further, let s be the
     sequence of characters consisting of the characters in
     text followed by nextchr followed by the
     characters in m_in.  This routine requires that a
     prefix of s match the syntax of floating-point literals as
     defined by the Java language specification.

 Ensures: Scans the floating-point literal in s.
     Depending on the type of the literal, returns
     TagConstants.FLOATLIT or
     TagConstants.DOUBLELIT and sets sets
     auxVal to either a Float or
     Double.  If an error is encountered, a message is
     sent to ErorrSet and recovery is performed. */

    //@ requires m_in != null;
    //@ requires textlen>0;
    //@ modifies ttype, auxVal, m_nextchr, endingLoc, text, textlen;
    //@ ensures \result==ttype;
    //@ ensures \result==TagConstants.FLOATLIT || \result==TagConstants.DOUBLELIT;
    private int finishFloatingPointLiteral(int nextchr) {
        try {
            boolean error = false;
            boolean zeroMantissa = true; // Used for underflow detection

            // First, see if there are any non-zero digits in the non-fractional
            // part of the mantissa
            for(int i = 0, len = textlen - (text[textlen-1] == '.' ? 1 : 0);
                i < len; i++)
                if (text[i] != '0') { zeroMantissa = false; break; }

            // If there's a fractional part, scan it in
            while (Character.isDigit((char)nextchr)) {
                if (nextchr != '0') zeroMantissa = false;
                this.append(nextchr);
                nextchr = m_in.read();		// throws IOException
            }

            // If there's an exponent, scan it in
            if (nextchr == 'e' || nextchr == 'E') {
                this.append(nextchr);
                nextchr = m_in.read();
                if (nextchr == '+' || nextchr == '-') {
                    this.append(nextchr);
                    nextchr = m_in.read();
                }
                while (Character.isDigit((char)nextchr)) {
                    this.append(nextchr);
                    nextchr = m_in.read();
                }
                if (! Character.isDigit(text[textlen-1])) {
                    ErrorSet.error(startingLoc, ("Digits required in exponent part"
                                                 + " of floating-point literal."));
                    error = true;
                }
            }

            String s = (error ? "1.0" : String.valueOf(this.text, 0, textlen));

            // Assert: s has one of the following forms:
            //   [0-9]+ (. [0-9]*)? (e [+-] [0-9]+)?
            //   . [0-9]+ (e [+-] [0-9]+)?
            // Also, zeroMantissa is true iff all digits in the mantissa are zero
            // (Todo: examine code more closely to see if this is really true.)

            boolean f = (nextchr == 'F' || nextchr == 'f');
            if (f || nextchr == 'D' || nextchr == 'd') {
                this.append(nextchr);
                m_nextchr = m_in.read();
            } else m_nextchr = nextchr;
            endingLoc = m_in.getLocation();

            if (f) {
                Float result = Float.valueOf(s);  // !throw NumberFormatException
                auxVal = result;
                if (result.isInfinite())
                    ErrorSet.error(startingLoc, "Floating-point literal overflow");
                else if (! zeroMantissa && result.floatValue() == 0.0)
                    ErrorSet.error(startingLoc, "Floating-point literal underflow");
            } else {
                Double result = Double.valueOf(s);  // !throw NumberFormatException
                auxVal = result;
                if (result.isInfinite())
                    ErrorSet.error(startingLoc, "Floating-point literal overflow");
                else if (! zeroMantissa && result.doubleValue() == 0.0D)
                    ErrorSet.error(startingLoc, "Floating-point literal underflow");
            }
            return ttype = (f ? ParserTagConstants.FLOATLIT : ParserTagConstants.DOUBLELIT);
        } catch (IOException e) {
            ErrorSet.fatal(m_in.getLocation(), e.toString());
            return ParserTagConstants.NULL; // Dummy
        }
    }   //@ nowarn Exception;	// NumberFormatException won't be thrown

    /** Scans a punctuation string or a floating-point
     number.  If input doesn't match either a floating-point number or
     any punctuation, returns TagConstants.NULL.  Assumes
     startingLoc already filled in.

The routine may change the mark arbitrarily.

 This method leaves m_in in a different state than
     the previous ones do.  Ordinarily, scanXXX routines
     return with m_nextchr holding the character just
     after the token scanned and m_in pointing to the
     character after that.  scanPunctuation does too, but
     only when the value returned is not
     TagConstants.C_COMMENT or
     TagConstants.EOL_COMMENT; in those two cases, it
     returns with m_in pointing to the character just
     after the token scanned and m_nextchr undefined.
     This aids in pragma processing.  Also, if TagConstants.NULL
     is returned, then m_nextchr is undefined and
     m_in is where it was on entry.
     */

    //@ requires m_in != null;
    //@ modifies ttype, auxVal, m_nextchr, textlen, endingLoc, text;
    //@ modifies m_in.marked;
    //@ ensures \result==ttype;
    private int scanPunctuation(int nextchr) {
        try {
            boolean possibleFloatingPointNumber = (nextchr == '.');
            text[0] = (char)nextchr;
            textlen = 1;
            PunctuationPrefixTree prefix = punctuationTable;
            PunctuationPrefixTree lastPunctuation = prefix;
            int lastPunctuationLength = 0;
            m_in.mark();

            // The following loop, which has been unrolled once so the
            // first iteration can be handled specially, has the invariant:
            //   prefix == null || depth(prefix) == textlen-1
            //   nextchr == text[textlen-1]
            //   (nextchr_0 + m_in_0) == (text[0,textlen) + m_in)
            //   lastPunctuation != null && lastPunctuation is last valid punct seen
            //   lastPunctuationLength == depth(lastPunctuation)
            //   (nextchr_0+m_in_0)==(text[0,lastPunctuationLength]+m_in.resetedtext)
            // Stating part of this invariant graphically:
            //               l      t       l = lastPunctuationLength; t = textlen
            //    text:   abcdefghij
            // nextchr_0+
            //    m_in_0: abcdefghijklmnop
            //               r     nm       r = resetted text, n = nextchr, m = m_in

            int index = nextchr - '!';
            if (index < 0 || PunctuationPrefixTree.CHILDLEN <= index)
                prefix = null;
            else
                prefix = prefix.children[nextchr - '!'];
            if (prefix != null && prefix.code != ParserTagConstants.NULL) {
                lastPunctuation = prefix;
                lastPunctuationLength = textlen;
                m_in.mark();
            }
            nextchr = m_in.read();
            if (possibleFloatingPointNumber && Character.isDigit((char)nextchr)) {
                // Deal with special case of floating-point numbers
                m_in.clearMark();
                return finishFloatingPointLiteral(nextchr);
            }
            this.append(nextchr);
            while (prefix != null) {
                index = nextchr - '!';
                if (index < 0 || PunctuationPrefixTree.CHILDLEN <= index)
                    prefix = null;
                else
                    prefix = prefix.children[nextchr - '!'];
                if (prefix != null && prefix.code != ParserTagConstants.NULL) {
                    lastPunctuation = prefix;
                    lastPunctuationLength = textlen;
                    m_in.mark();
                }
                nextchr = m_in.read();
                this.append(nextchr);
            }
            // End of unrolled loop

            m_in.reset();
            textlen = lastPunctuationLength;
            endingLoc = m_in.getLocation();
            ttype = lastPunctuation.code;
            if (ttype != ParserTagConstants.C_COMMENT &&
                ttype != ParserTagConstants.EOL_COMMENT &&
                ttype != ParserTagConstants.NULL) {
                m_nextchr = m_in.read();
            }
            return ttype;
        } catch (IOException e) {
            ErrorSet.fatal(m_in.getLocation(), e.toString());
            return ParserTagConstants.NULL; // Dummy
        }
    }

    /** Scans a Java extension.  If input doesn't match any Java extension,
     returns TagConstants.NULL.  Assumes startingLoc
     already filled in, and assumes textlen is 0.

The routine may change the mark arbitrarily.

 If a Java extension is matched, returns with m_nextchr
     holding the character just after the token scanned and m_in
     pointing to the character after that.
     */
    //@ requires m_in != null;
    //@ requires textlen == 0;
    //@ modifies ttype, auxVal, m_nextchr;
    //@ modifies m_in.marked;
    //@ ensures \result==ttype;
    protected int scanJavaExtensions(int nextchr) {
        ttype = ParserTagConstants.NULL;
        return ttype;
    }

    //// Internal char buffer used by string scanner.

    // Having this separate from text allows us to accumulate both the
    // original input in text and the escape-converted input in stringLit

    //@ private invariant stringLit != null;
    //@ private invariant stringLit.length>=64;
    private char[] stringLit = new char[64];

    //@ private invariant stringLitLen>=0;
    private int stringLitLen = 0;

    private void stringLitAppend(int c) {
        try {
            stringLit[stringLitLen] = (char)c;    //@ nowarn IndexTooBig; // caught
        } catch (ArrayIndexOutOfBoundsException e) {
            char[] newstringLit = new char[stringLitLen + 128];
            System.arraycopy(stringLit, 0, newstringLit, 0, stringLitLen);
            stringLit = newstringLit;
            stringLit[stringLitLen] = (char)c;
        }
        stringLitLen++;
    }

    //// The keyword and punctuation tables, plus methods for changing them

    //@ private invariant punctuationTable != null;
    private PunctuationPrefixTree punctuationTable = new PunctuationPrefixTree();

    /**
     * Unenforceable invariant: all tokenTypes in this table do not
     * require a non-null auxVal.  (cf. Token.auxVal).
     */
    //  Old specs from original full JML spec files.  Must be
    //  rewritten for current java.util.Hashtable specs.
    /*  invariant (keywords != null) ==> (keywords.keyType == \type(Identifier) &&
                  keywords.elementType == \type(Integer)); */
    protected Hashtable keywords = null;

    protected boolean javakeywords = false, onlyjavakeywords = false;
    //@ invariant onlyjavakeywords == (javakeywords && keywords == null);

    static {
        // When class initializes, change the tokenType field
        // of Identifier instances associated with keywords.
        for(int code = ParserTagConstants.FIRST_KEYWORD;
            code <= ParserTagConstants.LAST_KEYWORD;
            code++) {
            Identifier idn = Identifier.intern(ParserTagConstants.toString(code));
            _SpecialParserInterface.setTokenType(idn, code);
        }
    }

    /** Add all of Java's keywords to the scanner.  The token codes used
     for these keywords are those defined by the TagConstants
     class.  Requires that none of these keywords have been added
     already. */

    public void addJavaKeywords() {
        javakeywords = true;
        if (keywords != null)
            // New values override existing ones...
            for(int i = ParserTagConstants.FIRST_KEYWORD;
                i <= ParserTagConstants.LAST_KEYWORD;
                i++)
                keywords.remove(Identifier.intern(ParserTagConstants.toString(i)));
        else onlyjavakeywords = true;
    }

    /**
     * Add a keyword to a Lex object with the given code.
     * Requires that newkeyword is a Java identifier and
     * that code is not TagConstants.NULL or
     * a tokenType that requires auxVal to be non-null;
     * (cf. Token.auxVal).
     *
     * Also requires that the keyword hasn't already been added.
     */
    //@ requires code != TagConstants.NULL;
    //@ requires code != TagConstants.BOOLEANLIT;
    //@ requires code != TagConstants.INTLIT;
    //@ requires code != TagConstants.LONGLIT;
    //@ requires code != TagConstants.DOUBLELIT;
    //@ requires code != TagConstants.STRINGLIT;
    //@ requires code != TagConstants.CHARLIT;
    //@ requires code != TagConstants.LEXICALPRAGMA;
    //@ requires code != TagConstants.MODIFIERPRAGMA;
    //@ requires code != TagConstants.STMTPRAGMA;
    //@ requires code != TagConstants.TYPEDECLELEMPRAGMA;
    //@ requires code != TagConstants.TYPEMODIFIERPRAGMA;
    public void addKeyword(/*@ non_null @*/ String newkeyword, int code) {
	Assert.precondition(code != ParserTagConstants.NULL);
	if (keywords == null) {
	    keywords = new Hashtable();
            //  Old specs from original full JML spec files.  Must be
            //  rewritten for current java.util.Hashtable specs.
	    //  set keywords.keyType = \type(Identifier);
	    //  set keywords.elementType = \type(Integer);
	}
	keywords.put(Identifier.intern(newkeyword), new Integer(code));
	onlyjavakeywords = false;
    }

    /** Add all of Java's punctuation strings to the scanner.  The codes
     used for these punctuation strings are the found in the
     TagConstants class.  Requires that none of these
     punctuation strings have been added before. */

    public void addJavaPunctuation() {
        Assert.notFalse(ParserTagConstants.punctuationStrings.length ==
                        ParserTagConstants.punctuationCodes.length);
        for(int i = 0; i < ParserTagConstants.punctuationStrings.length; i++)
            addPunctuation(ParserTagConstants.punctuationStrings[i],
                           ParserTagConstants.punctuationCodes[i]);
    }

    /** Add a punctuation string to a scanner associated with a given
     code.  Requires that the characters in the punctuation string are
     all punctuation characters, that is, non-alphanumeric ASCII
     characters whose codes are between 33 ('!')  and 126 ('~')
     inclusive.  Also requires that the code is not
     TagConstants.NULL and that the punctuation string
     hasn't already been added. */
    //@ requires punctuation != null;
    //@ requires code != TagConstants.NULL;
    //@ requires code != TagConstants.IDENT;
    //@ requires code != TagConstants.BOOLEANLIT;
    //@ requires code != TagConstants.INTLIT;
    //@ requires code != TagConstants.LONGLIT;
    //@ requires code != TagConstants.FLOATLIT;
    //@ requires code != TagConstants.DOUBLELIT;
    //@ requires code != TagConstants.STRINGLIT;
    //@ requires code != TagConstants.CHARLIT;
    //@ requires code != TagConstants.LEXICALPRAGMA;
    //@ requires code != TagConstants.MODIFIERPRAGMA;
    //@ requires code != TagConstants.STMTPRAGMA;
    //@ requires code != TagConstants.TYPEDECLELEMPRAGMA;
    //@ requires code != TagConstants.TYPEMODIFIERPRAGMA;
    public void addPunctuation(String punctuation, int code) {
        Assert.precondition(code != ParserTagConstants.NULL);
        PunctuationPrefixTree prefix = punctuationTable;
        for(int j = 0; j < punctuation.length(); j++) {
            int c = punctuation.charAt(j);
            Assert.precondition(	//@ nowarn Pre;
                                ('!' <= c && c <= '/') || (':' <= c && c <= '@')
                                || ('[' <= c && c <= '`') || ('{' <= c && c <= '~'));
            int index = c - '!';
            PunctuationPrefixTree child = prefix.children[index];
            if (child == null)
                child = prefix.children[index] = new PunctuationPrefixTree();
            prefix = child;
        }
        prefix.code = code;
    }

    //// Diagnostic routines

    /** Checks invariants (assumes that Token fields
     haven't been mucked with by outside code).  prefix is
     used to prefix error messages with context provided by the
     caller. */

    public void zzz(String prefix) {
        super.zzz();
        lookaheadq.zzz("Near character "
                       + Location.toOffset(startingLoc)
                       + ": " + prefix);
    }
}

class PunctuationPrefixTree {
    public static final int CHILDLEN = 1 + '~' - '!';

    /*@ invariant code != TagConstants.IDENT &&
     code != TagConstants.BOOLEANLIT &&
     code != TagConstants.INTLIT &&
     code != TagConstants.LONGLIT &&
     code != TagConstants.FLOATLIT &&
     code != TagConstants.DOUBLELIT &&
     code != TagConstants.STRINGLIT &&
     code != TagConstants.CHARLIT &&
     code != TagConstants.LEXICALPRAGMA &&
     code != TagConstants.MODIFIERPRAGMA &&
     code != TagConstants.STMTPRAGMA &&
     code != TagConstants.TYPEDECLELEMPRAGMA &&
     code != TagConstants.TYPEMODIFIERPRAGMA; */
    public int code = ParserTagConstants.NULL; // ! NULL ==> a punctuation string

    //@ invariant children != null;
    //@ invariant children.length == CHILDLEN;
    //@ invariant \typeof(children) == \type(PunctuationPrefixTree[]);
    public PunctuationPrefixTree[] children
            = new PunctuationPrefixTree[CHILDLEN];
}


text:
#ifndef COINCOMMITMENT_H_
#define COINCOMMITMENT_H_

#include <vector>

namespace libzerocash {

/****************************** Coin commitment ******************************/

class CoinCommitment {

friend class PourTransaction;
friend class PourProver;

public:
	CoinCommitment();

	CoinCommitment(const std::vector<unsigned char>& val,
                   const std::vector<unsigned char>& k);

    const std::vector<unsigned char>& getCommitmentValue() const;

	bool operator==(const CoinCommitment& rhs) const;
	bool operator!=(const CoinCommitment& rhs) const;

private:
    std::vector<unsigned char> commitmentValue;
};

} /* namespace libzerocash */

#endif /* COINCOMMITMENT_H_ */


text:
import os.path

from django.conf import settings

WEBCAM_URL = getattr(settings, 'WEBCAM_URL', 'webcams')
WEBCAM_ROOT = getattr(settings, 'WEBCAM_ROOT',
                      os.path.join(settings.BASE_DIR, 'cams'))

WEBCAM_STATIC_URL = getattr(settings, 'WEBCAM_STATIC_URL', 'cams')

WEBCAM_SIZE = getattr(settings, 'WEBCAM_SIZE', (80, 60))
DEFAULT_FEATURES_SIZE = getattr(settings, 'DEFAULT_FEATURES_SIZE', (40, 30))

# %t means timestamp as an integer
PICTURE_PATH = getattr(settings, 'PICTURE_PATH', '%Y/%m/%d/%t.jpg')


text:
'use strict';

/*!
 * Module dependencies.
 */

var path = require('path')
  , debug = require('debug')('parent-dir')
  , nm = '/node_modules'

/**
 * Find the parent app directory by looking up the directory
 * tree until there is is no `package.json` file found or there is
 * no `node_modules` directory found.
 *
 * This task is syncronous as it should only ever be ran once at
 * app startup, then cached by `require`
 *
 * @returns {String} directory
 */

module.exports = (function() {
  debug('walking module parent tree')

  var dir = module
    , p

  // This is the simplest way, if included as a node module, the parent directory
  // is generally the first dir to have a `node_modules` dir
  if (!!~dir.id.indexOf(nm)) {
    p = dir.id.split(nm)[0]

    debug('simple path: `%s`', p)
  }

  // We dont want to go all the way up the chain, in the case we are running
  // in a test context such as `mocha`, move up the chain if the current dir
  // is within `node_modules`, or if not, that the parent directory isnt moving
  // *into* the `node_modules` dir.
  while (dir.parent
    && (
      !!~dir.id.indexOf(nm)
      || !~dir.parent.id.indexOf(nm)
    ) && (
      // Dont move down further into dirs
      !~path.dirname(dir.parent.id).indexOf(path.dirname(dir.id))
    )
  ) {

    debug('walking `%s`', dir.id)
    dir = dir.parent
  }

  // If the module path contains the simple path found above, dont use it
  var p2 = path.dirname(dir.id)
  if (!~p2.indexOf(p)) p = p2
  p = path.resolve(p)

  debug('found `%s`', p)
  return p
})()


text:
package io.gatling.http.util

import java.{ util => ju }
import java.net._
import java.util.concurrent.ThreadLocalRandom

import scala.jdk.CollectionConverters._
import scala.util.control.NonFatal

import com.typesafe.scalalogging.LazyLogging
import io.netty.util.NetUtil

private[http] object InetAddresses extends LazyLogging {
  private def isBindable(localAddress: InetAddress): Boolean = {
    val socket = new Socket
    val socketAddress = new InetSocketAddress(localAddress, 0)
    try {
      socket.bind(socketAddress)
      true
    } catch {
      case NonFatal(e) =>
        logger.debug(s"Address $localAddress is not bindable", e)
        false
    } finally {
      socket.close()
    }
  }

  private val AllLocalAddresses =
    for {
      networkInterface <- NetworkInterface.getNetworkInterfaces.asScala.toList
      inetAddress <- networkInterface.getInetAddresses.asScala
      if !inetAddress.isLoopbackAddress &&
        !inetAddress.isLinkLocalAddress &&
        !inetAddress.isMulticastAddress &&
        isBindable(inetAddress)
    } yield inetAddress

  val AllIpV4LocalAddresses: List[InetAddress] = AllLocalAddresses.filter(_.isInstanceOf[Inet4Address])
  val AllIpV6LocalAddresses: List[InetAddress] = if (NetUtil.isIpV4StackPreferred) Nil else AllLocalAddresses.filter(_.isInstanceOf[Inet6Address])

  @SuppressWarnings(Array("org.wartremover.warts.IsInstanceOf", "org.wartremover.warts.AnyVal"))
  def shuffleInetAddresses(originalAddresses: ju.List[InetAddress], isIpV4StackPreferred: Boolean, isIpV6AddressesPreferred: Boolean): ju.List[InetAddress] =
    if (originalAddresses.size() == 1) {
      originalAddresses
    } else {
      var ipV4: ju.List[InetAddress] = null
      var ipV6: ju.List[InetAddress] = null

      originalAddresses.asScala.foreach { inetAddress =>
        if (inetAddress.isInstanceOf[Inet4Address]) {
          if (ipV4 == null) {
            ipV4 = new ju.ArrayList[InetAddress](originalAddresses.size())
          }
          ipV4.add(inetAddress)
        } else if (!isIpV4StackPreferred) {
          if (ipV6 == null) {
            ipV6 = new ju.ArrayList[InetAddress](originalAddresses.size())
          }
          ipV6.add(inetAddress)
        }
      }

      val higher = if (isIpV6AddressesPreferred) ipV6 else ipV4
      val lower = if (isIpV6AddressesPreferred) ipV4 else ipV6

      val random = ThreadLocalRandom.current()
      if (higher != null) {
        shuffle(higher, random)
        if (lower != null) {
          shuffle(lower, random)
          higher.addAll(lower)
        }
        higher
      } else {
        shuffle(lower, random)
        lower
      }
    }

  private def shuffle(list: ju.List[InetAddress], random: ThreadLocalRandom): Unit =
    if (list.size() > 1) {
      ju.Collections.shuffle(list, random)
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">

	<meta http-equiv="content-type" content="application/xhtml+xml" />
	<title>MIT Campus Map: Browse by Building Number</title>
	<link rel="stylesheet" type="text/css" href="../../styles/sp.css" />
	<meta name="MobileOptimized" content="176">

Campus Map

West Campus: W1-W16

		W1

		W2

		W4

		W5

		W7

		W8

		W11

		W13

		W15

		W16

		< Back

		0: MIT Mobile Web Home

		1: Campus Map Home

	Campus map provided by Department of Facilities and Information Services & Technology


text:
ACCEPTED

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

#### Published in
Mycotaxon 33: 402 (1988)

#### Original name
Parmelia conspersa var. coloradoensis Gyeln.

### Remarks
null


text:
<!DOCTYPE html>

   <meta charset="utf-8" />
   <meta name="Author" content="Takashi Masuyama" />
   <meta name="viewport" content="width=device-width" />

   <title>Truncated icosahedron</title>

    <canvas id="screen"></canvas>

pentagon x 12, hexagon x 20


text:
package de.hpi.bpmn2_0.model.data_object;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import de.hpi.bpmn2_0.model.BaseElement;

/**
 *
Java class for tInputOutputSpecification complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="tInputOutputSpecification">
 *   <complexContent>
 *     <extension base="{http://www.omg.org/bpmn20}tBaseElement">
 *       <sequence>
 *         <element ref="{http://www.omg.org/bpmn20}dataInput" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/bpmn20}dataOutput" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/bpmn20}inputSet" maxOccurs="unbounded" minOccurs="0"/>
 *         <element ref="{http://www.omg.org/bpmn20}outputSet" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tInputOutputSpecification", propOrder = {
    "dataInput",
    "dataOutput",
    "inputSet",
    "outputSet"
})
public class InputOutputSpecification
    extends BaseElement
{

    protected List<DataInput> dataInput;
    protected List<DataOutput> dataOutput;
    protected List<InputSet> inputSet;
    protected List<OutputSet> outputSet;

    /**
     * Gets the value of the dataInput property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the dataInput property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDataInput().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DataInput }
     *
     *
     */
    public List<DataInput> getDataInput() {
        if (dataInput == null) {
            dataInput = new ArrayList<DataInput>();
        }
        return this.dataInput;
    }

    /**
     * Gets the value of the dataOutput property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the dataOutput property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getDataOutput().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link DataOutput }
     *
     *
     */
    public List<DataOutput> getDataOutput() {
        if (dataOutput == null) {
            dataOutput = new ArrayList<DataOutput>();
        }
        return this.dataOutput;
    }

    /**
     * Gets the value of the inputSet property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the inputSet property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getInputSet().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link TInputSet }
     *
     *
     */
    public List<InputSet> getInputSet() {
        if (inputSet == null) {
            inputSet = new ArrayList<InputSet>();
        }
        return this.inputSet;
    }

    /**
     * Gets the value of the outputSet property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the outputSet property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getOutputSet().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link TOutputSet }
     *
     *
     */
    public List<OutputSet> getOutputSet() {
        if (outputSet == null) {
            outputSet = new ArrayList<OutputSet>();
        }
        return this.outputSet;
    }

}


text:
package org.apache.ambari.server.api.stomp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.ambari.server.events.listeners.tasks.TaskStatusListener;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class NamedTasksSubscriptions {
  private static Logger LOG = LoggerFactory.getLogger(NamedTasksSubscriptions.class);

  private ConcurrentHashMap<String, List<SubscriptionId>> taskIds = new ConcurrentHashMap<>();
  private final String subscriptionPrefix = "/events/tasks/";
  private final Lock taskIdsLock = new ReentrantLock();

  private Provider<TaskStatusListener> taskStatusListenerProvider;

  @Inject
  public NamedTasksSubscriptions(Provider<TaskStatusListener> taskStatusListenerProvider) {
    this.taskStatusListenerProvider = taskStatusListenerProvider;
  }

  public void addTaskId(String sessionId, Long taskId, String id) {
    try {
      taskIdsLock.lock();
      taskIds.compute(sessionId, (sid, ids) -> {
        if (ids == null) {
          ids = new ArrayList<>();
        }
        AtomicBoolean completed = new AtomicBoolean(false);
        taskStatusListenerProvider.get().getActiveTasksMap().computeIfPresent(taskId, (tid, task) -> {
          if (task.getStatus().isCompletedState()) {
            completed.set(true);
          }
          return task;
        });
        if (!completed.get()) {
          ids.add(new SubscriptionId(taskId, id));
        }
        return ids;
      });
      LOG.info(String.format("Task subscription was added for sessionId = %s, taskId = %s, id = %s",
          sessionId, taskId, id));
    } finally {
      taskIdsLock.unlock();
    }
  }

  public void removeId(String sessionId, String id) {
    taskIds.computeIfPresent(sessionId, (sid, tasks) -> {
      Iterator<SubscriptionId> iterator = tasks.iterator();
      while (iterator.hasNext()) {
        if (iterator.next().getId().equals(id)) {
          iterator.remove();
          LOG.info(String.format("Task subscription was removed for sessionId = %s, id = %s", sessionId, id));
        }
      }
      return tasks;
    });
  }

  public void removeTaskId(Long taskId) {
    try {
      taskIdsLock.lock();
      for (String sessionId : taskIds.keySet()) {
        taskIds.computeIfPresent(sessionId, (id, tasks) -> {
          Iterator<SubscriptionId> iterator = tasks.iterator();
          while (iterator.hasNext()) {
            if (iterator.next().getTaskId().equals(taskId)) {
              iterator.remove();
              LOG.info(String.format("Task subscription was removed for sessionId = %s and taskId = %s",
                  sessionId, taskId));
            }
          }
          return tasks;
        });
      }
    } finally {
      taskIdsLock.unlock();
    }
  }

  public void removeSession(String sessionId) {
    try {
      taskIdsLock.lock();
      taskIds.remove(sessionId);
      LOG.info(String.format("Task subscriptions were removed for sessionId = %s", sessionId));
    } finally {
      taskIdsLock.unlock();
    }
  }

  public Optional<Long> matchDestination(String destination) {
    Optional<Long> taskIdOpt = Optional.of(StringUtils.substringAfter(destination, subscriptionPrefix))
        .filter(StringUtils::isNotEmpty)
        .filter(StringUtils::isNumeric)
        .map(Long::parseLong);
    return taskIdOpt;
  }

  public void addDestination(String sessionId, String destination, String id) {
    Optional<Long> taskIdOpt = matchDestination(destination);
    if (taskIdOpt.isPresent()) {
      addTaskId(sessionId, taskIdOpt.get(), id);
    }
  }

  public boolean checkTaskId(Long taskId) {
    for (List<SubscriptionId> ids: taskIds.values()) {
      for (SubscriptionId subscriptionId : ids) {
        if (subscriptionId.getTaskId().equals(taskId)) {
          return true;
        }
      }
    }
    return false;
  }

  public class SubscriptionId {
    private final Long taskId;
    private final String id;

    public SubscriptionId(Long taskId, String id) {
      this.taskId = taskId;
      this.id = id;
    }

    public Long getTaskId() {
      return taskId;
    }

    public String getId() {
      return id;
    }
  }
}


text:
<?php

namespace Magento\Catalog\Test\Block\Adminhtml\Product\Attribute\Edit\Tab;

use Magento\Backend\Test\Block\Widget\Tab;
use Mtf\Client\Element;

/**
 * Class AdvancedPropertiesTab
 * Tab "Advanced Attribute Properties"
 */
class Advanced extends Tab
{
    /**
     * "Advanced Attribute Properties" tab-button
     *
     * @var string
     */
    protected $propertiesTab = '[data-target="#advanced_fieldset-content"][data-toggle="collapse"]';

    /**
     * "Advanced Attribute Properties" tab-button active
     *
     * @var string
     */
    protected $propertiesTabActive = '.title.active';

    /**
     * Fill 'Advanced Attribute Properties' tab
     *
     * @param array $fields
     * @param Element|null $element
     * @return $this
     */
    public function fillFormTab(array $fields, Element $element = null)
    {
        if (!$this->_rootElement->find($this->propertiesTabActive)->isVisible()) {
            $this->_rootElement->find($this->propertiesTab)->click();
        }

        return parent::fillFormTab($fields);
    }
}


text:
package org.apache.maven.plugin.cxx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Goal which Launch an external executable.
 *
 * @author Franck Bonin
 */
@Mojo( name = "launch" )
public class LaunchMojo extends AbstractLaunchMojo
{

    /**
     * Can be of type <argument> or <classpath> Can be overriden using "cxx.args"
     * env. variable
     *
     * @since 0.0.4
     */
    @Parameter()
    private List<String> arguments;

    @Override
    protected List<String> getArgsList()
    {
        return arguments;
    }

    /**
     * Arguments for the executed program
     *
     */
    @Parameter( property = "launch.args" )
    private String commandArgs;

    @Override
    protected String getCommandArgs()
    {
        return commandArgs;
    }

    /**
     * The executable. Can be a full path or a the name executable. In the latter case, the executable must be in the
     * PATH for the execution to work.
     *
     * @since 0.0.4
     */
    @Parameter( property = "launch.executable", required = true )
    private String executable;

    @Override
    protected String getExecutable()
    {
        return executable;
    }

    /**
     * Environment variables to pass to the executed program.
     *
     * @since 0.0.4
     */
    @Parameter()
    private Map environmentVariables = new HashMap();

    @Override
    protected Map getMoreEnvironmentVariables()
    {
        return environmentVariables;
    }

    /**
     * Exit codes to be resolved as successful execution for non-compliant applications (applications not returning 0
     * for success).
     *
     * @since 0.0.4
     */
    @Parameter()
    private List<String> successCodes;

    @Override
    protected List<String> getSuccesCode()
    {
        return successCodes;
    }

    /**
     * The current working directory. Optional. If not specified, basedir will be used.
     *
     * @since 0.0.4
     */
    @Parameter( property = "launch.workingdir" )
    private File workingDir;

    @Override
    protected File getWorkingDir()
    {
        if ( null == workingDir )
        {
            workingDir = new File( basedir.getPath() );
        }
        return workingDir;
    }

    /**
     * Os for which command shall be executed
     * os name match is java.lang.System.getProperty( "os.name" )
     *
     * @since 0.0.4
     */
    @Parameter()
    private List includeOS;

    /**
     * Os for which command shall not be executed
     * os name match is java.lang.System.getProperty( "os.name" )
     *
     * @since 0.0.4
     */
    @Parameter()
    private List excludeOS;

    @Override
    protected boolean isSkip()
    {
        String sOsName = System.getProperty( "os.name" );
        sOsName = sOsName.replace( " ", "" );
        getLog().info( "os.name is \"" + sOsName + "\"" );
        if ( null == excludeOS && null == includeOS )
        {
            return false;
        }
        else if ( null == includeOS )
        {
            return excludeOS.contains( sOsName );
        }
        else if ( null == excludeOS )
        {
            return !includeOS.contains( sOsName );
        }
        else
        {
            return ( excludeOS.contains( sOsName ) || !includeOS.contains( sOsName ) );
        }
    }

    /**
     * The OutputStreamOut Location.
     *
     * @since 0.0.5
     */
    @Parameter( property = "launch.outputStreamOut", defaultValue = "" )
    private File outputStreamOut;

    @Override
    protected OutputStream getOutputStreamOut()
    {
        String sOutputStreamOut = new String();
        if ( null != outputStreamOut && !outputStreamOut.toString().isEmpty() )
        {
            if ( outputStreamOut.isAbsolute() )
            {
                sOutputStreamOut = outputStreamOut.getPath();
            }
            else
            {
                sOutputStreamOut = basedir.getAbsolutePath() + File.separator + outputStreamOut.getPath();
            }

            getLog().info( "Launch output location " + sOutputStreamOut );

            OutputStream output = super.getOutputStreamOut();
            File file = new File( sOutputStreamOut );
            try
            {
                new File( file.getParent() ).mkdirs();
                file.createNewFile();
                output = new FileOutputStream( file );
            }
            catch ( IOException e )
            {
                getLog().error( "Launch report redirected to stout since " + sOutputStreamOut + " can't be opened" );
            }
            return output;
        }
        else
        {
            return super.getOutputStreamOut();
        }
    }

    /**
     * The OutputStreamErr Location.
     *
     * @since 0.0.5
     */
    @Parameter( property = "launch.outputStreamErr", defaultValue = "" )
    private File outputStreamErr;

    @Override
    protected OutputStream getOutputStreamErr()
    {
        String sOutputStreamErr = new String();
        if ( null != outputStreamErr && !outputStreamErr.toString().isEmpty() )
        {
            if ( outputStreamErr.isAbsolute() )
            {
                sOutputStreamErr = outputStreamErr.getPath();
            }
            else
            {
                sOutputStreamErr = basedir.getAbsolutePath() + File.separator + outputStreamErr.getPath();
            }

            getLog().info( "Launch erroutput location " + sOutputStreamErr );

            OutputStream output = super.getOutputStreamErr();
            File file = new File( sOutputStreamErr );
            try
            {
                new File( file.getParent() ).mkdirs();
                file.createNewFile();
                output = new FileOutputStream( file );
            }
            catch ( IOException e )
            {
                getLog().error( "Launch report redirected to stout since " + sOutputStreamErr + " can't be opened" );
            }
            return output;
        }
        else
        {
            return super.getOutputStreamErr();
        }
    }

    /**
     * The InputStream Location.
     *
     * @since 0.0.5
     */
    @Parameter( property = "launch.inputStream", defaultValue = "" )
    private File inputStream;

    @Override
    protected InputStream getInputStream()
    {
        String sInputStream = new String();
        if ( null != inputStream && !inputStream.toString().isEmpty() )
        {
            if ( inputStream.isAbsolute() )
            {
                sInputStream = inputStream.getPath();
            }
            else
            {
                sInputStream = basedir.getAbsolutePath() + File.separator + inputStream.getPath();
            }

            getLog().info( "Launch input location " + sInputStream );

            InputStream input = super.getInputStream();
            File file = new File( sInputStream );
            try
            {
                new File( file.getParent() ).mkdirs();
                file.createNewFile();
                input = new FileInputStream( file );
            }
            catch ( IOException e )
            {
                getLog().error( "Launch report redirected to stout since " + sInputStream + " can't be opened" );
            }
            return input;
        }
        else
        {
            return super.getInputStream();
        }
    }
}


text:
if(!dojo._hasResource["dojox.form._FormSelectWidget"]){
dojo._hasResource["dojox.form._FormSelectWidget"]=true;
dojo.deprecated("dojox.form._FormSelectWidget","Use dijit.form._FormSelectWidget instead","2.0");
dojo.provide("dojox.form._FormSelectWidget");
dojo.require("dijit.form._FormSelectWidget");
dojo.setObject("dojox.form._FormSelectWidget",dijit.form._FormSelectWidget);
}


text:
package com.tnf.ptm.sound;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.TimeUtils;
import com.tnf.ptm.common.GameDrawer;
import com.tnf.ptm.common.PtmObject;
import com.tnf.ptm.common.PtmGame;
import com.tnf.ptm.common.DebugCol;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DebugHint {
    private static final long MAX_AWAIT = 3000;
    private final Vector2 myPos;
    private final Map<String, Long> myMsgs;

    private PtmObject myOwner;
    private String myMsg;

    public DebugHint(PtmObject owner, Vector2 pos) {
        myOwner = owner;
        myPos = new Vector2(pos);
        myMsgs = new HashMap<String, Long>();
    }

    public void add(String value) {
        boolean needsRebuild = !myMsgs.containsKey(value);
        myMsgs.put(value, TimeUtils.millis() + MAX_AWAIT);
        if (needsRebuild) {
            rebuild();
        }
    }

    private void rebuild() {
        StringBuilder sb = new StringBuilder();
        for (String msg : myMsgs.keySet()) {
            sb.append(msg).append("\n");
        }
        myMsg = sb.toString();
    }

    public void update(PtmGame game) {
        if (myOwner != null) {
            if (myOwner.shouldBeRemoved(game)) {
                myOwner = null;
            } else {
                myPos.set(myOwner.getPosition());
            }
        }

        long now = TimeUtils.millis();
        boolean needsRebuild = false;
        Iterator<Map.Entry<String, Long>> it = myMsgs.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Long> e = it.next();
            if (e.getValue() <= now) {
                it.remove();
                needsRebuild = true;
            }
        }
        if (needsRebuild) {
            rebuild();
        }
    }

    public boolean shouldRemove() {
        return myMsgs.isEmpty();
    }

    public void draw(GameDrawer drawer, PtmGame game) {
        float fontSz = game.getCam().getDebugFontSize();
        drawer.drawString(myMsg, myPos.x, myPos.y, fontSz, false, DebugCol.HINT);
    }
}