text:
package com.timehop.droidcon2014retrofitsample.data.reddit;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.timehop.droidcon2014retrofitsample.data.reddit.model.RedditListing;
import com.timehop.droidcon2014retrofitsample.data.reddit.model.RedditObject;
import com.timehop.droidcon2014retrofitsample.data.reddit.model.RedditResponse;

import org.joda.time.DateTime;

import java.util.List;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
import retrofit.http.GET;
import retrofit.http.Path;

public interface RedditService {
  @GET("/r/{subreddit}/comments/{id}.json")
  List<RedditResponse<RedditListing>> getComments(
      @Path("subreddit") String subreddit,
      @Path("id") String id
  );

  @GET("/r/{subreddit}/comments/{id}.json")
  void getComments(
      @Path("subreddit") String subreddit,
      @Path("id") String id,
      Callback<List<RedditResponse<RedditListing>>> callback
  );

  @GET("/r/{subreddit}.json")
  RedditResponse<RedditListing> getSubreddit(@Path("subreddit") String subreddit);

  @GET("/r/{subreddit}.json")
  void getSubreddit(
      @Path("subreddit") String subreddit,
      Callback<RedditResponse<RedditListing>> callback);

  public static class Implementation {
    public static RedditService get() {
      return getBuilder()
          .build()
          .create(RedditService.class);
    }

    static RestAdapter.Builder getBuilder() {
      return new RestAdapter.Builder()
          .setConverter(new GsonConverter(getGson()))
          .setEndpoint("http://www.reddit.com");
    }

    private static Gson getGson() {
      return new GsonBuilder()
          .registerTypeAdapter(RedditObject.class, new RedditObjectDeserializer())
          .registerTypeAdapter(DateTime.class, new DateTimeDeserializer())
          .create();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
@interface CYRecommendTitleView ()

@end

@implementation CYRecommendTitleView

- (IBAction)recommendClick:(id)sender {
    if (self.recommdMoreClick) {
        self.recommdMoreClick(self.recommedTitle.text);
    }
}

@end


text:
SET ROLE 'dbuser';
DROP DATABASE IF EXISTS gallery;
CREATE DATABASE gallery;
\c gallery;
SET ROLE 'dbuser';

CREATE TABLE Artist(
	artist_id integer primary key,
	avator varchar(500),
	name varchar(100),
	address varchar(100),
	self_intro varchar(3000),
	gender varchar(100)
);

CREATE TABLE Painting(
	painting_id integer primary key,
	artist_id integer references Artist(artist_id),
	price float8,
	height float8,
	width float8,
	img varchar(500),
	title varchar(100),
	type varchar(100),
	available boolean default true
);

CREATE TABLE Customer(
	customer_id serial primary key,
	name varchar(100),
	email varchar(100) unique,
	password text
);

CREATE TABLE Buy(
	customer_id serial references Customer(customer_id),
	painting_id integer references Painting(painting_id)
);

CREATE TABLE Orders(
	order_number serial primary key,
	customer_id serial references Customer(customer_id),
	order_time timestamp with time zone
);

CREATE TABLE OrderItem(
	order_number serial references Orders(order_number),
	painting_id integer references Painting(painting_id),
	price float8,
	primary key(order_number, painting_id)
);


text:
Add-on for Firefox browser.
Automatically opens Firefox Developer Tools when new tab / new window is opened.
If user closed Developer Tools on tab then add-on won't reopen Developer Tools on this tab.

By default Developer Tools will be opened on tab `ready` event: when the DOM for a tab's content is ready.
If you need then Developer Tools may be opened earlier, immediately when a new tab is opened, for that open
`about:addons` > `DevTools Auto Open` > `Preferences` and check option `On tab open`.
`On tab open` is disabled by default because produces bugs
[#1](https://github.com/dmitry-kulikov/firefox-devtools-auto-open/issues/1),
[#2](https://github.com/dmitry-kulikov/firefox-devtools-auto-open/issues/2).


text:
'use strict';

function src(thisResource) {
  /* jshint validthis: true */
  var self = this;
  if (!thisResource.$ || self.isExternal(thisResource.url)) { return; }

  var $ = thisResource.$;
  var images = $('img');

  images.each(function () {
    var src = $(this).attr('src');
    if (validSrc(src)) {
      self.add(src, thisResource.url);
    }
  });
}

function validSrc(src) {
  if (!src) { return false; }
  if (/^(data:)/.test(src)) { return false; }
  return true;
}

module.exports = src;


text:
function output = c_mat_sliceToCell(mat,dim)
% slice a matrix up into pieces and return each piece as an element in a cell array
% (e.g. for constructing x,y,z input to scatter3 from a single list of 3d coordinates)
if nargin < 2
	dim = c_findFirstNonsingletonDimension(mat);
end

assert(isnumeric(mat)); % not actually necessary, could be removed

numSlices = size(mat,dim);
output = cell(1,numSlices);
permOrder = 1:ndims(mat);
permOrder = circshift(permOrder,-dim+1,2);
mat = permute(mat,permOrder);
origSize = size(mat);
mat = reshape(mat,origSize(1),prod(origSize(2:end)));
for i=1:numSlices
	sliceMat = mat(i,:);
	sliceMat = reshape(sliceMat,[1, origSize(2:end)]);
	sliceMat = ipermute(sliceMat,permOrder);
	output{i} = sliceMat;
end
end


text:
=====
Original
=====
This code was cloned from
   https://bitbucket.org/iamFIREcracker/osaic
and ported the code to use the PILLOW (by changing one line). So feel free to cite the original.

=====
osaic
=====

**osaic** is a simple python module which let you create mosaics from
images by issuing a simple ``python -mosaic foo.jpg`` command.

The basic idea is to take as input a set of images: the first is used as
background for the final mosaic; the others are indexed by average
colors and pated, as tiles, over the final mosaic.

In addition, users are enabled to specify the final size of the mosaic
(relative to the size of the initial target image) and the number of
tiles to use per side.

Dependencies
============

The module depends on python ``PIL`` library (automatically fetched by
the installation script) for all the operations concerning *image
processing*. In addition, to add support for *jpeg*\s and *png*\s
images, and to enable the module to display mosaics on screen, please
install ``libjpeg``, ``libpng`` and ``libtk`` as well.

Install
=======

To install **osaic**, you are enabled to grab it from both the mercurial
repository and from the Python Package Index (PyPI). The former is
preferred for *bleeding-edge* users, even tough the latter is not
guaranteed to be *very* stable as well.

Mercurial
---------

From sources::

    cd /wherever/you/want
    hg clone https://bitbucket.org/iamFIREcracker/osaic
    python setup.py install

PyPI
----

From sources::

    cd /path/to/workspace
    wget http://pypi.python.org/packages/source/o/osaic/osaic-2.0.0.tar.gz
    tar zxvf osaic-2.0.0.tar.gz
    cd osaic-2.0.0
    python setup.py install

From the PyPI::

    pip install osaic

Usage
=====

**osaic** is a module that can be used both as a standalone application
and as a standard python module.

Standalone application
----------------------

A typical usage of the application is to display a mosaic composition
created from a source image::

    python -mosaic image.jpg

If you want to save the output to a file instead of showing it::

    python -mosaic image.jpg -o mosaic-image.jpg

Finally, if you want to create a mosaic which is 4 times bigger than the
original image, and with 100 tiles per side, just issue::

    python -mosaic -z4 -t100 image.jpg

For everything else use the help message::

    python -mosaic -h

Library
-------

The module is a collection of objects and functions with different
capabilities: functions for vectors, color transformations, *image*
objects, image indexes and procedure wrappers.

Regarding operation with vectors, the module implement some basic
functions not included in standard Python but useful while working with
colors::

    >>> dotproduct([1, 2, 3], [4, 5, 6])
    70
    >>> difference([1, 2, 3], [1, 2, 3])
    [0, 0, 0]
    >>> squaredistance([1, 2, 3], [0, 0, 0])
    30

It is possible to find also a couple of functions wrapping up common
colors operations, like computation of the average color of an image and
color quantization. The latter is particularly useful while trying to
keep the CPU work load at low levels::

    >>> average_color('almost-red.png')
    (240, 10, 20)
    >>> quantize_color((240, 10, 20), levels=2)
    (192, 64, 64)

As noted earlier, the module is built on top of the Python ``PIL``
library. However, we chose not export such *external* objects, but
rather present to users some wrappers, namely `ImageWrapper`::

    >>> img = Image.open('foo.png')
    >>> img.size
    (640, 480)
    >>> img.reratio(5 / 1)
    >>> img.crop((0, 0, 10, 10))
    >>> img.size
    (10, 10)
    >>> img.show()

While creating mosaics, it comes in handy to have to possibility to
index a set of images and make it possible to search which of them is
the most similar, in terms of *average color*, to another one. The
``ImageList`` object is shipped with the module for this reason::

    >>> img_list = ImageList(['1.png', '2.png', '3.png'])
    >>> img_list.search((255, 0, 0))
    ImageTuple(filename='1.png', color=(255, 0, 0), image=None)

Finally, the module is shipped with a ``mosaicify`` function which wraps
up all the operations needed to create mosaic, including source images
indexing, and search of neighbour images depending on the average
color::

    >>> import osaic
    >>> osaic.mosaicify(
    ...     target='foo.png',
    ...     sources=['bar.png', 'asd.png', 'bazinga.png'],
    ...     tiles=128,
    ...     zoom=4,
    ...     output='mosaic.png',
    ... )


text:
TMGSEQL4 ;TMG/kst/Interface with SequelSystems PMS for ICD codes ;8/1/12, 2/2/14, 3/24/21
         ;;1.0;TMG-LIB;**1**;8/1/12

 ;"TMG SEQUEL ICD DIAGNOSIS CODES IMPORT FUNCTIONS
 ;
 ;"~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--
 ;"Copyright (c) 6/23/2015  Kevin S. Toppenberg MD
 ;"
 ;"This file is part of the TMG LIBRARY, and may only be used in accordence
 ;" to license terms outlined in separate file TMGLICNS.m, which should
 ;" always be distributed with this file.
 ;"~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--
 ;
 ;"=======================================================================
 ;" API -- Public Functions.
 ;"=======================================================================
 ;"ASKIMPORT
 ;"RUNNOW  -- provide an entry point for running import NOW.  This will delete prior alerts
 ;"AUTOIN  -- entry point for scheduled task
 ;"QUIETIN
 ;"$$IMPORTFILE(FILEPATH,FILENAME,ERRARRAY,PROGFN,DELFILES,USERID,BADICDLIST)
 ;"$$IMPORTGLOBAL(GREF,ERRARRAY,PROGFN,USERID,BADICDLIST)
 ;"=======================================================================
 ;"PRIVATE API FUNCTIONS
 ;"=======================================================================
 ;"$$PROCESLN(ONELINE,ERRARRAY,DUZ,PARSEFN,BADICDLIST)
 ;"$$PARSELN(ONELINE,ARRAY,BADICDLIST)
 ;"UPDATEDB(PCEINFO,ERRARRAY)
 ;"=======================================================================
 ;"DEPENDENCIES
 ;"TMGIOUTL
 ;"TMGMISC
 ;"=======================================================================
 ;"=======================================================================
 ;
DEBUGIN ;
        NEW TMPNAME
        NEW DEFPATH SET DEFPATH="/tmp/"
        NEW DEFFNAME SET DEFFNAME="demographics.csv"
        NEW FPATH,FNAME
        NEW ERRARRAY
        NEW RESULT
        ;
        SET TMPNAME=$$GETFNAME^TMGIOUTL("Please enter file to import.",.DEFPATH,.DEFFNAME,,.FPATH,.FNAME)
        IF TMPNAME="" GOTO AIDONE
        SET DEFPATH=FPATH
        ;
        NEW FILEPATH SET FILEPATH=FPATH
        NEW FILENAME SET FILENAME=FNAME
        NEW ERRARRAY
        NEW DELFILES
        NEW GREF,GREF1
        NEW RESULT
        ;
        SET GREF=$NAME(^TMP("TMG",$J,"SEQUELIMPORT","DATA",1))   ;"I use this to process array
        SET GREF1=$NAME(@GREF@(1))                   ;"I use this to load file
        KILL @GREF
        SET RESULT=$$FTG^%ZISH(FILEPATH,FILENAME,GREF1,6)  ;"load file into a global
        IF RESULT=0 GOTO IFDONE
        NEW USERID SET USERID=$GET(USERID,+$GET(DUZ))
        ;
        NEW TMGINVALID ;"Will be used as a globally-scoped variable in the module
        SET RESULT=1
        NEW DELAY SET DELAY=0
        NEW TMGCUR,TMGMAX,TMGSTART,TMGABORT ;"avail for PROGFN function
        SET TMGABORT=0
        SET TMGMAX=+$ORDER(@GREF@(""),-1)
        SET TMGSTART=$H  ;"store starting time.
        ;
        ;"---- finish conversion below....

        ;"Set up selector array
        ;" NEW TMGSel,TMGPick
        ;" NEW i SET i=0
        ;" FOR  SET i=$ORDER(@GREF@(i)) QUIT:i=""  DO
        ;" . NEW ONELINE SET ONELINE=$GET(@GREF@(i))
        ;" . NEW ID SET ID=$PIECE(ONELINE,",",1)
        ;" . NEW LName SET LName=$PIECE(ONELINE,",",3)
        ;" . NEW FNAME SET FNAME=$PIECE(ONELINE,",",4)
        ;" . SET TMGSel(LName_","_FNAME_" ("_ID_")",i)=""
        ;"
        ;" DO SELECTR2^TMGUSRI3("TMGSel","TMGPick","Pick Entries to Work On")
        ;"
        ;" NEW TMGDisplay SET TMGDisplay=""
        ;" FOR  SET TMGDisplay=$ORDER(TMGPick(TMGDisplay)) QUIT:TMGDisplay=""  DO
        ;" . NEW I SET I=0
        ;" . FOR  SET I=$ORDER(TMGPick(TMGDisplay,I)) QUIT:I=""  DO
        ;" . . NEW ONELINE SET ONELINE=$GET(@GREF@(I))
        ;" . . SET RESULT=$$PROCESLN(ONELINE,.ERRARRAY,USERID)
        ;"
        ;" KILL @GREF
        ;" KILL @G2Ref
        ;"
        ;" DO  ;"record the current time as the time of last import
        ;" . DO NOW^%DTC
        ;" . NEW TMGFDA,TMGMSG
        ;" . SET TMGFDA(22711,"1,",4)=%  ;"#4 = LAST IMPORT DATE
        ;" . DO FILE^DIE("E","TMGFDA","TMGMSG")  ;" note: ignores TMGMSG or errors.
        ;"
        QUIT
        ;
        ;
ASKIMPORT  ;
        ;"Purpose: To ask user for filename and then import ICD data.
        ;"Input: None
        ;"Output: Database is updated with data from file.
        ;"Result: None
        ;
        NEW TMPNAME,TMGKEYIN
        NEW DEFPATH SET DEFPATH="/mnt/WinServer/"
        NEW DEFFNAME SET DEFFNAME="ICD_By_Patient.csv"
        NEW FPATH,FNAME,ERRARRAY,RESULT
        NEW PROGFN SET PROGFN="DO PROGBAR^TMGUSRI2(TMGCUR,""Progress"",1,TMGMAX,,TMGSTART)"
        SET PROGFN=PROGFN_" READ *TMGKEYIN:0 SET:(TMGKEYIN=27) TMGABORT=1"
        SET TMPNAME=$$GETFNAME^TMGIOUTL("Please enter file to import.",.DEFPATH,.DEFFNAME,,.FPATH,.FNAME)
        IF TMPNAME="" GOTO AIDONE
        SET DEFPATH=FPATH
        NEW BADICDLIST
        WRITE !,!,"Importing ICD-9 codes into problem list.",!
        WRITE "Running this multiple times will NOT lead to",!
        WRITE "duplicate entries",!,!
        SET RESULT=$$IMPORTFILE(FPATH,FNAME,.ERRARRAY,PROGFN,,,.BADICDLIST)
        IF $DATA(BADICDLIST) DO
        . WRITE "Here is a list of missing ICD-9 codes in the VistA system.",!
        . DO ZWRITE^TMGZWR("BADICDLIST")
AIDONE  QUIT
        ;
        ;
RUNNOW  ;
        ;"Purpose: To provide an entry point for running import NOW.  This will delete prior alerts
        ;"Input: none.  Settings stored in File 22711 are used
        ;"Output: None.  Progress shown to console.  The database should be updated
        ;"Results: none
        ;
        WRITE !!,"Importing Sequel ICD Diagnosis codes now...",!
        NEW FNAME SET FNAME=$$GET1^DIQ(22711,"1,","IMPORT ICD DATAFILE NAME")
        NEW FPATH SET FPATH=$$GET1^DIQ(22711,"1,","IMPORT DATAFILE PATH")
        NEW DELFILES SET DELFILES=+$$GET1^DIQ(22711,"1,","DELETE DATAFILE AFTER IMPORT?","I")
        NEW USERID SET USERID=$$GET1^DIQ(22711,"1,","ALERT RECIPIENT","I")
        NEW PROGFN SET PROGFN="DO PROGBAR^TMGUSRI2(TMGCUR,""Progress"",1,TMGMAX,,TMGSTART)"
        SET PROGFN=PROGFN_" READ *TMGKEYIN:0 SET:(TMGKEYIN=27) TMGABORT=1"
        NEW BADICDLIST
        NEW RESULT SET RESULT=$$IMPORTFILE(FPATH,FNAME,,PROGFN,DELFILES,USERID,.BADICDLIST)
        QUIT
        ;
AUTOIN  ;
        ;"Purpose: To provide an entry point for a scheduled task.  This will delete prior alerts
        ;"Input: none.  Settings stored in File 22711 are used
        ;"Output: None.  There should be no console output.  The database should be updated
        ;"Results: none
        ;
        NEW INITTIME SET INITTIME=$H
        NEW USERID SET USERID=$$GET1^DIQ(22711,"1,","ALERT RECIPIENT","I")
        ;
        DO  ;"clear out 'next run task number'
        . NEW TMGFDA,TMGMSG
        . SET TMGFDA(22711,"1,",8)="@"  ;"#4 = TASK FOR NEXT RUN
        . DO FILE^DIE("E","TMGFDA","TMGMSG")  ;" note: ignores TMGMSG or errors.
        ;
        NEW TEMP SET TEMP=$$QuietClear^TMGSEQL3(USERID,"TMGSQLICDIMPORT")  ;"clear prior alerts & errors
        DO QUIETIN  ;" DO import
        ;
        ;"Here I schedule the next task to run again.
        NEW HRINT SET HRINT=$$GET1^DIQ(22711,"1,","IMPORT FREQUENCY (IN HOURS)","I")
        IF +HRINT>0 DO
        . NEW TIME SET TIME=$$HADD^XLFDT(INITTIME,0,HRINT,0)
        . NEW task SET task=$$Schedule^TMGSEQL3(TIME,"AUTOIN^TMGSEQL4","Import of ICD data from Sequel PMS.")
        . ;"store 'next run task number'
        . SET TMGFDA(22711,"1,",8)="`"_task  ;"#4 = TASK FOR NEXT RUN
        . DO FILE^DIE("E","TMGFDA","TMGMSG")  ;" note: ignores TMGMSG or errors.
        ;
        QUIT
        ;
        ;
QUIETIN ;
        ;"Purpose: To import data based on settings, with no user interaction (in or out)
        ;"Input: none.  Settings stored in File 22711 are used
        ;"Output: None.  There should be no console output.  The database should be updated
        ;"Results: none
        ;
        NEW FNAME SET FNAME=$$GET1^DIQ(22711,"1,","IMPORT ICD DATAFILE NAME")
        NEW FPATH SET FPATH=$$GET1^DIQ(22711,"1,","IMPORT DATAFILE PATH")
        NEW DELFILES SET DELFILES=+$$GET1^DIQ(22711,"1,","DELETE DATAFILE AFTER IMPORT?","I")
        NEW USERID SET USERID=$$GET1^DIQ(22711,"1,","ALERT RECIPIENT","I")
        NEW PROGFN SET PROGFN="DO PROGBAR^TMGUSRI2(TMGCUR,""Progress"",1,TMGMAX,,TMGSTART)"
        NEW BADICDLIST,ERRARRAY
        SET RESULT=$$IMPORTFILE(FPATH,FNAME,.ERRARRAY,PROGFN,DELFILES,USERID,.BADICDLIST)
        QUIT
        ;
        ;
IMPORTFILE(FILEPATH,FILENAME,ERRARRAY,PROGFN,DELFILES,USERID,BADICDLIST)
        ;"Purpose: To import data from file specified.
        ;"Input:   FILEPATH: Path of file to input.
        ;"         FILENAME: The Name of file of file to input.
        ;"              Note: This is written to import a specific file
        ;"                      created by SequelMed Systems, filled with
        ;"                      patient demographics, in CVS format
        ;"              Note: This file will be DELETED IF DELFILES=1
        ;"         ERRARRAY: PASS BY REFERENCE.  Array to receive failed data lines.
        ;"         PROGFN: OPTIONAL -- IF supplied, then M code contained in this string
        ;"              will be xecuted periodically, to allow display of a progress bar etc.
        ;"              Note: the following variables with global scope will be declared and
        ;"                      available for use: TMGCUR (current count), TMGMAX (max count),
        ;"                      TMGSTART (the start time
        ;"                      External function can signal a request an abort by setting TMGABORT=1
        ;"         DELFILES: OPTIONAL -- IF 1, then source files (FILENAME and F2Name) are deleted after import
        ;"         USERID : OPTIONAL -- user to receive alerts regarding errors.  Default is current user (DUZ)
        ;"         BADICDLIST -- PASS BY REFERENCE. This will be an accumulated list of missing ICD-9 codes.
        ;"Output: Database is updated with data from file.
        ;"Result: 1 successful completion, 0=error
        ;
        NEW GREF,GREF1,RESULT
        SET GREF=$NAME(^TMP("TMG",$J,"SEQUELIMPORT","DATA",1))   ;"I use this to process array
        SET GREF1=$NAME(@GREF@(1))                   ;"I use this to load file
        KILL @GREF
        SET RESULT=$$FTG^%ZISH(FILEPATH,FILENAME,GREF1,6)  ;"load file into a global
        IF RESULT=0 GOTO IFDONE
        SET USERID=$GET(USERID,+$GET(DUZ))
        SET RESULT=$$IMPORTGLOBAL(GREF,.ERRARRAY,.PROGFN,USERID,.BADICDLIST)  ;"Note: @GREF, killed at end of $$IMPORTGLOBAL()
        ;"Next, record the current time as the time of last import
        DO NOW^%DTC
        NEW TMGFDA,TMGMSG
        SET TMGFDA(22711,"1,",4)=%  ;"#4 = LAST IMPORT DATE
        DO FILE^DIE("E","TMGFDA","TMGMSG")  ;" note: ignores TMGMSG or errors.
        IF $GET(DELFILES)=1 DO
        . ;"Notice: After I implemented this, I realized that I have a permissions problem
        . ;"  at my site... the uploaded files belong to the uploaded user, and deletion by
        . ;"  this user is being blocked.  I'll leave in for now...
        . NEW TEMP
        . SET TEMP=$$DELFILE^TMGIOUTL(FILEPATH_FILENAME)
        . SET TEMP=$$DELFILE^TMGIOUTL(F2Path_F2Name)
        ;
IFDONE  QUIT RESULT
        ;
        ;
IMPORTGLOBAL(GREF,ERRARRAY,PROGFN,USERID,BADICDLIST)
        ;"Purpose: To import data from global specified.
        ;"Input:   GREF -- the NAME of array holding the data to import (1st file)
        ;"              Format: @GREF@(1)=ONELINE
        ;"                      @GREF@(2)=ONELINE .. etc.
        ;"              Note: This is written to import a specific file
        ;"                      created by SequelMed Systems, filled with
        ;"                      patient ICD data, in CVS format
        ;"              Note: ARRAY will be KILLED at the end of this function.
        ;"         ERRARRAY: PASS BY REFERENCE.  Array to receive failed data lines.
        ;"         PROGFN: OPTIONAL -- IF supplied, then M code contained in this string
        ;"              will be xecuted periodically, to allow display of a progress bar etc.
        ;"              Note: the following variables with global scope will be declared and
        ;"                      available for use: TMGCUR (current count), TMGMAX (max count),
        ;"                      TMGSTART (the start time
        ;"                      External function can signal a request an abort by setting TMGABORT=1
        ;"         USERID : OPTIONAL -- user to receive alerts regarding errors.  Default is current user (DUZ)
        ;"        BADICDLIST -- PASS BY REFERENCE. This will be an accumulated list of missing ICD-9 codes.
        ;"Output: Database is updated with data from file.
        ;"Result: 1 successful completion, 0=error
        ;
        NEW TMGINVALID ;"Will be used as a globally-scoped variable in the module
        NEW RESULT SET RESULT=1
        NEW DELAY SET DELAY=0
        NEW TMGCUR,TMGMAX,TMGSTART,TMGABORT ;"avail for PROGFN function
        SET TMGABORT=0
        SET TMGMAX=+$ORDER(@GREF@(""),-1)
        SET TMGSTART=$H  ;"store starting time.
        SET USERID=$GET(USERID,+$GET(DUZ))
        ;
        SET TMGCUR=$ORDER(@GREF@(""))
        IF TMGCUR'="" FOR  DO  QUIT:(TMGCUR="")!(TMGABORT=1)
        . NEW ONELINE SET ONELINE=$GET(@GREF@(TMGCUR))
        . SET RESULT=$$PROCESLN(ONELINE,.ERRARRAY,USERID,,.BADICDLIST)
        . SET DELAY=DELAY+1
        . IF (DELAY>30),$GET(PROGFN)'="" DO  ;"update progress bar every 30 cycles
        . . NEW $ETRAP SET $ETRAP="WRITE ""(Invalid M Code!.  Error Trapped.)"" SET $ETRAP="""",$ecode="""""
        . . XECUTE PROGFN  ;"call the specified progress code.
        . . SET DELAY=0
        . SET TMGCUR=$ORDER(@GREF@(TMGCUR))
        ;
        KILL @GREF
        QUIT RESULT
        ;
        ;
PROCESLN(ONELINE,ERRARRAY,DUZ,PARSEFN,BADICDLIST)
        ;"Purpose: To process one line from patient ICD/CPT import file.
        ;"Input: ONELINE-- One line from CVS file.
        ;"       ERRARRAY: PASS BY REFERENCE.  Array to receive failed data lines.
        ;"       DUZ: The user who will recieve alerts of errors
        ;"       PARSEFN:  OPTIONAL-- the name of a function to use to parse csv line
        ;"              default value is "PARSELN"
        ;"              e.g. "MyFn" or "MyFn^MyRoutine".  Must take same params as PARSELN
        ;"              This will allow this code to be used on a variety of .csv files, with
        ;"              different data-formats--each one with its own parser funtion.
        ;"       BADICDLIST -- PASS BY REFERENCE. This will be an accumulated list of missing ICD-9 codes.
        ;"Output: Data is put into database, IF it is not there already.
        ;"Result: 1=OK To continue; -1=abort or bad data
        ;
        NEW XFN
        NEW PCEINFO,ERR1ARRY
        NEW RESULT SET RESULT=1
        SET PARSEFN=$GET(PARSEFN,"PARSELN")
        SET XFN="SET RESULT=$$"_PARSEFN_"(.ONELINE,.PCEINFO,.BADICDLIST)"
        XECUTE XFN
        IF +RESULT<1 DO  GOTO PLNDN
        . NEW MSG SET MSG=$PIECE(RESULT,"^",2)
        . IF MSG="SKIP" SET RESULT=1 QUIT
        . SET ERR1ARRY(0)=MSG
        . DO MARKERR(ONELINE,.PCEINFO,.ERR1ARRY,.ERRARRAY)  ;
        SET RESULT=$$UPDATEDB(.PCEINFO,.ERR1ARRY)
        IF RESULT<1 DO MARKERR(ONELINE,.ERR1ARRY,.ERRARRAY)  ;
PLNDN   QUIT RESULT
        ;
MARKERR(SRCLINE,PCEINFO,ERR1ARRY,ERRARRAY)  ;
        ;"Purpose: report error on one line from CSV import file
        ;"Input: SRCLINE -- The original import CSV line
        ;"       PCEINFO -- Event info array
        ;"       ERR1ARRY -- PASS BY REFERENCE.  The Array containing the error information,
        ;"          with following format:
        ;"          ERR1ARRY(0)=local message (if any)
        ;"          ERR1ARRY("DIERR")=Standard fileman DIERR array.
        ;"       ERRARRAY -- PASS BY REFERENCE.  Master error array.
        ;
        NEW SKIP SET SKIP=0
        NEW MSG SET MSG=$GET(ERR1ARRY(0))
        IF MSG'="" DO  GOTO:SKIP MERDN
        . IF $DATA(ERRARRAY("MSG",MSG)) SET SKIP=1 QUIT
        . SET ERRARRAY("MSG",MSG)=""
        NEW COUNT SET COUNT=+$GET(ERRARRAY)+1
        SET ERRARRAY=COUNT
        SET ERRARRAY(COUNT)=SRCLINE
        MERGE ERRARRAY(COUNT,"INFO")=ERR1ARRY
        ;"TEMP RESTORE LATER --> DO ALERTERR^TMGSEQL2(SRCLINE,.PCEINFO,.ERR1ARRY,DUZ,"TMGSQLICDIMPORT")
        WRITE !,"HERE I WOULD ALERT ERROR:",!
        IF $DATA(ERR1ARRY) DO ZWRITE^TMGZWR("ERR1ARRY")
MERDN   QUIT
        ;
        ;
PARSELN(ONELINE,ARRAY,BADICDLIST)
        ;"Purpose: To process one line from patient demographics file.
        ;"         Also gets data into an acceptible format.
        ;"Input: ONELINE -- One line from CVS demographics file. (Format as per PROCESLN)
        ;"           Format is as follows, *** all on one line (comma delimited)
        ;"           01- Insurance_Name
        ;"           02- visit_date_from
        ;"           03- proc_cpt_code
        ;"           04- practice_name
        ;"           05- location_name
        ;"           06- provider_name
        ;"           07- total_amount_charged
        ;"           08- total_amount_paid
        ;"           09- total_adjustment
        ;"           10- icd_9_code  (may be multiple, space delimited)
        ;"           11- modifier
        ;"           12- visit_seq_num
        ;"           13- charge_seq_num
        ;"           14- patient_seq_num
        ;"           15- parent_seq_num
        ;"           16- account_num <-- matches custom field 22701 in PATIENT file
        ;"           17- last_name
        ;"           18- first_name
        ;"           19- plan_priority_type
        ;"           20- plan_id
        ;"           21- ref_provider
        ;"           22- asst_provider
        ;"           23- entry_date
        ;"           24- panel_group
        ;"           25- num_of_units
        ;"       ARRAY -- PASS BY REFERENCE. And OUT parameter.  Any prior data killed. Format:
        ;"           ARRAY("DATE")= Event date (in internal Fileman format)
        ;"           ARRAY("PROC CPT CODE")=Procedure code for event
        ;"           ARRAY("LOCATION")=Location IEN for event
        ;"           ARRAY("PROVIDER")=Provider IEN for event
        ;"           ARRAY("PATIENT")=DFN^Patient Name
        ;"           ARRAY("ICD CODE",ICD_IEN)=Text Description
        ;"           ARRAY("ICD CODE",ICD_IEN,"LEX")=IEN757.01^Lex Descr^IC9_Name^ICD_IEN^ICD Set Name
        ;"       BADICDLIST -- PASS BY REFERENCE. This will be an accumulated list of missing ICD-9 codes.
        ;"       Note: uses TMGINVALID (globally scoped var defined in this module)
        ;"Output: ARRAY is filled with Format as follows (note not all data used):
        ;"Result: 1=OK To continue; -1^Error Message -1^SKIP IF should skip this
        ;
        NEW TEMP
        NEW RESULT SET RESULT=1
        SET ONELINE=$TRANSLATE($GET(ONELINE),"""","'") ;"  convert " to ' to avoid fileman error
        KILL ARRAY
        ;"-----------------------------
        NEW DATE SET DATE=$PIECE(ONELINE,",",2)
        SET DATE=$$TRIM^XLFSTR(DATE)
        IF DATE="visit_date_from" DO  GOTO PLDN  ;"Skip header row
        . SET RESULT="-1^SKIP"
        SET DATE=$PIECE(DATE," ",1)   ;" '03/09/05 00:00' --> '03/09/05'
        NEW %DT,X,Y
        SET %DT="P",X=DATE DO ^%DT
        IF +Y<0 DO  GOTO PLDN
        . SET RESULT="-1^Date '"_DATE_"' is not valid."
        SET ARRAY("DATE")=Y
        ;"-----------------------------
        SET ARRAY("PROC CPT CODE")=$$Trim^TMGSTUTL($PIECE(ONELINE,",",3))
        ;"-----------------------------
        NEW LOC SET LOC=$$Trim^TMGSTUTL($PIECE(ONELINE,",",5))
        NEW LOCIEN SET LOCIEN=+$ORDER(^SC("TMGPMS",LOC,0))
        IF LOCIEN'>0 DO  GOTO PLDN
        . IF $$SKIPLOC(LOC) SET RESULT="-1^SKIP" QUIT
        . SET RESULT="-1^Location '"_LOC_"' not found in field 'TMG PMS NAME' for any record in HOSPITAL LOCATION file."
        SET ARRAY("LOCATION")=LOCIEN
        ;"-----------------------------
        NEW TEMPPROV SET TEMPPROV=$PIECE(ONELINE,",",6)
        IF TEMPPROV="" DO  GOTO PLDN
        . SET RESULT="-1^No Provider found for event"
        ;"SET TEMPPROV=$$ConvProvider^TMGSEQL1(TEMPPROV)
        ;"IF TEMPPROV="SKIP" DO  GOTO PLDN
        ;". SET RESULT="-1^Provider 'SKIP' invalid"
        IF $$INVALPRV^TMGSEQL1(TEMPPROV) DO  GOTO PLDN
        . SET RESULT="-1^SKIP"
        NEW PROVIEN SET PROVIEN=+$ORDER(^VA(200,"TMG",TEMPPROV,0))
        IF PROVIEN'>0 DO  GOTO PLDN
        . SET RESULT="-1^Unable to find provider '"_TEMPPROV_"'"
        SET ARRAY("PROVIDER")=PROVIEN
        ;"-----------------------------
        NEW ACCTNUM SET ACCTNUM=+$PIECE(ONELINE,",",16)
        IF ACCTNUM'>0 DO  GOTO PLDN
        . SET RESULT="-1^Patient PMS account number not provided."
        NEW TMGDFN SET TMGDFN=$ORDER(^DPT("TMGS",ACCTNUM,0))
        IF TMGDFN'>0 DO  GOTO PLDN
        . SET RESULT="-1^Unable to convert PMS account number '"_ACCTNUM_"' into VistA patient number (DFN)"
        SET ARRAY("PATIENT")=TMGDFN_"^"_$PIECE($GET(^DPT(TMGDFN,0)),"^",1)
        ;"-----------------------------
        NEW ICDTEMP SET ICDTEMP=$PIECE(ONELINE,",",10)
        NEW I FOR I=1:1:$LENGTH(ICDTEMP," ") DO
        . NEW ANICD SET ANICD=$PIECE(ICDTEMP," ",I) QUIT:ANICD=""
        . NEW ICDIEN SET ICDIEN=+$ORDER(^ICD9("BA",ANICD_" ",0))
        . IF ICDIEN>0 DO  QUIT
        . . NEW DESCR SET DESCR=$PIECE($GET(^ICD9(ICDIEN,0)),"^",3)
        . . SET ARRAY("ICD CODE",ICDIEN)=DESCR
        . . NEW LEXARR,LEXINFO
        . . DO LEXSRCH^ORQQPL1(.LEXARR,ANICD,1,,0)
        . . SET LEXINFO=$GET(LEXARR(1))
        . . SET ARRAY("ICD CODE",ICDIEN,"LEX")=LEXINFO
        . ELSE  SET BADICDLIST(ANICD)=""
        . ;"IF RESULT=1 SET RESULT="-1^"
        . ;"SET RESULT=RESULT_"ICD-9 code '"_ANICD_"' not in VistA. "
        IF $DATA(ARRAY("ICD CODE"))=0 DO
        . SET RESULT="-1^SKIP"
        ;"-----------------------------
PLDN    QUIT RESULT
        ;
        ;
SKIPLOC(LOC)  ;
        ;"Return is location should be skipped
        ;"Results: 1 IF should be skipped, 0 IF no skipped
        NEW RESULT SET RESULT=0
        IF LOC="LAUHOSPIN" SET RESULT=1
        ELSE  IF LOC="LAUHOSPOUT" SET RESULT=1
        ELSE  IF LOC="PML" SET RESULT=1
        ELSE  IF LOC="TMG-FPG" SET RESULT=1
        QUIT RESULT
        ;
        ;
UPDATEDB(PCEINFO,ERR1ARRY)
        ;"Purpose: To put that data from the PCEINFO array into the database (if needed)
        ;"Input: PCEINFO -- array (PASS BY REFERENCE), with the following items being used:
        ;"           PCEINFO("DATE")= Event date (in internal Fileman format)
        ;"           PCEINFO("PROC CPT CODE")=Procedure code for event
        ;"           PCEINFO("LOCATION")=Location IEN for event
        ;"           PCEINFO("PROVIDER")=Provider IEN for event
        ;"           PCEINFO("PATIENT")=DFN^Patient Name
        ;"           PCEINFO("ICD CODE",ICD_IEN)=Text Description
        ;"           PCEINFO("ICD CODE",ICD_IEN,"LEX")=IEN757.01^Lex Descr^IC9_Name^ICD_IEN^ICD Set Name
        ;"      ERR1ARRY -- PASS BY REFERENCE.  And OUT parameter to get back error info.
        ;"Output: Data is put into database, IF it is not there already.
        ;"Result: 1 successful completion, -1=error
        ;
        SET RESULT=1
        NEW TMGDFN SET TMGDFN=+PCEINFO("PATIENT")
        NEW PROBEXISTS SET PROBEXISTS=0
        NEW ICDIEN SET ICDIEN=0
        FOR  SET ICDIEN=$ORDER(PCEINFO("ICD CODE",ICDIEN)) QUIT:ICDIEN=""  DO
        . NEW STATUS SET STATUS=$$GETSTAT(TMGDFN,ICDIEN)
        . IF +STATUS=1 QUIT  ;"Already has ICD code in problem
        . IF +STATUS=0 SET RESULT=$$ADDPROB(ICDIEN,.PCEINFO,.ERR1ARRY)  ;"Add NEW problem
        . IF +STATUS=2 DO
        . . NEW INACTIVEDATE SET INACTIVEDATE=+$PIECE(STATUS,"^",2)
        . . NEW THISDATE SET THISDATE=PCEINFO("DATE")
        . . IF INACTIVEDATE>THISDATE QUIT
        . . NEW PROBIEN SET PROBIEN=$PIECE(STATUS,"^",2)  ;"PROBIEN = pre-existing PROBLEM record IEN
        . . SET RESULT=$$ACTVPROB(PROBIEN,.ERR1ARRY)
        QUIT RESULT
        ;
        ;
GETSTAT(TMGDFN,ICDIEN)  ;
        ;"Purpose: determine status on an ICD code in problems for a patient
        ;"Results: 0=No problem with this ICD code exists for patient
        ;"         1^PROBIEN=problem with this ICD code exists, and is active
        ;"         2^PROBIEN^FMDATE = problem with this ICD code exists, but is INACTIVE
        ;"                    PROBIEN = IEN of the existing problem
        ;"                    FMDATE is the date the problem was inactivated.
        ;"
        NEW RESULT SET RESULT=0
        NEW PROBIEN SET PROBIEN=0
        FOR  SET PROBIEN=$ORDER(^AUPNPROB("AC",TMGDFN,PROBIEN)) QUIT:(+PROBIEN'>0)!(RESULT=1)  DO
        . NEW THISICD SET THISICD=$PIECE($GET(^AUPNPROB(PROBIEN,0)),"^",1)
        . IF THISICD'=ICDIEN QUIT
        . SET RESULT=1_"^"_PROBIEN
        . NEW STATUS SET STATUS=$PIECE($GET(^AUPNPROB(PROBIEN,0)),"^",12)
        . IF STATUS'="I" QUIT
        . SET RESULT=2_"^"_PROBIEN_"^"_$PIECE($GET(^AUPNPROB(PROBIEN,1)),"^",7)  ;" 1;7=DATE RESOLVED
        QUIT RESULT
        ;
        ;
ACTVPROB(PROBIEN,ERR1ARRY)  ;
        ;"Purpose: Activate existing problem.
        ;"Input: PROBIEN -- The IEN of the problem in the PROBLEM file (#9000011)
        ;"      ERRARRAY -- PASS BY REFERENCE.  And OUT parameter to get back error info.
        ;"Result: 1 successful completion, -1=error
        NEW RESULT SET RESULT=1
        NEW TMGFDA,TMGMSG
        SET TMGFDA(9000011,PROBIEN_",",.12)="A"
        DO FILE^DIE("K","TMGFDA","TMGMSG")
        IF $DATA(TMGMSG("DIERR")) DO
        . MERGE ERR1ARRAY=TMGMSG
        . SET RESULT=-1
        QUIT RESULT
        ;
        ;
ADDPROB(PROBIEN,PCEINFO,ERR1ARRY)  ;"Add NEW problem
        ;"Purpose: Create a NEW problem for patient, using entry for RPC 'ORQQPL ADD SAVE'
        ;"Input: PCEINFO -- PASS BY REFERENCE.  Format:
        ;"           PCEINFO("DATE")= Event date (in internal Fileman format)
        ;"           PCEINFO("PROC CPT CODE")=Procedure code for event
        ;"           PCEINFO("LOCATION")=Location IEN for event
        ;"           PCEINFO("PROVIDER")=Provider IEN for event
        ;"           PCEINFO("PATIENT")=DFN^Name
        ;"           PCEINFO("ICD CODE",ICD_IEN)=Text Description
        ;"Results: 1 if OK, or -1 IF error
        ;
        NEW RESULT SET RESULT=-1
        NEW TMGDFN SET TMGDFN=PCEINFO("PATIENT")
        NEW PROV SET PROV=PCEINFO("PROVIDER")
        NEW MSG SET MSG=PCEINFO("ICD CODE",PROBIEN)
        IF +$GET(DUZ(2))'>0 DO DUZ^XUP(DUZ)
        NEW FACILITY SET FACILITY=+$GET(DUZ(2))
        IF FACILITY'>0 SET FACILITY=$ORDER(^VA(200,DUZ,2,0))
        NEW LEXINFO SET LEXINFO=$GET(PCEINFO("ICD CODE",PROBIEN,"LEX"))
        IF LEXINFO'="" SET MSG=$PIECE(LEXINFO,"^",2)
        NEW X,NOWDATE DO NOW^%DTC SET NOWDATE=X
        NEW ARR1
        SET ARR1(.01)=PROBIEN
        SET ARR1(.03)="0^"
        SET ARR1(.05)="^"_MSG
        SET ARR1(.08)=PCEINFO("DATE")
        SET ARR1(.12)="A^ACTIVE"
        SET ARR1(.13)="^"
        IF LEXINFO'="" SET ARR1(1.01)=$PIECE(LEXINFO,"^",1,2)
        SET ARR1(1.02)="T"  ;"T = transcribed (and will be flagged). Or could use "P"-- permanent
        SET ARR1(1.03)=PROV
        SET ARR1(1.04)=PROV
        SET ARR1(1.05)=PROV
        SET ARR1(1.06)="^"
        SET ARR1(1.07)="^"
        SET ARR1(1.08)=PCEINFO("LOCATION")
        SET ARR1(1.09)=NOWDATE
        SET ARR1(1.1)="0^NO"
        SET ARR1(1.11)="0^NO"
        SET ARR1(1.12)="0^NO"
        SET ARR1(1.13)="0^NO"
        SET ARR1(1.14)="^"
        SET ARR1(1.15)="^"
        SET ARR1(1.16)="^"
        NEW TMGARR
        NEW FLD SET FLD=0
        NEW CNT SET CNT=1
        FOR  SET FLD=$ORDER(ARR1(FLD)) QUIT:(FLD="")  DO
        . NEW VAL SET VAL=$GET(ARR1(FLD)) QUIT:VAL=""
        . SET TMGARR(CNT)="GMPFLD("_FLD_")="""_VAL_""""
        . SET CNT=CNT+1
        ;"SET ARR1(10,0)="0"
        SET TMGARR(CNT)="GMPFLD(10,0)=""0"""
        DO ADDSAVE^ORQQPL1(.RESULT,TMGDFN,PROV,FACILITY,.TMGARR)
        IF RESULT<1 DO
        . SET ERR1ARRY(0)="Unable to add NEW problem via ORQQPL ADD SAVE functionality"
        QUIT RESULT
        ;


text:
package com.google.cloud.solutions.autotokenize.testing;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.stream.Collectors.toList;

import com.google.common.flogger.GoogleLogger;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public final class TestCsvFileGenerator {

  public static final int DEFAULT_COLUMN_COUNT = 5;
  public static final int DEFAULT_ROWS_COUNT = 100;

  private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();

  private final int numberOfRows;
  private final int numColumns;
  private final boolean addHeader;
  private final char delimiter;

  private TestCsvFileGenerator(
      int numberOfRows, int numColumns, boolean addHeader, char delimiter) {
    this.numberOfRows = numberOfRows;
    this.numColumns = numColumns;
    this.addHeader = addHeader;
    this.delimiter = delimiter;
  }

  public static TestCsvFileGenerator create() {
    return new TestCsvFileGenerator(DEFAULT_ROWS_COUNT, DEFAULT_COLUMN_COUNT, false, ',');
  }

  public TestCsvFileGenerator addHeaderRow() {
    return new TestCsvFileGenerator(numberOfRows, numColumns, true, delimiter);
  }

  public TestCsvFileGenerator withRowCount(int numberOfRows) {
    return new TestCsvFileGenerator(numberOfRows, numColumns, addHeader, delimiter);
  }

  public TestCsvFileGenerator withColumnCount(int numColumns) {
    return new TestCsvFileGenerator(numberOfRows, numColumns, addHeader, delimiter);
  }

  public TestCsvFileGenerator withDelimiter(char delimiter) {
    return new TestCsvFileGenerator(numberOfRows, numColumns, addHeader, delimiter);
  }

  public List<List<String>> writeRandomRecordsToFile(String fileName) throws IOException {
    logger.atInfo().log(
        "Creating %s records (headers(%s): %s) in fileName %s",
        numberOfRows, addHeader, numColumns, fileName);

    var headers =
        IntStream.range(0, numColumns).mapToObj(x -> "header-" + x).collect(toImmutableList());

    var randomStringGenerator = new RandomStringGenerator();

    var csvData =
        Stream.concat(
                (addHeader ? Stream.of(headers) : Stream.of()),
                IntStream.range(0, numberOfRows)
                    .mapToObj(
                        x ->
                            IntStream.range(0, numColumns)
                                .boxed()
                                .map(randomStringGenerator::buildRandomString)
                                .collect(toList())))
            .collect(toList());

    writeRecordsToFile(csvData, fileName);
    return csvData;
  }

  public void writeRecordsToFile(List<List<String>> csvRecords, String fileName)
      throws IOException {

    try (var csvPrinter =
        new CSVPrinter(new FileWriter(fileName), CSVFormat.DEFAULT.withDelimiter(delimiter))) {
      for (var testRow : csvRecords) {
        csvPrinter.printRecord(testRow);
      }

      csvPrinter.close(true);
    }
  }

  static class RandomStringGenerator {
    private final Random random;

    RandomStringGenerator() {
      random = new Random();
    }

    String buildRandomString(int x) {
      return random
          .ints('a', 'z' + 1)
          .limit(random.nextInt(20))
          .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
          .toString();
    }

    String buildRandomString() {
      return buildRandomString(0);
    }
  }
}


text:
package us.nineworlds.xstreamer.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.eclipse.jface.viewers.TreeNode;

import com.github.xws.Pilot;
import com.github.xws.Upgrades;

public class PilotTreeNode extends TreeNode {

	private static final long serialVersionUID = -9033190175203649457L;
	private Pilot pilot;
	private Upgrades upgrades;

	public PilotTreeNode(Pilot userObject) {
		super(userObject);
		pilot = userObject;
		upgrades = pilot.getUpgrades();
	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(pilot.getName());
		stringBuilder.append(" (");
		stringBuilder.append(pilot.getPoints());
		stringBuilder.append(")");
		return stringBuilder.toString();
	}

	@Override
	public boolean hasChildren() {
		if (upgrades != null) {
			return upgrades.getAdditionalProperties().size() > 0;
		}

		return false;
	}

	@Override
	public TreeNode[] getChildren() {
		List<UpgradeTreeNode> upgrades = new ArrayList<>();
		for (Entry<String, Object> entry : this.upgrades.getAdditionalProperties().entrySet()) {
			UpgradeTreeNode upgradesTreeNode = new UpgradeTreeNode(entry.getKey(), (List<String>) entry.getValue(), this.upgrades);
			upgrades.add(upgradesTreeNode);
		}

		return upgrades.toArray(new TreeNode[upgrades.size()]);
	}
}


text:
package org.nmdp.hmlfhirconverter.service;

import org.nmdp.hmlfhirconverter.dao.HaploidRepository;
import org.nmdp.hmlfhirconverter.dao.custom.HaploidCustomRepository;
import org.nmdp.hmlfhirconvertermodels.domain.Haploid;
import org.nmdp.hmlfhirconverter.service.base.MongoCrudRepositoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class HaploidServiceImpl extends MongoCrudRepositoryService<Haploid, org.nmdp.hmlfhirconvertermodels.dto.Haploid> implements HaploidService {

    @Autowired
    public HaploidServiceImpl(@Qualifier("haploidRepository") HaploidRepository haploidRepository,
                             @Qualifier("haploidCustomRepository") HaploidCustomRepository haploidCustomRepository) {
        super(haploidCustomRepository, haploidRepository, Haploid.class, org.nmdp.hmlfhirconvertermodels.dto.Haploid.class);
    }
}


text:
<!DOCTYPE html>
<html>
<!--
@license
Copyright (C) 2010 The Libphonenumber Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
  Author: Nikolaos Trogkanis
-->
<head>
<meta charset="utf-8">
<title>libphonenumber Unit Tests - i18n.phonenumbers - phonenumberutil.js</title>
<script src="../../../../closure-library/closure/goog/base.js"></script>
<script>
  goog.require('goog.proto2.Message');
</script>
<script src="phonemetadata.pb.js"></script>
<script src="phonenumber.pb.js"></script>
<script src="metadatafortesting.js"></script>
<script src="regioncodefortesting.js"></script>
<script src="phonenumberutil.js"></script>
<script src="phonenumberutil_test.js"></script>
</head>
<body>
</body>
</html>


text:
namespace peloton {
namespace stats {

DatabaseMetric::DatabaseMetric(MetricType type, oid_t database_id)
    : AbstractMetric(type), database_id_(database_id) {}

void DatabaseMetric::Aggregate(AbstractMetric& source) {
  PL_ASSERT(source.GetType() == DATABASE_METRIC);

  DatabaseMetric& db_metric = static_cast<DatabaseMetric&>(source);
  txn_committed_.Aggregate(db_metric.GetTxnCommitted());
  txn_aborted_.Aggregate(db_metric.GetTxnAborted());
}

const std::string DatabaseMetric::GetInfo() const {
  std::stringstream ss;
  ss << "//"
        "===-----------------------------------------------------------------"
        "---===//" << std::endl;
  ss << "// DATABASE_ID " << database_id_ << std::endl;
  ss << "//"
        "===-----------------------------------------------------------------"
        "---===//" << std::endl;
  ss << "# transactions committed: " << txn_committed_.GetInfo() << std::endl;
  ss << "# transactions aborted:   " << txn_aborted_.GetInfo() << std::endl;
  return ss.str();
}

}  // namespace stats
}  // namespace peloton


text:
.class Landroid/support/v4/widget/TextViewCompat$JbTextViewCompatImpl;
.super Landroid/support/v4/widget/TextViewCompat$BaseTextViewCompatImpl;
.source "TextViewCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/widget/TextViewCompat;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "JbTextViewCompatImpl"
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 95
    invoke-direct {p0}, Landroid/support/v4/widget/TextViewCompat$BaseTextViewCompatImpl;-><init>()V

    return-void
.end method

# virtual methods
.method public getMaxLines(Landroid/widget/TextView;)I
    .locals 1
    .param p1, "textView"    # Landroid/widget/TextView;

    .prologue
    .line 98
    invoke-static {p1}, Landroid/support/v4/widget/TextViewCompatJb;->getMaxLines(Landroid/widget/TextView;)I

    move-result v0

    return v0
.end method

.method public getMinLines(Landroid/widget/TextView;)I
    .locals 1
    .param p1, "textView"    # Landroid/widget/TextView;

    .prologue
    .line 103
    invoke-static {p1}, Landroid/support/v4/widget/TextViewCompatJb;->getMinLines(Landroid/widget/TextView;)I

    move-result v0

    return v0
.end method


text:
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
import binascii

class AddressIndexTest(BitcoinTestFramework):

    def setup_chain(self):
        print("Initializing test directory "+self.options.tmpdir)
        initialize_chain_clean(self.options.tmpdir, 4)

    def setup_network(self):
        self.nodes = []
        # Nodes 0/1 are "wallet" nodes
        self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-relaypriority=0"]))
        self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-addressindex"]))
        # Nodes 2/3 are used for testing
        self.nodes.append(start_node(2, self.options.tmpdir, ["-debug", "-addressindex", "-relaypriority=0"]))
        self.nodes.append(start_node(3, self.options.tmpdir, ["-debug", "-addressindex"]))
        connect_nodes(self.nodes[0], 1)
        connect_nodes(self.nodes[0], 2)
        connect_nodes(self.nodes[0], 3)

        self.is_network_split = False
        self.sync_all()

    def run_test(self):
        print("Mining blocks...")
        self.nodes[0].generate(105)
        self.sync_all()

        chain_height = self.nodes[1].getblockcount()
        assert_equal(chain_height, 105)
        assert_equal(self.nodes[1].getbalance(), 0)
        assert_equal(self.nodes[2].getbalance(), 0)

        # Check that balances are correct
        balance0 = self.nodes[1].getaddressbalance("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br")
        assert_equal(balance0["balance"], 0)

        # Check p2pkh and p2sh address indexes
        print("Testing p2pkh and p2sh address index...")

        txid0 = self.nodes[0].sendtoaddress("mo9ncXisMeAoXwqcV5EWuyncbmCcQN4rVs", 10)
        self.nodes[0].generate(1)

        txidb0 = self.nodes[0].sendtoaddress("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br", 10)
        self.nodes[0].generate(1)

        txid1 = self.nodes[0].sendtoaddress("mo9ncXisMeAoXwqcV5EWuyncbmCcQN4rVs", 15)
        self.nodes[0].generate(1)

        txidb1 = self.nodes[0].sendtoaddress("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br", 15)
        self.nodes[0].generate(1)

        txid2 = self.nodes[0].sendtoaddress("mo9ncXisMeAoXwqcV5EWuyncbmCcQN4rVs", 20)
        self.nodes[0].generate(1)

        txidb2 = self.nodes[0].sendtoaddress("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br", 20)
        self.nodes[0].generate(1)

        self.sync_all()

        txids = self.nodes[1].getaddresstxids("mo9ncXisMeAoXwqcV5EWuyncbmCcQN4rVs")
        assert_equal(len(txids), 3)
        assert_equal(txids[0], txid0)
        assert_equal(txids[1], txid1)
        assert_equal(txids[2], txid2)

        txidsb = self.nodes[1].getaddresstxids("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br")
        assert_equal(len(txidsb), 3)
        assert_equal(txidsb[0], txidb0)
        assert_equal(txidsb[1], txidb1)
        assert_equal(txidsb[2], txidb2)

        # Check that limiting by height works
        print("Testing querying txids by range of block heights..")
        height_txids = self.nodes[1].getaddresstxids({
            "addresses": ["2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br"],
            "start": 105,
            "end": 110
        })
        assert_equal(len(height_txids), 2)
        assert_equal(height_txids[0], txidb0)
        assert_equal(height_txids[1], txidb1)

        # Check that multiple addresses works
        multitxids = self.nodes[1].getaddresstxids({"addresses": ["2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br", "mo9ncXisMeAoXwqcV5EWuyncbmCcQN4rVs"]})
        assert_equal(len(multitxids), 6)
        assert_equal(multitxids[0], txid0)
        assert_equal(multitxids[1], txidb0)
        assert_equal(multitxids[2], txid1)
        assert_equal(multitxids[3], txidb1)
        assert_equal(multitxids[4], txid2)
        assert_equal(multitxids[5], txidb2)

        # Check that balances are correct
        balance0 = self.nodes[1].getaddressbalance("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br")
        assert_equal(balance0["balance"], 45 * 100000000)

        # Check that outputs with the same address will only return one txid
        print("Testing for txid uniqueness...")
        addressHash = bytes([99,73,164,24,252,69,120,209,10,55,43,84,180,92,40,12,200,196,56,47])
        scriptPubKey = CScript([OP_HASH160, addressHash, OP_EQUAL])
        unspent = self.nodes[0].listunspent()
        tx = CTransaction()
        tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
        tx.vout = [CTxOut(10, scriptPubKey), CTxOut(11, scriptPubKey)]
        tx.rehash()

        signed_tx = self.nodes[0].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)

        self.nodes[0].generate(1)
        self.sync_all()

        txidsmany = self.nodes[1].getaddresstxids("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br")
        assert_equal(len(txidsmany), 4)
        assert_equal(txidsmany[3], sent_txid)

        # Check that balances are correct
        print("Testing balances...")
        balance0 = self.nodes[1].getaddressbalance("2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br")
        assert_equal(balance0["balance"], 45 * 100000000 + 21)

        # Check that balances are correct after spending
        print("Testing balances after spending...")
        privkey2 = "cSdkPxkAjA4HDr5VHgsebAPDEh9Gyub4HK8UJr2DFGGqKKy4K5sG"
        address2 = "mgY65WSfEmsyYaYPQaXhmXMeBhwp4EcsQW"
        addressHash2 = bytes([11,47,10,12,49,191,224,64,107,12,204,19,129,253,190,49,25,70,218,220])
        scriptPubKey2 = CScript([OP_DUP, OP_HASH160, addressHash2, OP_EQUALVERIFY, OP_CHECKSIG])
        self.nodes[0].importprivkey(privkey2)

        unspent = self.nodes[0].listunspent()
        tx = CTransaction()
        tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
        amount = int(unspent[0]["amount"] * 100000000 - 100000)
        tx.vout = [CTxOut(amount, scriptPubKey2)]
        tx.rehash()
        signed_tx = self.nodes[0].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        spending_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
        self.nodes[0].generate(1)
        self.sync_all()
        balance1 = self.nodes[1].getaddressbalance(address2)
        assert_equal(balance1["balance"], amount)

        tx = CTransaction()
        tx.vin = [CTxIn(COutPoint(int(spending_txid, 16), 0))]
        send_amount = 1 * 100000000 + 12840
        change_amount = amount - send_amount - 100000
        tx.vout = [CTxOut(change_amount, scriptPubKey2), CTxOut(send_amount, scriptPubKey)]
        tx.rehash()

        signed_tx = self.nodes[0].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        sent_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)
        self.nodes[0].generate(1)
        self.sync_all()

        balance2 = self.nodes[1].getaddressbalance(address2)
        assert_equal(balance2["balance"], change_amount)

        # Check that deltas are returned correctly
        deltas = self.nodes[1].getaddressdeltas({"addresses": [address2], "start": 1, "end": 200})
        balance3 = 0
        for delta in deltas:
            balance3 += delta["satoshis"]
        assert_equal(balance3, change_amount)
        assert_equal(deltas[0]["address"], address2)
        assert_equal(deltas[0]["blockindex"], 1)

        # Check that entire range will be queried
        deltasAll = self.nodes[1].getaddressdeltas({"addresses": [address2]})
        assert_equal(len(deltasAll), len(deltas))

        # Check that deltas can be returned from range of block heights
        deltas = self.nodes[1].getaddressdeltas({"addresses": [address2], "start": 113, "end": 113})
        assert_equal(len(deltas), 1)

        # Check that unspent outputs can be queried
        print("Testing utxos...")
        utxos = self.nodes[1].getaddressutxos({"addresses": [address2]})
        assert_equal(len(utxos), 1)
        assert_equal(utxos[0]["satoshis"], change_amount)

        # Check that indexes will be updated with a reorg
        print("Testing reorg...")

        best_hash = self.nodes[0].getbestblockhash()
        self.nodes[0].invalidateblock(best_hash)
        self.nodes[1].invalidateblock(best_hash)
        self.nodes[2].invalidateblock(best_hash)
        self.nodes[3].invalidateblock(best_hash)
        self.sync_all()

        balance4 = self.nodes[1].getaddressbalance(address2)
        assert_equal(balance4, balance1)

        utxos2 = self.nodes[1].getaddressutxos({"addresses": [address2]})
        assert_equal(len(utxos2), 1)
        assert_equal(utxos2[0]["satoshis"], amount)

        # Check sorting of utxos
        self.nodes[2].generate(150)

        txidsort1 = self.nodes[2].sendtoaddress(address2, 50)
        self.nodes[2].generate(1)
        txidsort2 = self.nodes[2].sendtoaddress(address2, 50)
        self.nodes[2].generate(1)
        self.sync_all()

        utxos3 = self.nodes[1].getaddressutxos({"addresses": [address2]})
        assert_equal(len(utxos3), 3)
        assert_equal(utxos3[0]["height"], 114)
        assert_equal(utxos3[1]["height"], 264)
        assert_equal(utxos3[2]["height"], 265)

        # Check mempool indexing
        print("Testing mempool indexing...")

        privKey3 = "cVfUn53hAbRrDEuMexyfgDpZPhF7KqXpS8UZevsyTDaugB7HZ3CD"
        address3 = "mw4ynwhS7MmrQ27hr82kgqu7zryNDK26JB"
        addressHash3 = bytes([170,152,114,181,187,205,181,17,216,158,14,17,170,39,218,115,253,44,63,80])
        scriptPubKey3 = CScript([OP_DUP, OP_HASH160, addressHash3, OP_EQUALVERIFY, OP_CHECKSIG])
        address4 = "2N8oFVB2vThAKury4vnLquW2zVjsYjjAkYQ"
        scriptPubKey4 = CScript([OP_HASH160, addressHash3, OP_EQUAL])
        unspent = self.nodes[2].listunspent()

        tx = CTransaction()
        tx.vin = [CTxIn(COutPoint(int(unspent[0]["txid"], 16), unspent[0]["vout"]))]
        amount = int(unspent[0]["amount"] * 100000000 - 100000)
        tx.vout = [CTxOut(amount, scriptPubKey3)]
        tx.rehash()
        signed_tx = self.nodes[2].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        memtxid1 = self.nodes[2].sendrawtransaction(signed_tx["hex"], True)
        time.sleep(2)

        tx2 = CTransaction()
        tx2.vin = [CTxIn(COutPoint(int(unspent[1]["txid"], 16), unspent[1]["vout"]))]
        amount = int(unspent[1]["amount"] * 100000000 - 100000)
        tx2.vout = [
            CTxOut(int(amount / 4), scriptPubKey3),
            CTxOut(int(amount / 4), scriptPubKey3),
            CTxOut(int(amount / 4), scriptPubKey4),
            CTxOut(int(amount / 4), scriptPubKey4)
        ]
        tx2.rehash()
        signed_tx2 = self.nodes[2].signrawtransaction(binascii.hexlify(tx2.serialize()).decode("utf-8"))
        memtxid2 = self.nodes[2].sendrawtransaction(signed_tx2["hex"], True)
        time.sleep(2)

        mempool = self.nodes[2].getaddressmempool({"addresses": [address3]})
        assert_equal(len(mempool), 3)
        assert_equal(mempool[0]["txid"], memtxid1)
        assert_equal(mempool[0]["address"], address3)
        assert_equal(mempool[0]["index"], 0)
        assert_equal(mempool[1]["txid"], memtxid2)
        assert_equal(mempool[1]["index"], 0)
        assert_equal(mempool[2]["txid"], memtxid2)
        assert_equal(mempool[2]["index"], 1)

        blk_hashes = self.nodes[2].generate(1);
        self.sync_all();
        mempool2 = self.nodes[2].getaddressmempool({"addresses": [address3]})
        assert_equal(len(mempool2), 0)

        tx = CTransaction()
        tx.vin = [
            CTxIn(COutPoint(int(memtxid2, 16), 0)),
            CTxIn(COutPoint(int(memtxid2, 16), 1))
        ]
        tx.vout = [CTxOut(int(amount / 2 - 100000), scriptPubKey2)]
        tx.rehash()
        self.nodes[2].importprivkey(privKey3)
        signed_tx3 = self.nodes[2].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        memtxid3 = self.nodes[2].sendrawtransaction(signed_tx3["hex"], True)
        time.sleep(2)

        mempool3 = self.nodes[2].getaddressmempool({"addresses": [address3]})
        assert_equal(len(mempool3), 2)
        assert_equal(mempool3[0]["prevtxid"], memtxid2)
        assert_equal(mempool3[0]["prevout"], 0)
        assert_equal(mempool3[1]["prevtxid"], memtxid2)
        assert_equal(mempool3[1]["prevout"], 1)

        # sending and receiving to the same address
        privkey1 = "cQY2s58LhzUCmEXN8jtAp1Etnijx78YRZ466w4ikX1V4UpTpbsf8"
        address1 = "myAUWSHnwsQrhuMWv4Br6QsCnpB41vFwHn"
        address1hash = bytes([193,146,191,247,81,175,142,254,193,81,53,212,43,254,237,249,26,111,62,52])
        address1script = CScript([OP_DUP, OP_HASH160, address1hash, OP_EQUALVERIFY, OP_CHECKSIG])

        self.nodes[0].sendtoaddress(address1, 10)
        self.nodes[0].generate(1)
        self.sync_all()

        utxos = self.nodes[1].getaddressutxos({"addresses": [address1]})
        assert_equal(len(utxos), 1)

        tx = CTransaction()
        tx.vin = [
            CTxIn(COutPoint(int(utxos[0]["txid"], 16), utxos[0]["outputIndex"]))
        ]
        amount = int(utxos[0]["satoshis"] - 100000)
        tx.vout = [CTxOut(amount, address1script)]
        tx.rehash()
        self.nodes[0].importprivkey(privkey1)
        signed_tx = self.nodes[0].signrawtransaction(binascii.hexlify(tx.serialize()).decode("utf-8"))
        mem_txid = self.nodes[0].sendrawtransaction(signed_tx["hex"], True)

        self.sync_all()
        mempool_deltas = self.nodes[2].getaddressmempool({"addresses": [address1]})
        assert_equal(len(mempool_deltas), 2)

        # Include chaininfo in results
        print("Testing results with chain info...")

        deltas_with_info = self.nodes[1].getaddressdeltas({
            "addresses": [address2],
            "start": 1,
            "end": 200,
            "chainInfo": True
        })
        start_block_hash = self.nodes[1].getblockhash(1);
        end_block_hash = self.nodes[1].getblockhash(200);
        assert_equal(deltas_with_info["start"]["height"], 1)
        assert_equal(deltas_with_info["start"]["hash"], start_block_hash)
        assert_equal(deltas_with_info["end"]["height"], 200)
        assert_equal(deltas_with_info["end"]["hash"], end_block_hash)

        utxos_with_info = self.nodes[1].getaddressutxos({"addresses": [address2], "chainInfo": True})
        expected_tip_block_hash = self.nodes[1].getblockhash(267);
        assert_equal(utxos_with_info["height"], 267)
        assert_equal(utxos_with_info["hash"], expected_tip_block_hash)

        print("Passed\n")

if __name__ == '__main__':
    AddressIndexTest().main()


text:
from __future__ import division, absolute_import

import os, sys, errno, warnings
try:
    import pwd, grp
except ImportError:
    pwd = grp = None
try:
    from os import setgroups, getgroups
except ImportError:
    setgroups = getgroups = None

from twisted.python.compat import _PY3, unicode
if _PY3:
    UserDict = object
else:
    from UserDict import UserDict

class InsensitiveDict:
    """Dictionary, that has case-insensitive keys.

    Normally keys are retained in their original form when queried with
    .keys() or .items().  If initialized with preserveCase=0, keys are both
    looked up in lowercase and returned in lowercase by .keys() and .items().
    """
    """
    Modified recipe at
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66315 originally
    contributed by Sami Hangaslammi.
    """

    def __init__(self, dict=None, preserve=1):
        """Create an empty dictionary, or update from 'dict'."""
        self.data = {}
        self.preserve=preserve
        if dict:
            self.update(dict)

    def __delitem__(self, key):
        k=self._lowerOrReturn(key)
        del self.data[k]

    def _lowerOrReturn(self, key):
        if isinstance(key, bytes) or isinstance(key, unicode):
            return key.lower()
        else:
            return key

    def __getitem__(self, key):
        """Retrieve the value associated with 'key' (in any case)."""
        k = self._lowerOrReturn(key)
        return self.data[k][1]

    def __setitem__(self, key, value):
        """Associate 'value' with 'key'. If 'key' already exists, but
        in different case, it will be replaced."""
        k = self._lowerOrReturn(key)
        self.data[k] = (key, value)

    def has_key(self, key):
        """Case insensitive test whether 'key' exists."""
        k = self._lowerOrReturn(key)
        return k in self.data

    __contains__=has_key

    def _doPreserve(self, key):
        if not self.preserve and (isinstance(key, bytes)
                                  or isinstance(key, unicode)):
            return key.lower()
        else:
            return key

    def keys(self):
        """List of keys in their original case."""
        return list(self.iterkeys())

    def values(self):
        """List of values."""
        return list(self.itervalues())

    def items(self):
        """List of (key,value) pairs."""
        return list(self.iteritems())

    def get(self, key, default=None):
        """Retrieve value associated with 'key' or return default value
        if 'key' doesn't exist."""
        try:
            return self[key]
        except KeyError:
            return default

    def setdefault(self, key, default):
        """If 'key' doesn't exists, associate it with the 'default' value.
        Return value associated with 'key'."""
        if not self.has_key(key):
            self[key] = default
        return self[key]

    def update(self, dict):
        """Copy (key,value) pairs from 'dict'."""
        for k,v in dict.items():
            self[k] = v

    def __repr__(self):
        """String representation of the dictionary."""
        items = ", ".join([("%r: %r" % (k,v)) for k,v in self.items()])
        return "InsensitiveDict({%s})" % items

    def iterkeys(self):
        for v in self.data.values():
            yield self._doPreserve(v[0])

    def itervalues(self):
        for v in self.data.values():
            yield v[1]

    def iteritems(self):
        for (k, v) in self.data.values():
            yield self._doPreserve(k), v

    def popitem(self):
        i=self.items()[0]
        del self[i[0]]
        return i

    def clear(self):
        for k in self.keys():
            del self[k]

    def copy(self):
        return InsensitiveDict(self, self.preserve)

    def __len__(self):
        return len(self.data)

    def __eq__(self, other):
        for k,v in self.items():
            if not (k in other) or not (other[k]==v):
                return 0
        return len(self)==len(other)

class OrderedDict(UserDict):
    """A UserDict that preserves insert order whenever possible."""
    def __init__(self, dict=None, **kwargs):
        self._order = []
        self.data = {}
        if dict is not None:
            if hasattr(dict,'keys'):
                self.update(dict)
            else:
                for k,v in dict: # sequence
                    self[k] = v
        if len(kwargs):
            self.update(kwargs)
    def __repr__(self):
        return '{'+', '.join([('%r: %r' % item) for item in self.items()])+'}'

    def __setitem__(self, key, value):
        if not self.has_key(key):
            self._order.append(key)
        UserDict.__setitem__(self, key, value)

    def copy(self):
        return self.__class__(self)

    def __delitem__(self, key):
        UserDict.__delitem__(self, key)
        self._order.remove(key)

    def iteritems(self):
        for item in self._order:
            yield (item, self[item])

    def items(self):
        return list(self.iteritems())

    def itervalues(self):
        for item in self._order:
            yield self[item]

    def values(self):
        return list(self.itervalues())

    def iterkeys(self):
        return iter(self._order)

    def keys(self):
        return list(self._order)

    def popitem(self):
        key = self._order[-1]
        value = self[key]
        del self[key]
        return (key, value)

    def setdefault(self, item, default):
        if self.has_key(item):
            return self[item]
        self[item] = default
        return default

    def update(self, d):
        for k, v in d.items():
            self[k] = v

def uniquify(lst):
    """Make the elements of a list unique by inserting them into a dictionary.
    This must not change the order of the input lst.
    """
    dct = {}
    result = []
    for k in lst:
        if k not in dct:
            result.append(k)
        dct[k] = 1
    return result

def padTo(n, seq, default=None):
    """
    Pads a sequence out to n elements,

    filling in with a default value if it is not long enough.

    If the input sequence is longer than n, raises ValueError.

    Details, details:
    This returns a new list; it does not extend the original sequence.
    The new list contains the values of the original sequence, not copies.
    """

    if len(seq) > n:
        raise ValueError("%d elements is more than %d." % (len(seq), n))

    blank = [default] * n

    blank[:len(seq)] = list(seq)

    return blank

def getPluginDirs():
    warnings.warn(
        "twisted.python.util.getPluginDirs is deprecated since Twisted 12.2.",
        DeprecationWarning, stacklevel=2)
    import twisted
    systemPlugins = os.path.join(os.path.dirname(os.path.dirname(
                            os.path.abspath(twisted.__file__))), 'plugins')
    userPlugins = os.path.expanduser("~/TwistedPlugins")
    confPlugins = os.path.expanduser("~/.twisted")
    allPlugins = filter(os.path.isdir, [systemPlugins, userPlugins, confPlugins])
    return allPlugins

def addPluginDir():
    warnings.warn(
        "twisted.python.util.addPluginDir is deprecated since Twisted 12.2.",
        DeprecationWarning, stacklevel=2)
    sys.path.extend(getPluginDirs())

def sibpath(path, sibling):
    """
    Return the path to a sibling of a file in the filesystem.

    This is useful in conjunction with the special C{__file__} attribute
    that Python provides for modules, so modules can load associated
    resource files.
    """
    return os.path.join(os.path.dirname(os.path.abspath(path)), sibling)

def _getpass(prompt):
    """
    Helper to turn IOErrors into KeyboardInterrupts.
    """
    import getpass
    try:
        return getpass.getpass(prompt)
    except IOError as e:
        if e.errno == errno.EINTR:
            raise KeyboardInterrupt
        raise
    except EOFError:
        raise KeyboardInterrupt

def getPassword(prompt = 'Password: ', confirm = 0, forceTTY = 0,
                confirmPrompt = 'Confirm password: ',
                mismatchMessage = "Passwords don't match."):
    """Obtain a password by prompting or from stdin.

    If stdin is a terminal, prompt for a new password, and confirm (if
    C{confirm} is true) by asking again to make sure the user typed the same
    thing, as keystrokes will not be echoed.

    If stdin is not a terminal, and C{forceTTY} is not true, read in a line
    and use it as the password, less the trailing newline, if any.  If
    C{forceTTY} is true, attempt to open a tty and prompt for the password
    using it.  Raise a RuntimeError if this is not possible.

    @returns: C{str}
    """
    isaTTY = hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()

    old = None
    try:
        if not isaTTY:
            if forceTTY:
                try:
                    old = sys.stdin, sys.stdout
                    sys.stdin = sys.stdout = open('/dev/tty', 'r+')
                except:
                    raise RuntimeError("Cannot obtain a TTY")
            else:
                password = sys.stdin.readline()
                if password[-1] == '\n':
                    password = password[:-1]
                return password

        while 1:
            try1 = _getpass(prompt)
            if not confirm:
                return try1
            try2 = _getpass(confirmPrompt)
            if try1 == try2:
                return try1
            else:
                sys.stderr.write(mismatchMessage + "\n")
    finally:
        if old:
            sys.stdin.close()
            sys.stdin, sys.stdout = old

def println(*a):
    sys.stdout.write(' '.join(map(str, a))+'\n')

# XXX
# This does not belong here
# But where does it belong?

def str_xor(s, b):
    return ''.join([chr(ord(c) ^ b) for c in s])

def makeStatBar(width, maxPosition, doneChar = '=', undoneChar = '-', currentChar = '>'):
    """
    Creates a function that will return a string representing a progress bar.
    """
    aValue = width / float(maxPosition)
    def statBar(position, force = 0, last = ['']):
        assert len(last) == 1, "Don't mess with the last parameter."
        done = int(aValue * position)
        toDo = width - done - 2
        result = "[%s%s%s]" % (doneChar * done, currentChar, undoneChar * toDo)
        if force:
            last[0] = result
            return result
        if result == last[0]:
            return ''
        last[0] = result
        return result

    statBar.__doc__ = """statBar(position, force = 0) -> '[%s%s%s]'-style progress bar

    returned string is %d characters long, and the range goes from 0..%d.
    The 'position' argument is where the '%s' will be drawn.  If force is false,
    '' will be returned instead if the resulting progress bar is identical to the
    previously returned progress bar.
""" % (doneChar * 3, currentChar, undoneChar * 3, width, maxPosition, currentChar)
    return statBar

def spewer(frame, s, ignored):
    """
    A trace function for sys.settrace that prints every function or method call.
    """
    from twisted.python import reflect
    if frame.f_locals.has_key('self'):
        se = frame.f_locals['self']
        if hasattr(se, '__class__'):
            k = reflect.qual(se.__class__)
        else:
            k = reflect.qual(type(se))
        print('method %s of %s at %s' % (
                frame.f_code.co_name, k, id(se)))
    else:
        print('function %s in %s, line %s' % (
                frame.f_code.co_name,
                frame.f_code.co_filename,
                frame.f_lineno))

def searchupwards(start, files=[], dirs=[]):
    """
    Walk upwards from start, looking for a directory containing
    all files and directories given as arguments::
    >>> searchupwards('.', ['foo.txt'], ['bar', 'bam'])

    If not found, return None
    """
    start=os.path.abspath(start)
    parents=start.split(os.sep)
    exists=os.path.exists; join=os.sep.join; isdir=os.path.isdir
    while len(parents):
        candidate=join(parents)+os.sep
        allpresent=1
        for f in files:
            if not exists("%s%s" % (candidate, f)):
                allpresent=0
                break
        if allpresent:
            for d in dirs:
                if not isdir("%s%s" % (candidate, d)):
                    allpresent=0
                    break
        if allpresent: return candidate
        parents.pop(-1)
    return None

class LineLog:
    """
    A limited-size line-based log, useful for logging line-based
    protocols such as SMTP.

    When the log fills up, old entries drop off the end.
    """
    def __init__(self, size=10):
        """
        Create a new log, with size lines of storage (default 10).
        A log size of 0 (or less) means an infinite log.
        """
        if size < 0:
            size = 0
        self.log = [None]*size
        self.size = size

    def append(self,line):
        if self.size:
            self.log[:-1] = self.log[1:]
            self.log[-1] = line
        else:
            self.log.append(line)

    def str(self):
        return '\n'.join(filter(None,self.log))

    def __getitem__(self, item):
        return filter(None,self.log)[item]

    def clear(self):
        """Empty the log"""
        self.log = [None]*self.size

def raises(exception, f, *args, **kwargs):
    """
    Determine whether the given call raises the given exception.
    """
    try:
        f(*args, **kwargs)
    except exception:
        return 1
    return 0

class IntervalDifferential:
    """
    Given a list of intervals, generate the amount of time to sleep between
    "instants".

    For example, given 7, 11 and 13, the three (infinite) sequences::

        7 14 21 28 35 ...
        11 22 33 44 ...
        13 26 39 52 ...

    will be generated, merged, and used to produce::

        (7, 0) (4, 1) (2, 2) (1, 0) (7, 0) (1, 1) (4, 2) (2, 0) (5, 1) (2, 0)

    New intervals may be added or removed as iteration proceeds using the
    proper methods.
    """

    def __init__(self, intervals, default=60):
        """
        @type intervals: C{list} of C{int}, C{long}, or C{float} param
        @param intervals: The intervals between instants.

        @type default: C{int}, C{long}, or C{float}
        @param default: The duration to generate if the intervals list
        becomes empty.
        """
        self.intervals = intervals[:]
        self.default = default

    def __iter__(self):
        return _IntervalDifferentialIterator(self.intervals, self.default)

class _IntervalDifferentialIterator:
    def __init__(self, i, d):

        self.intervals = [[e, e, n] for (e, n) in zip(i, range(len(i)))]
        self.default = d
        self.last = 0

    def next(self):
        if not self.intervals:
            return (self.default, None)
        last, index = self.intervals[0][0], self.intervals[0][2]
        self.intervals[0][0] += self.intervals[0][1]
        self.intervals.sort()
        result = last - self.last
        self.last = last
        return result, index

    def addInterval(self, i):
        if self.intervals:
            delay = self.intervals[0][0] - self.intervals[0][1]
            self.intervals.append([delay + i, i, len(self.intervals)])
            self.intervals.sort()
        else:
            self.intervals.append([i, i, 0])

    def removeInterval(self, interval):
        for i in range(len(self.intervals)):
            if self.intervals[i][1] == interval:
                index = self.intervals[i][2]
                del self.intervals[i]
                for i in self.intervals:
                    if i[2] > index:
                        i[2] -= 1
                return
        raise ValueError("Specified interval not in IntervalDifferential")

class FancyStrMixin:
    """
    Mixin providing a flexible implementation of C{__str__}.

    C{__str__} output will begin with the name of the class, or the contents
    of the attribute C{fancybasename} if it is set.

    The body of C{__str__} can be controlled by overriding C{showAttributes} in
    a subclass.  Set C{showAttributes} to a sequence of strings naming
    attributes, or sequences of C{(attributeName, callable)}, or sequences of
    C{(attributeName, displayName, formatCharacter)}. In the second case, the
    callable is passed the value of the attribute and its return value used in
    the output of C{__str__}.  In the final case, the attribute is looked up
    using C{attributeName}, but the output uses C{displayName} instead, and
    renders the value of the attribute using C{formatCharacter}, e.g. C{"%.3f"}
    might be used for a float.
    """
    # Override in subclasses:
    showAttributes = ()

    def __str__(self):
        r = ['<', (hasattr(self, 'fancybasename') and self.fancybasename)
             or self.__class__.__name__]
        for attr in self.showAttributes:
            if isinstance(attr, str):
                r.append(' %s=%r' % (attr, getattr(self, attr)))
            elif len(attr) == 2:
                r.append((' %s=' % (attr[0],)) + attr[1](getattr(self, attr[0])))
            else:
                r.append((' %s=' + attr[2]) % (attr[1], getattr(self, attr[0])))
        r.append('>')
        return ''.join(r)

    __repr__ = __str__

class FancyEqMixin:
    """
    Mixin that implements C{__eq__} and C{__ne__}.

    Comparison is done using the list of attributes defined in
    C{compareAttributes}.
    """
    compareAttributes = ()

    def __eq__(self, other):
        if not self.compareAttributes:
            return self is other
        if isinstance(self, other.__class__):
            return (
                [getattr(self, name) for name in self.compareAttributes] ==
                [getattr(other, name) for name in self.compareAttributes])
        return NotImplemented

    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

try:
    # Python 2.7 / Python 3.3
    from os import initgroups as _c_initgroups
except ImportError:
    try:
        # Python 2.6
        from twisted.python._initgroups import initgroups as _c_initgroups
    except ImportError:
        _c_initgroups = None

if pwd is None or grp is None or setgroups is None or getgroups is None:
    def initgroups(uid, primaryGid):
        """
        Do nothing.

        Underlying platform support require to manipulate groups is missing.
        """
else:
    # Fallback to the inefficient Python version
    def _setgroups_until_success(l):
        while(1):
            # NASTY NASTY HACK (but glibc does it so it must be okay):
            # In case sysconfig didn't give the right answer, find the limit
            # on max groups by just looping, trying to set fewer and fewer
            # groups each time until it succeeds.
            try:
                setgroups(l)
            except ValueError:
                # This exception comes from python itself restricting
                # number of groups allowed.
                if len(l) > 1:
                    del l[-1]
                else:
                    raise
            except OSError as e:
                if e.errno == errno.EINVAL and len(l) > 1:
                    # This comes from the OS saying too many groups
                    del l[-1]
                else:
                    raise
            else:
                # Success, yay!
                return

    def initgroups(uid, primaryGid):
        """
        Initializes the group access list.

        If the C extension is present, we're calling it, which in turn calls
        initgroups(3).

        If not, this is done by reading the group database /etc/group and using
        all groups of which C{uid} is a member.  The additional group
        C{primaryGid} is also added to the list.

        If the given user is a member of more than C{NGROUPS}, arbitrary
        groups will be silently discarded to bring the number below that
        limit.

        @type uid: C{int}
        @param uid: The UID for which to look up group information.

        @type primaryGid: C{int} or C{NoneType}
        @param primaryGid: If provided, an additional GID to include when
            setting the groups.
        """
        if _c_initgroups is not None:
            return _c_initgroups(pwd.getpwuid(uid)[0], primaryGid)
        try:
            # Try to get the maximum number of groups
            max_groups = os.sysconf("SC_NGROUPS_MAX")
        except:
            # No predefined limit
            max_groups = 0

        username = pwd.getpwuid(uid)[0]
        l = []
        if primaryGid is not None:
            l.append(primaryGid)
        for groupname, password, gid, userlist in grp.getgrall():
            if username in userlist:
                l.append(gid)
                if len(l) == max_groups:
                    break # No more groups, ignore any more
        try:
            _setgroups_until_success(l)
        except OSError as e:
            # We might be able to remove this code now that we
            # don't try to setgid/setuid even when not asked to.
            if e.errno == errno.EPERM:
                for g in getgroups():
                    if g not in l:
                        raise
            else:
                raise

def switchUID(uid, gid, euid=False):
    """
    Attempts to switch the uid/euid and gid/egid for the current process.

    If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
    this function will issue a L{UserWarning} and not raise an exception.

    @type uid: C{int} or C{NoneType}
    @param uid: the UID (or EUID) to switch the current process to. This
                parameter will be ignored if the value is C{None}.

    @type gid: C{int} or C{NoneType}
    @param gid: the GID (or EGID) to switch the current process to. This
                parameter will be ignored if the value is C{None}.

    @type euid: C{bool}
    @param euid: if True, set only effective user-id rather than real user-id.
                 (This option has no effect unless the process is running
                 as root, in which case it means not to shed all
                 privileges, retaining the option to regain privileges
                 in cases such as spawning processes. Use with caution.)
    """
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
        getuid = os.geteuid
    else:
        setuid = os.setuid
        setgid = os.setgid
        getuid = os.getuid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        if uid == getuid():
            uidText = (euid and "euid" or "uid")
            actionText = "tried to drop privileges and set%s %s" % (uidText, uid)
            problemText = "%s is already %s" % (uidText, getuid())
            warnings.warn("%s but %s; should we be root? Continuing."
                          % (actionText, problemText))
        else:
            initgroups(uid, gid)
            setuid(uid)

class SubclassableCStringIO(object):
    """
    A wrapper around cStringIO to allow for subclassing.
    """
    __csio = None

    def __init__(self, *a, **kw):
        from cStringIO import StringIO
        self.__csio = StringIO(*a, **kw)

    def __iter__(self):
        return self.__csio.__iter__()

    def next(self):
        return self.__csio.next()

    def close(self):
        return self.__csio.close()

    def isatty(self):
        return self.__csio.isatty()

    def seek(self, pos, mode=0):
        return self.__csio.seek(pos, mode)

    def tell(self):
        return self.__csio.tell()

    def read(self, n=-1):
        return self.__csio.read(n)

    def readline(self, length=None):
        return self.__csio.readline(length)

    def readlines(self, sizehint=0):
        return self.__csio.readlines(sizehint)

    def truncate(self, size=None):
        return self.__csio.truncate(size)

    def write(self, s):
        return self.__csio.write(s)

    def writelines(self, list):
        return self.__csio.writelines(list)

    def flush(self):
        return self.__csio.flush()

    def getvalue(self):
        return self.__csio.getvalue()

def untilConcludes(f, *a, **kw):
    """
    Call C{f} with the given arguments, handling C{EINTR} by retrying.

    @param f: A function to call.

    @param *a: Positional arguments to pass to C{f}.

    @param **kw: Keyword arguments to pass to C{f}.

    @return: Whatever C{f} returns.

    @raise: Whatever C{f} raises, except for C{IOError} or C{OSError} with
        C{errno} set to C{EINTR}.
    """
    while True:
        try:
            return f(*a, **kw)
        except (IOError, OSError) as e:
            if e.args[0] == errno.EINTR:
                continue
            raise

def mergeFunctionMetadata(f, g):
    """
    Overwrite C{g}'s name and docstring with values from C{f}.  Update
    C{g}'s instance dictionary with C{f}'s.

    @return: A function that has C{g}'s behavior and metadata merged from
        C{f}.
    """
    try:
        g.__name__ = f.__name__
    except TypeError:
        pass
    try:
        g.__doc__ = f.__doc__
    except (TypeError, AttributeError):
        pass
    try:
        g.__dict__.update(f.__dict__)
    except (TypeError, AttributeError):
        pass
    try:
        g.__module__ = f.__module__
    except TypeError:
        pass
    return g

def nameToLabel(mname):
    """
    Convert a string like a variable name into a slightly more human-friendly
    string with spaces and capitalized letters.

    @type mname: C{str}
    @param mname: The name to convert to a label.  This must be a string
    which could be used as a Python identifier.  Strings which do not take
    this form will result in unpredictable behavior.

    @rtype: C{str}
    """
    labelList = []
    word = ''
    lastWasUpper = False
    for letter in mname:
        if letter.isupper() == lastWasUpper:
            # Continuing a word.
            word += letter
        else:
            # breaking a word OR beginning a word
            if lastWasUpper:
                # could be either
                if len(word) == 1:
                    # keep going
                    word += letter
                else:
                    # acronym
                    # we're processing the lowercase letter after the acronym-then-capital
                    lastWord = word[:-1]
                    firstLetter = word[-1]
                    labelList.append(lastWord)
                    word = firstLetter + letter
            else:
                # definitely breaking: lower to upper
                labelList.append(word)
                word = letter
        lastWasUpper = letter.isupper()
    if labelList:
        labelList[0] = labelList[0].capitalize()
    else:
        return mname.capitalize()
    labelList.append(word)
    return ' '.join(labelList)

def uidFromString(uidString):
    """
    Convert a user identifier, as a string, into an integer UID.

    @type uid: C{str}
    @param uid: A string giving the base-ten representation of a UID or the
        name of a user which can be converted to a UID via L{pwd.getpwnam}.

    @rtype: C{int}
    @return: The integer UID corresponding to the given string.

    @raise ValueError: If the user name is supplied and L{pwd} is not
        available.
    """
    try:
        return int(uidString)
    except ValueError:
        if pwd is None:
            raise
        return pwd.getpwnam(uidString)[2]

def gidFromString(gidString):
    """
    Convert a group identifier, as a string, into an integer GID.

    @type uid: C{str}
    @param uid: A string giving the base-ten representation of a GID or the
        name of a group which can be converted to a GID via L{grp.getgrnam}.

    @rtype: C{int}
    @return: The integer GID corresponding to the given string.

    @raise ValueError: If the group name is supplied and L{grp} is not
        available.
    """
    try:
        return int(gidString)
    except ValueError:
        if grp is None:
            raise
        return grp.getgrnam(gidString)[2]

def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
    """
    Run the given function wrapped with seteuid/setegid calls.

    This will try to minimize the number of seteuid/setegid calls, comparing
    current and wanted permissions

    @param euid: effective UID used to call the function.
    @type euid: C{int}

    @type egid: effective GID used to call the function.
    @param egid: C{int}

    @param function: the function run with the specific permission.
    @type function: any callable

    @param *args: arguments passed to C{function}
    @param **kwargs: keyword arguments passed to C{function}
    """
    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return function(*args, **kwargs)
    else:
        if uid != 0 and (uid != euid or gid != egid):
            os.seteuid(0)
        if gid != egid:
            os.setegid(egid)
        if euid != 0 and (euid != uid or gid != egid):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if euid != 0 and (uid != euid or gid != egid):
                os.seteuid(0)
            if gid != egid:
                os.setegid(gid)
            if uid != 0 and (uid != euid or gid != egid):
                os.seteuid(uid)

def runWithWarningsSuppressed(suppressedWarnings, f, *args, **kwargs):
    """
    Run C{f(*args, **kwargs)}, but with some warnings suppressed.

    Unlike L{twisted.internet.utils.runWithWarningsSuppressed}, it has no
    special support for L{twisted.internet.defer.Deferred}.

    @param suppressedWarnings: A list of arguments to pass to filterwarnings.
        Must be a sequence of 2-tuples (args, kwargs).

    @param f: A callable.

    @param args: Arguments for C{f}.

    @param kwargs: Keyword arguments for C{f}

    @return: The result of C{f(*args, **kwargs)}.
    """
    with warnings.catch_warnings():
        for a, kw in suppressedWarnings:
            warnings.filterwarnings(*a, **kw)
        return f(*args, **kwargs)

__all__ = [
    "uniquify", "padTo", "getPluginDirs", "addPluginDir", "sibpath",
    "getPassword", "println", "makeStatBar", "OrderedDict",
    "InsensitiveDict", "spewer", "searchupwards", "LineLog",
    "raises", "IntervalDifferential", "FancyStrMixin", "FancyEqMixin",
    "switchUID", "SubclassableCStringIO", "mergeFunctionMetadata",
    "nameToLabel", "uidFromString", "gidFromString", "runAsEffectiveUser",
    "untilConcludes",
    "runWithWarningsSuppressed",
    ]

if _PY3:
    __all3__ = ["FancyEqMixin", "untilConcludes",
                "runWithWarningsSuppressed", "FancyStrMixin", "nameToLabel",
                "InsensitiveDict"]
    for name in __all__[:]:
        if name not in __all3__:
            __all__.remove(name)
            del globals()[name]
    del name, __all3__


text:
/*
 * @(#)FlagTerm.java	1.12 05/08/29
 *
 * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
 */

package javax.mail.search;

import javax.mail.*;

/**
 * This class implements comparisons for Message Flags.
 *
 * @author Bill Shannon
 * @author John Mani
 */
public final class FlagTerm extends SearchTerm {

    /**
     * Indicates whether to test for the presence or
     * absence of the specified Flag. If true,
     * then test whether all the specified flags are present, else
     * test whether all the specified flags are absent.
     *
     * @serial
     */
    protected boolean set;

    /**
     * Flags object containing the flags to test.
     *
     * @serial
     */
    protected Flags flags;

    private static final long serialVersionUID = -142991500302030647L;

    /**
     * Constructor.
     *
     * @param flags	Flags object containing the flags to check for
     * @param set	the flag setting to check for
     */
    public FlagTerm(Flags flags, boolean set) {
	this.flags = flags;
	this.set = set;
    }

    /**
     * Return the Flags to test.
     */
    public Flags getFlags() {
	return (Flags)flags.clone();
    }

    /**
     * Return true if testing whether the flags are set.
     */
    public boolean getTestSet() {
	return set;
    }

    /**
     * The comparison method.
     *
     * @param msg	The flag comparison is applied to this Message
     * @return		true if the comparson succeeds, otherwise false.
     */
    public boolean match(Message msg) {

	try {
	    Flags f = msg.getFlags();
	    if (set) { // This is easy
		if (f.contains(flags))
		    return true;
		else
		    return false;
	    }

	    // Return true if ALL flags in the passed in Flags
	    // object are NOT set in this Message.

	    // Got to do this the hard way ...
	    Flags.Flag[] sf = flags.getSystemFlags();

	    // Check each flag in the passed in Flags object
	    for (int i = 0; i < sf.length; i++) {
		if (f.contains(sf[i]))
		    // this flag IS set in this Message, get out.
		    return false;
	    }

	    String[] s = flags.getUserFlags();

	    // Check each flag in the passed in Flags object
	    for (int i = 0; i < s.length; i++) {
		if (f.contains(s[i]))
		    // this flag IS set in this Message, get out.
		    return false;
	    }

	    return true;

	} catch (Exception e) {
	    return false;
	}
    }

    /**
     * Equality comparison.
     */
    public boolean equals(Object obj) {
	if (!(obj instanceof FlagTerm))
	    return false;
	FlagTerm ft = (FlagTerm)obj;
	return ft.set == this.set && ft.flags.equals(this.flags);
    }

    /**
     * Compute a hashCode for this object.
     */
    public int hashCode() {
	return set ? flags.hashCode() : ~flags.hashCode();
    }
}