text:
<TITLE>man page(1) manual page</TITLE>

Table of Contents

_________________________________________________________________

Name

table - Create and manipulate tables

Synopsis

table pathName ?options?

Standard Options

-anchor

        -background    -cursor

-exportselection

              -font           -foreground

-highlightbackground

          -highlightcolor -highlightthickness

-insertbackground

             -insertborderwidth-insertofftime
-insertontime -insertwidth -invertselected -padx

-pady

          -relief        -takefocus      -xscrollcommand
-yscrollcommand

See the options manual entry for details on the standard
options.

Widget-specific Options

Command-Line Name:-autoclear

Database Name: autoClear

Database Class: AutoClear

A boolean value which specifies whether the first
keypress in a cell will delete whatever text was previously
there. Defaults to 0.

Command-Line Name:-bordercursor

Database Name: borderCursor

Database Class: Cursor

Specifies the name of the cursor to show when over
borders, a visual indication that interactive resizing
is allowed (it is thus affect by the value of
-resizeborders). Defaults to crosshair.

Command-Line Name:-borderwidth or -bd

Database Name: borderWidth

Database Class: BorderWidth

Specifies a non-negative value indicating the width of
the 3-D border to draw on interior table cells (if such
a border is being drawn; the relief option typically
determines this). This can be overridden by the a
tag's borderwidth option. It can also be affected by
the defined -drawmode for the table. The value may
have any of the forms acceptable to Tk_GetPixels.

Command-Line Name:-browsecommand or -browsecmd
Database Name: browseCommand

Database Class: BrowseCommand

Specifies a command which will be evaluated anytime the
active cell changes. It uses the %-substition model
described in COMMAND SUBSTITUTION below.

Command-Line Name:-cache

Database Name: cache

Database Class: Cache

A boolean value that specifies whether an internal
cache of the table contents should be kept. This
greatly enhances speed performance when used with -command
but uses extra memory. Can maintain state when
both -command and -variable are empty. The cache is
automatically flushed whenever the value of -cache or
-variable changes, otherwise you have to explicitly
flush it. Defaults to false.

Command-Line Name:-colorigin

Database Name: colOrigin

Database Class: Origin

Specifies what column index to interpret as the leftmost
column in the table. This value is used for user
indices in the table. Defaults to 0.

Command-Line Name:-cols

Database Name: cols

Database Class: Cols

Number of cols in the table. Defaults to 10.

Command-Line Name:-colseparator

Database Name: colSeparator

Database Class: Separator

Specifies a separator character that will be interpreted
as the column separator when cutting or pasting
data in a table. By default, columns are separated as
elements of a tcl list.

Command-Line Name:-colstretchmode

Database Name: colStretchMode

Database Class: StretchMode

Specifies one of the following stretch modes for
columns to fill extra allocated window space:

none Columns will not stretch to fill the assigned

window space. If the columns are too narrow,
there will be a blank space at the right of the
table. This is the default.

unset

Only columns that do not have a specific width set
will be stretched.

all All columns will be stretched by the same number
of pixels to fill the window space allocated to
the table. This mode can interfere with interactive
border resizing which tries to force column
width.

last The last column will be stretched to fill the window
space allocated to the table.

fill (only valid for -rowstretch currently)
The table will get more or less columns according
to the window space allocated to the table. This
mode has numerous quirks and may disappear in the
future.

Command-Line Name:-coltagcommand

Database Name: colTagCommand

Database Class: TagCommand

Provides the name of a procedure that will be evaluated
by the widget to determine the tag to be used for a
given column. When displaying a cell, the table widget
will first check to see if a tag has been defined using
the tag col widget method. If no tag is found, it will
evaluate the named procedure passing the column number
in question as the sole argument. The procedure is
expected to return the name of a tag to use, or a null
string. Errors occuring during the evaluation of the
procedure, or the return of an invalid tag name are
silently ignored.

Command-Line Name:-colwidth

Database Name: colWidth

Database Class: ColWidth

Default column width, interpreted as characters in the
default font when the number is positive, or pixels if
it is negative. Defaults to 10.

Command-Line Name:-command

Database Name: command

Database Class: Command

Specified a command to use as a procedural interface to
cell values. If -usecommand is true, this command will
be used instead of any reference to the -variable
array. When retrieving cell values, the return value
of the command is used as the value for the cell. It
uses the %-substition model described in COMMAND SUBSTITUTION
below.

Command-Line Name:-drawmode

Database Name: drawMode

Database Class: DrawMode

Sets the table drawing mode to one of the following
options:

slow The table is drawn to an offscreen pixmap using
the Tk bordering functions (double-buffering).
This means there will be no flashing, but this
mode is slow for larger tables.

compatible

The table is drawn directly to the screen using
the Tk border functions. It is faster, but the
screen may flash on update. This is the default.

fast The table is drawn directly to the screen and the
borders are done with fast X calls, so they are
always one pixel wide only. As a side effect, it
restricts -borderwidth to a range of 0 or 1. This
mode provides best performance for large tables,
but can flash on redraw and is not 100% Tk compatible
on the border mode.

single

The table is drawn to the screen as in fast mode,
but only single pixel lines are drawn (not square
borders).

Command-Line Name:-flashmode

Database Name: flashMode

Database Class: FlashMode

A boolean value which specifies whether cells should
flash when their value changes. The table tag flash
will be applied to these cells for the duration specified
by -flashtime. Defaults to 0.

Command-Line Name:-flashtime

Database Name: flashTime

Database Class: FlashTime

The amount of time, in 1/4 second increments, for which
a cell should flash when its value has changed.
-flashmode must be on. Defaults to 2.

Command-Line Name:-height

Database Name: height

Database Class: Height

Specifies the desired height for the window, in rows.
If zero or less, then the desired height for the window
is made just large enough to hold all the rows in the
table. The height can be further limited by -maxheight.

Command-Line Name:-invertselected

Database Name: invertSelected

Database Class: InvertSelected

Specifies whether the foreground and background of an
item should simply have their values swapped instead of
merging the sel tag options when the cell is selected.
Defaults to 0 (merge).

Command-Line Name:-maxheight

Database Name: maxHeight

Database Class: MaxHeight

The max height in pixels that the window will request.
Defaults to 600.

Command-Line Name:-maxwidth

Database Name: maxWidth

Database Class: MaxWidth

The max width in pixels that the window will request.
Defaults to 800.

Command-Line Name:-multiline

Database Name: multiline

Database Class: Multiline

Specifies the default setting for the multiline tag
option. Defaults to 1.

Command-Line Name:-resizeborders

Database Name: resizeBorders

Database Class: ResizeBorders

Specifies what kind of interactive border resizing to
allow, must be one of row, col, both (default) or none.

Command-Line Name:-rowheight

Database Name: rowHeight

Database Class: RowHeight

Default row height, interpreted as lines in the default
font when the number is positive, or pixels if it is
negative. Defaults to 1.

Command-Line Name:-roworigin

Database Name: rowOrigin

Database Class: Origin

Specifies what row index to interpret as the topmost
row in the table. This value is used for user indices
in the table. Defaults to 0.

Command-Line Name:-rows

Database Name: rows

Database Class: Rows

Number of rows in the table. Defaults to 10.

Command-Line Name:-rowseparator

Database Name: rowSeparator

Database Class: Separator

Specifies a separator character that will be interpreted
as the row separator when cutting or pasting
data in a table. By default, rows are separated as tcl
lists.

Command-Line Name:-rowstretchmode

Database Name: rowStretchMode

Database Class: StretchMode

Specifies the stretch modes for rows to fill extra
allocated window space. See -colstretchmode for valid
options.

Command-Line Name:-rowtagcommand

Database Name: rowTagCommand

Database Class: TagCommand

Provides the name of a procedure that can evaluated by
the widget to determine the tag to be used for a given
row. The procedure must be defined by the user to
accept a single argument (the row number), and return a
tag name or null string. This operates in a similar
manner as -coltagcommand, except that it applies to row
tags.

Command-Line Name:-selectioncommand or -selcmd
Database Name: selectionCommand

Database Class: SelectionCommand

Specifies a command to evaluate when the selection is
retrieved from a table via the selection mechanism (ie:
evaluating «selection get"). The return value from
this command will become the string passed on by the
selection mechanism. It uses the %-substition model
described in COMMAND SUBSTITUTION below. If an error
occurs, a Tcl background error is generated and nothing
is returned.

Command-Line Name:-selectmode

Database Name: selectMode

Database Class: SelectMode

Specifies one of several styles for manipulating the
selection. The value of the option may be arbitrary,
but the default bindings expect it to be either single,
browse, multiple, or extended; the default value is
browse. These styles are like those for the Tk listbox,
except expanded for 2 dimensions.

Command-Line Name:-selecttitle

Database Name: selectTitles

Database Class: SelectTitles

Specifies whether title cells should be allowed in the
selection. Defaults to 0 (disallowed).

Command-Line Name:-selecttype

Database Name: selectType

Database Class: SelectType

Specifies one of several types of selection for the
table. The value of the option may be one of row, col,
cell, or both (meaning row && col); the default value
is cell. These types define whether an entire row/col
is affected when a cell's selection is changed (set or
clear).

Command-Line Name:-sparsearray

Database Name: sparseArray

Database Class: SparseArray

A boolean value that specifies whether an associated
Tcl array should be kept as a sparse array (1, the
default) or as a full array (0). If true, then cell
values that are empty will be deleted from the array
(taking less memory). If false, then all values in the
array will be maintained.

Command-Line Name:-state

Database Name: state

Database Class: State

Specifies one of two states for the entry: normal or
disabled. If the table is disabled then the value may
not be changed using widget commands and no insertion
cursor will be displayed, even if the input focus is in
the widget. Also, all insert or delete methods will be
ignored. Defaults to normal.

Command-Line Name:-titlecols

Database Name: titleCols

Database Class: TitleCols

Number of columns to use as a title area. Defaults to
0.

Command-Line Name:-titlerows

Database Name: titleRows

Database Class: TitleRows

Number of rows to use as a title area. Defaults to 0.

Command-Line Name:-usecommand

Database Name: useCommand

Database Class: UseCommand

A boolean value which specifies whether to use the command
option. This value sets itself to zero if command
is used and returns an error. Defaults to 1 (will use
command if specified).

Command-Line Name:-validate

Database Name: validate

Database Class: Validate

A boolean specifying whether validation should occur
for the active buffer. Defaults to 0.

Command-Line Name:-validatecommand or -vcmd
Database Name: validateCommand

Database Class: ValidateCommand

Specifies a command to execute when the active cell is
edited. This command is expected to return a Tcl
boolean. If it returns true, then it is assumed the
new value is OK, otherwise the new value is rejected
(the edition will not take place). Errors in this command
are handled in the background. It uses the %-substition
model described in COMMAND SUBSTITUTION below.

Command-Line Name:-variable

Database Name: variable

Database Class: Variable

Global Tcl array variable to attach to the table's C
array. It will be created if it doesn't already exist
or is a simple variable. Keys used by the table in the
array are of the form row,col for cells and the special
key active which contains the value of the active cell
buffer. The Tcl array is managed as a sparse array
(the table doesn't require all valid indices have
values). No stored value for an index is equivalent to
the empty string, and clearing a cell will remove that
index from the Tcl array, unless the -sparsearray
options is set to 0.

Command-Line Name:-width

Database Name: width

Database Class: Width

Specifies the desired width for the window, in columns.
If zero or less, then the desired width for the window
is made just large enough to hold all the columns in
the table. The width can be further limited by
-maxwidth.

Command-Line Name:-wrap

Database Name: wrap

Database Class: Wrap

Specifies the default wrap value for tags. Defaults to
0.

_________________________________________________________________

Description

The table command creates a 2-dimensional grid of cells.
The table can use a Tcl array variable or Tcl command for
data storage and retrieval. The widget has an active cell,
the contents of which can be edited (when the state is normal).
The widget supports a default style for the cells and
also multiple tags, which can be used to change the style of
a row, column or cell (see TAGS for details). A cell flash
can be set up so that changed cells will change color for a
specified amount of time ("blink"). Cells can have embedded
images or windows, as described in TAGS and «EMBEDDED WINDOWS"
respectively.

One or more cells may be selected as described below. If a
table is exporting its selection (see -exportselection
option), then it will observe the standard X11 protocols for
handling the selection. See THE SELECTION for details.

It is not necessary for all the cells to be displayed in the
table window at once; commands described below may be used
to change the view in the window. Tables allow scrolling in
both directions using the standard -xscrollcommand and
-yscrollcommand options. They also support scanning, as
described below.

In order to obtain good performance, the table widget supports
multiple drawing modes, two of which are fully Tk compatible.

Initialization

When the table command is loaded into an interpreter, a
built-in Tcl command, tkTableInit, is evaluated. This will
search for the appropriate table binding init file to load.
The directories searched are those in $tcl_pkgPath, both
with Tktable(version) appended and without, $tk_library and
[pwd] (the current directory). You can also define an
$env(TK_TABLE_LIBRARY) to head this search list.    By
default, the file searched for is called tkTable.tcl, but
this      can      be      overridden       by       setting
$env(TK_TABLE_LIBRARY_FILE).

This entire init script can be overridden by providing your
own tkTableInit procedure before the library is loaded.
Otherwise, the aforementioned env(TK_TABLE_LIBRARY) variable
will    be    set    with    the    directory    in    which
$env(TK_TABLE_LIBRARY_FILE) was found.

Indices

Many of the widget commands for tables take one or more
indices as arguments. An index specifies a particular cell
of the table, in any of the following ways:

number,number

Specifies the cell as a numerical index of
row,col which corresponds to the index of the
associated        Tcl        array,        where
-roworigin,-colorigin corresponds to the first
cell in the table (0,0 by default).

active

     Indicates the cell that has the location cursor.
It is specified with the activate widget command.

anchor

     Indicates the anchor point for the selection,
which is set with the selection anchor widget
command.

bottomright Indicates the bottom-rightmost cell visible in
the table.

end

        Indicates the bottom right cell of the table.

origin

     Indicates the top-leftmost editable cell of the
table, not necessarily in the display. This
takes into account the user specified origin and
title area.

topleft

    Indicates the top-leftmost editable cell visible
in the table (this excludes title cells).

@x,y

       Indicates the cell that covers the point in the
table window specified by x and y (in pixel
coordinates). If no cell covers that point,
then the closest cell to that point is used.

In the widget command descriptions below, arguments named
index, first, and last always contain text indices in one of
the above forms.

Tags

A tag is a textual string that is associated with zero or
more rows, columns or cells in a table. Tags may contain
arbitrary characters, but it is probably best to avoid using
names which look like indices. There may be any number of
tags associated with rows, columns or cells in a table.
There are several permanent tags in each table that can be
configured by the user and will determine the attributes for
special cells:

active

   This tag is given to the active cell

flash

    If flash mode is on, this tag is given to any
recently edited cells.

sel

      This tag is given to any selected cells.

title

    This tag is given to any cells in the title
rows and columns. This tag has -state dis_abled
by default.

Tags control the way cells are displayed on the screen.
Where appropriate, the default for displaying cells is
determined by the options for the table widget. However,
display options may be associated with individual tags using
the ``pathName tag configure'' widget command. If a cell
has been tagged, then the display options associated with
the tag override the default display style. The following
options are currently supported for tags:

-anchor anchor

Anchor for item in the cell space.

-background or -bg color

Background color of the cell.

-borderwidth or -bd pixels

Borderwidth of the cell.

-font fontName

Font for text in the cell.

-foreground or -fg color

Foreground color of the cell.

-justify justify

How to justify multi-line text in a cell. It must
be one of left, right, or center.

-image imageName

An image to display in the cell instead of text.

-multiline boolean

Whether to display text with newlines on multiple
lines.

-relief relief

The relief for the cell.

-showtext boolean

Whether to show the text over an image. This does
not currently work on Windows or Mac for all cases
due to the lack of clipping support in Tk's X emulation
(patch submitted).

-state state

The state of the cell, to allow for certain cells
to be disabled. This prevents the cell from being
edited by the insert or delete methods, but a
direct set will not be prevented.

-wrap boolean

Whether characters should wrap in a cell that is
not wide enough.

A priority order is defined among tags, and this order is
used in implementing some of the tag-related functions
described below. When a cell is displayed, its properties
are determined by the tags which are assigned to it.
Including the special tags, this order is flash, active,
sel, title, celltag, rowtag, coltag, default.

If a cell has several tags associated with it, and if their
display options conflict, then the options of the highest
priority tag are used. If a particular display option
hasn't been specified for a particular tag, or if it is
specified as an empty string, then that option will never be
used; the next-highest-priority tag's option will used
instead. If no tag specifies a particular display option,
then the default style for the widget will be used.

Images are used for display purposes only. Editing in that
cell will still be enabled and any querying of the cell will
show the text value of the cell, regardless of the value of
-showtext.

Embedded Windows

There may be any number of embedded windows in a table
widget (one per cell), and any widget may be used as an
embedded window (subject to the usual rules for geometry
management, which require the table window to be the parent
of the embedded window or a descendant of its parent). The
embedded window's position on the screen will be updated as
the table is modified or scrolled, and it will be mapped and
unmapped as it moves into and out of the visible area of the
table widget. Each embedded window occupies one cell's
worth of space in the table widget, and it is referred to by
the index of the cell in the table. Windows associated with
the table widget are destroyed when the table widget is destroyed.

Windows are used for display purposes only. A value still
exists for that cell, but will not be shown unless the window
is deleted in some way. If the window is destroyed or
lost by the table widget to another geometry manager, then
any data associated with it is lost (the cell it occupied
will no longer appear in window names).

When an embedded window is added to a table widget with the
window configure widget command, several configuration
options may be associated with it. These options may be
modified with later calls to the window configure widget
command. The following options are currently supported:

-create script

NOT CURRENTLY SUPPORTED. Specifies a Tcl script
that may be evaluated to create the window for the
annotation. If no -window option has been specified
for this cell then this script will be
evaluated when the cell is about to be displayed
on the screen. Script must create a window for
the cell and return the name of that window as its
result. If the cell's window should ever be
deleted, the script will be evaluated again the
next time the cell is displayed.

-background or -bg color

Background color of the cell. If not specified,
it uses the table's default background.

-padx pixels

As defined in the Tk options man page.

-pady pixels

As defined in the Tk options man page.

-relief relief

The relief to use for the cell in which the window
lies. If not specified, it uses the table's
default relief.

-sticky sticky

Stickiness of the window inside the cell, as
defined by the grid command.

-window pathName

Specifies the name of a window to display in the
annotation. It must exist before being specified
here.

the Selection

Table selections are available as type STRING. By default,
the value of the selection will be the values of the
selected cells in nested Tcl list form where each row is a
list and each column is an element of a row list. You can
change the way this value is interpreted by setting the
-rowseparator and -colseparator options. For example,
default Excel format would be to set -rowseparator to «\n"
and -colseparator to «\t". Changing these values affects
both how the table sends out the selection and reads in
pasted data, ensuring that the table should always be able
to cut and paste to itself. It is possible to change how
pastes are handled by editing the table library procedure
tk_tablePasteHandler. This might be necessary if -selectioncommand
is set.

Row/Col Spanning

Individual cells can span multiple rows and/or columns.
This is done via the spans command (see below for exact
arguments). Cells in the title area that span are not permitted
to span beyond the title area, and will be constrained
accordingly. If the title area shrinks during a
configure, sanity checking will occur to ensure the above.
You may set spans on regular cells that extend beyond the
defined row/col area. These spans will not be constrained,
so that when the defined row/col area expands, the span will
expand with it.

When setting a span, checks are made as to whether the span
would overlap an already spanning or hidden cell. This is
an error and it not allowed. Spans can affect the overall
speed of table drawing, although not significantly. If
spans are not used, then there is no performance loss.

Cells hidden by spanning cells still have valid data. This
will be seen during cut and paste operations that involve
hidden cells, or through direct access by a command like get
or set.

The drawing properties of spanning cells apply to only the
visual area of the cell. For example, if a cell is center
justified over 5 columns, then when viewing any portion of
those columns, it will appear centered in the visible area.
The non-visible column area will not be considered in the
centering calculations.

Command Substitution

The various option based commands that the table supports
all support the familiar Tk %-substitution model (see bind
for more details). The following %-sequences are recognized
and substituted by the table widget:

%c For SelectionCommand, it is the maximum number of
columns in any row in the selection. Otherwise it is
the column of the triggered cell.

%C

A convenience substitution for %r,%c.

%i For SelectionCommand, it is the total number of cells
in the selection. For Command, it is 0 for a read
(get) and 1 for a write (set). Otherwise it is the
current cursor position in the cell.

%r For SelectionCommand, it is the number of rows in the
selection. Otherwise it is the row of the triggered
cell.

%s For ValidateCommand, it is the current value of the
cell being validated. For SelectionCommand, it is the
default value of the selection. For BrowseCommand, it
is the index of the last active cell. For Command, it
is empty for reads (get) and the current value of the
cell for writes (set).

%S For ValidateCommand, it is the potential new value of
the cell being validated. For BrowseCommand, it is the
index of the new active cell.

%W The pathname to the window for which the command was
generated.

Widget Command

The table command creates a new Tcl command whose name is
pathName. This command may be used to invoke various operations
on the widget. It has the following general form:
pathName option ?arg arg ...?

Option and the args determine the exact behavior of the command.

The following commands are possible for table widgets:

pathName activate index

Sets the active cell to the one indicated by index.

pathName bbox first ?last?

It returns the bounding box for the specified cell
(range) as a 4-tuple of x, y, width and height in pixels.
It clips the box to the visible portion, if any,
otherwise an empty string is returned.

pathName border option args

This command is a voodoo hack to implement border sizing
for tables. This is normally called through bindings,
with the following as valid options:

pathName border mark x y ?row|col?

Records x and y and the row and/or column border
under that point in the table window, if any; used
in conjunction with later border dragto commands.
Typically this command is associated with a mouse
button press in the widget. If row or col is not
specified, it returns a tuple of both border
indices (an empty item means no border). Otherwise,
just the specified item is returned.

pathName border dragto x y

This command computes the difference between its x
and y arguments and the x and y arguments to the
last border mark command for the widget. It then
adjusts the previously marked border by the
difference. This command is typically associated
with mouse motion events in the widget, to produce
the effect of interactive border resizing.

pathName cget option

Returns the current value of the configuration option
given by option. Option may have any of the values
accepted by the table command.

pathName clear option ?first? ?last?

This command is a convenience routine to clear certain
state information managed by the table. first and last
represent valid table indices. If neither are specified,
then the command operates on the whole table.
The following options are recognized:

pathName clear cache ?first? ?last?

Clears the specified section of the cache, if the
table has been keeping one.

pathName clear sizes ?first? ?last?

Clears the specified row and column areas of
specific height/width dimensions. When just one
index is specified, for example 2,0, that is
interpreted as row 2 and column 0.

pathName clear tags ?first? ?last?

Clears the specified area of tags (all row, column
and cell tags).

pathName clear all ?first? ?last?

Performs all of the above clear functions on the
specified area.

pathName configure ?option? ?value option value ...?
Query or modify the configuration options of the
widget. If no option is specified, returns a list
describing all of the available options for pathName
(see Tk_ConfigureInfo for information on the format of
this list). If option is specified with no value, then
the command returns a list describing the one named
option (this list will be identical to the corresponding
sublist of the value returned if no option is
specified). If one or more option-value pairs are
specified, then the command modifies the given widget
option(s) to have the given value(s); in this case the
command returns an empty string. Option may have any
of the values accepted by the table command.

pathName curselection ?value?

With no arguments, it returns the sorted indices of the
currently selected cells. Otherwise it sets all the
selected cells to the given value. The set has no
effect if there is no associated Tcl array or the state
is disabled.

pathName curvalue ?value?

If no value is given, the value of the cell being
edited (indexed by active) is returned, else it is set
to the given value.

pathName delete option arg ?arg?

This command is used to delete various things in a
table. It has several forms, depending on the option:

pathName delete active index ?index?
Deletes text from the active cell. If only one
index is given, it deletes the character after
that index, otherwise it deletes from the first
index to the second. index can be a number,
insert or end.

pathName delete cols ?switches? index ?count?
Deletes count cols starting at (and including) col
index. The index will be constrained to the limits
of the tables. If count is negative, it
deletes cols to the left. Otherwise it deletes
cols to the right. count defaults to 1 (meaning
just the column specified). The selection will be
cleared. At the moment, spans are not adjusted
with this action. Optional switches are:

-holddimensions

Causes the table cols to be unaffected by the
deletion (empty cols may appear). By default
the dimensions are adjusted by count.

-holdtags

Causes the tags specified by the tag method
to not move along with the data. Also
prevents specific widths set by the width
method from being adjusted. By default,
these tags are properly adjusted.

-holdwindows

Causes the embedded windows created with the
window method to not move along with the
data. By default, these windows are properly
adjusted.

-keeptitles

Prevents title area cells from being changed.
Otherwise they are treated just like regular
cells and will move as specified.

--

Signifies the end of the switches.

pathName delete rows ?switches? index ?count?
Deletes count rows starting at (and including) row
index. If count is negative, it deletes rows
going up. Otherwise it deletes rows going down.
The selection will be cleared. The switches are
the same as those for column deletion.

pathName get first ?last?

Returns the value of the cells specified by the table
indices first and (optionally) last in a list.

pathName height ?row? ?value row value ...?
If no row is specified, returns a list describing all
rows for which a height has been set. If row is specified
with no value, it prints out the height of that
row in characters (positive number) or pixels (negative
number). If one or more row-value pairs are specified,
then it sets each row to be that height in lines (positive
number) or pixels (negative number). If value is
default, then the row uses the default height, specified
by -rowheight.

pathName hidden ?index? ?index ...?

When called without args, it returns all the hidden
cells (those cells covered by a spanning cell). If one
index is specified, it returns the spanning cell covering
that index, if any. If multiple indices are specified,
it returns 1 if all indices are hidden cells, 0
otherwise.

pathName icursor ?arg?

With no arguments, prints out the location of the
insertion cursor in the active cell. With one argument,
sets the cursor to that point in the string. 0
is before the first character, you can also use insert
or end for the current insertion point or the end of
the text. If there is no active cell, or the cell or
table is disabled, this will return -1.

pathName index index ?row|col?

Returns the integer cell coordinate that corresponds to
index in the form row,col. If row or col is specified,
then only the row or column index is returned.

pathName insert option arg arg

This command is used to into various things into a
table. It has several forms, depending on the option:

pathName insert active index value

The value is a text string which is inserted at
the index postion of the active cell. The cursor
is then positioned after the new text. index can
be a number, insert or end.

pathName insert cols ?switches? index ?count?
Inserts count cols starting at col index. If
count is negative, it inserts before the specified
col. Otherwise it inserts after the specified
col. The selection will be cleared. The switches
are the same as those for column deletion.

pathName insert rows ?switches? index ?count?
Inserts count rows starting at row index. If
count is negative, it inserts before the specified
row. Otherwise it inserts after the specified
row. The selection will be cleared. The switches
are the same as those for column deletion.

pathName reread

Rereads the old contents of the cell back into the
editing buffer. Useful for a key binding when <Escape>
is pressed to abort the edit (a default binding).

pathName scan option args

This command is used to implement scanning on tables.
It has two forms, depending on option:

pathName scan mark x y

Records x and y and the current view in the table
window; used in conjunction with later scan
dragto commands. Typically this command is associated
with a mouse button press in the widget.
It returns an empty string.

pathName scan dragto x y.

This command computes the difference between its x
and y arguments and the x and y arguments to the
last scan mark command for the widget. It then
adjusts the view by 5 times the difference in
coordinates. This command is typically associated
with mouse motion events in the widget, to produce
the effect of dragging the list at high speed
through the window. The return value is an empty
string.

pathName see index

Adjust the view in the table so that the cell given by
index is positioned as the cell one off from top left
(excluding title rows and columns) if the cell is not
currently visible on the screen. The actual cell may
be different to keep the screen full.

pathName selection option arg

This command is used to adjust the selection within a
table. It has several forms, depending on option:

pathName selection anchor index

Sets the selection anchor to the cell given by
index. The selection anchor is the end of the
selection that is fixed while dragging out a
selection with the mouse. The index anchor may be
used to refer to the anchor cell.

pathName selection clear first ?last?
If any of the cells between first and last
(inclusive) are selected, they are deselected.
The selection state is not changed for cells outside
this range. first may be specified as all to
remove the selection from all cells.

pathName selection includes index

Returns 1 if the cell indicated by index is
currently selected, 0 if it isn't.

pathName selection set first ?last?

Selects all of the cells in the range between
first and last, inclusive, without affecting the
selection state of cells outside that range.

pathName set ?row|col? index ?value? ?index value ...?
Sets the specified index to the associated value.
Table validation will not be triggered via this method.
If row or col precedes the list of index/value pairs,
then the value is assumed to be a Tcl list whose values
will be split and set into the subsequent columns (if
row is specified) or rows (for col). For example, set
row 2,3 {2,3 2,4 2,5} will set 3 cells, from 2,3 to
2,5. The setting of cells is silently bounded by the
known table dimensions.

pathName spans ?index? ?rows,cols index rows,cols ...?
This command is used to manipulate row/col spans. When
called with no arguments, all known spans are returned
as a list of tuples of the form {index span}. When
called with only the index, the span for that index
only is returned, if any. Otherwise an even number of
index rows,cols pairs are used to set spans. A span
starts at the index and continues for the specified
number of rows and cols. Negative spans are not supported.
A span of 0,0 unsets any span on that cell.
See EXAMPLES for more info.

pathName tag option ?arg arg ...?

This command is used to manipulate tags. The exact
behavior of the command depends on the option argument
that follows the tag argument. cget, cell, and row|col
complain about unknown tag names. The following forms
of the command are currently supported:

pathName tag cell tagName ?index ...?
With no arguments, prints out the list of cells
that use the tag. Otherwise it sets the specified
cells to use the tag. If tag is {}, the cells are
reset to the default tag. Tags added during
-*tagcommand evaluation do not register here.

pathName tag cget tagName option

This command returns the current value of the
option named option associated with the tag given
by tagName. Option may have any of the values
accepted by the tag configure widget command.

pathName tag col tagName ?col ...?

With no arguments, prints out the list of cols
that use the tag. Otherwise it sets the specified
cols to use the tag. If tag is {}, the cols are
reset to the default tag. Tags added during -coltagcommand
evaluation do not register here. If
tagName does not exist, it is not created, but nor
is an error generated.

value ...?

pathName tag configure tagName ?option? ?value? ?option
This command is similar to the configure widget
command except that it modifies options associated
with the tag given by tagName instead of modifying
options for the overall table widget. If no
option is specified, the command returns a list
describing all of the available options for tag_Name
(see Tk_ConfigureInfo for information on the
format of this list). If option is specified with
no value, then the command returns a list describing
the one named option (this list will be identical
to the corresponding sublist of the value
returned if no option is specified). If one or
more option-value pairs are specified, then the
command modifies the given option(s) to have the
given value(s) in tagName; in this case the command
returns an empty string. See TAGS above for
details on the options available for tags.

pathName tag delete tagName

Deletes a tag. No error if the tag does not
exist.

pathName tag exists tagName

Returns 1 if the named tag exists, 0 otherwise.

pathName tag includes tagName index

Returns 1 if the specified index has the named
tag, 0 otherwise.

pathName tag names ?pattern?

If no pattern is specified, shows the names of all
defined tags. Otherwise the pattern is used as a
glob pattern to show only tags matching that pattern.

pathName tag row tagName ?row ...?

With no arguments, prints out the list of rows
that use the tag. Otherwise it sets the specified
rows to use the tag. If tag is {}, the rows are
reset to use the default tag. Tags added during
-rowtagcommand evaluation do not register here.
If tagName does not exist, it is not created, but
nor is an error generated.

pathName validate index

Explicitly validates the specified index based on the
current -validatecommand and returns 0 or 1 based on
whether the cell was validated.

pathName width ?col? ?value col value ...?
If no col is specified, returns a list describing all
cols for which a width has been set. If col is specified
with no value, it prints out the width of that col
in characters (positive number) or pixels (negative
number). If one or more col-value pairs are specified,
then it sets each col to be that width in characters
(positive number) or pixels (negative number). If
value is default, then the col uses the default width,
specified by -colwidth.

pathName window option ?arg arg ...?

This command is used to manipulate embedded windows.
The exact behavior of the command depends on the option
argument that follows the window argument. The following
forms of the command are currently supported:

pathName window cget index option

This command returns the current value of the
option named option associated with the window
given by index. Option may have any of the values
accepted by the window configure widget command.

value ...?

pathName window configure index ?option? ?value? ?option
This command is similar to the configure widget
command except that it modifies options associated
with the embedded window given by index instead of
modifying options for the overall table widget.
If no option is specified, the command returns a
list describing all of the available options for
index (see Tk_ConfigureInfo for information on the
format of this list). If option is specified with
no value, then the command returns a list describing
the one named option (this list will be
identical to the corresponding sublist of the
value returned if no option is specified). If one
or more option-value pairs are specified, then the
command modifies the given option(s) to have the
given value(s) in index; in this case the command
returns an empty string. See EMBEDDED WINDOWS
above for details on the options available for
windows.

pathName window delete index ?index ...?
Deletes an embedded window from the table. The
associated window will also be deleted.

pathName window move indexFrom indexTo
Moves an embedded window from one cell to another.
If a window already exists in the target cell, it
will be deleted.

pathName window names ?pattern?

If no pattern is specified, shows the cells of all
embedded windows. Otherwise the pattern is used
as a glob pattern to show only cells matching that
pattern.

pathName xview args

This command is used to query and change the horizontal
position of the information in the widget's window. It
can take any of the following forms:

pathName xview

Returns a list containing two elements. Each element
is a real fraction between 0 and 1; together
they describe the horizontal span that is visible
in the window. For example, if the first element
is .2 and the second element is .6, 20% of the
table's text is off-screen to the left, the middle
40% is visible in the window, and 40% of the text
is off-screen to the right. These are the same
values passed to scrollbars via the -xscrollcommand
option.

pathName xview index

Adjusts the view in the window so that the column
given by index is displayed at the left edge of
the window.

pathName xview moveto fraction

Adjusts the view in the window so that fraction of
the total width of the table text is off-screen to
the left. fraction must be a fraction between 0
and 1.

pathName xview scroll number what

This command shifts the view in the window left or
right according to number and what. Number must
be an integer. What must be either units or pages
or an abbreviation of one of these. If what is
units, the view adjusts left or right by number
character units (the width of the 0 character) on
the display; if it is pages then the view adjusts
by number screenfuls. If number is negative then
characters farther to the left become visible; if
it is positive then characters farther to the
right become visible.

pathName yview ?args?

This command is used to query and change the vertical
position of the text in the widget's window. It can
take any of the following forms:

pathName yview

Returns a list containing two elements, both of
which are real fractions between 0 and 1. The
first element gives the position of the table element
at the top of the window, relative to the
table as a whole (0.5 means it is halfway through
the table, for example). The second element gives
the position of the table element just after the
last one in the window, relative to the table as a
whole. These are the same values passed to
scrollbars via the -yscrollcommand option.

pathName yview index

Adjusts the view in the window so that the row
given by index is displayed at the top of the window.

pathName yview moveto fraction

Adjusts the view in the window so that the element
given by fraction appears at the top of the window.
Fraction is a fraction between 0 and 1; 0
indicates the first element in the table, 0.33
indicates the element one-third the way through
the table, and so on.

pathName yview scroll number what

This command adjusts the view in the window up or
down according to number and what. Number must be
an integer. What must be either units or pages.
If what is units, the view adjusts up or down by
number lines; if it is pages then the view adjusts
by number screenfuls. If number is negative then
earlier elements become visible; if it is positive
then later elements become visible.

Default Bindings

The initialization creates class bindings that give the following
default behaviour:

[1] Clicking Button-1 in a cell activates that cell.
Clicking into an already active cell moves the insertion
cursor to the character nearest the mouse.

[2] Moving the mouse while Button-1 is pressed will stroke
out a selection area. Exiting while Button-1 is
pressed causing scanning to occur on the table along
with selection.

[3] Moving the mouse while Button-2 is pressed causes scanning
to occur without any selection.

[4] Home moves the table to have the origin in view.

[5] End moves the table to have the end cell in view.

[6] Control-Home moves the table to the origin and
activates that cell.

[7] Control-End moves the table to the end and activates
that cell.

[8] Shift-Control-Home extends the selection to the origin.

[9] Shift-Control-End extends the selection to the end.

[10] The left, right, up and down arrows move the active
cell.

[11] Shift-<arrow> extends the selection in that direction.

[12] Control-leftarrow and Control-rightarrow move the
insertion cursor within the cell.

[13] Control-slash selects all the cells.

[14] Control-backslash clears selection from all the cells.

[15] Backspace deletes the character before the insertion
cursor in the active cell.

[16] Delete deletes the character after the insertion cursor
in the active cell.

[17] Escape rereads the value of the active cell from the
specified data source, discarding any edits that have
may been performed on the cell.

[18] Control-a moves the insertion cursor to the beginning
of the active cell.

[19] Control-e moves the insertion cursor to the end of the
active cell.

[20] Control-minus and Control-equals decrease and increase
the width of the column with the active cell in it.

[21] Moving the mouse while Button-3 (the right button on
Windows) is pressed while you are over a border will
cause interactive resizing of that row and/or column to
occur, based on the value of -resizeborders.

Some bindings may have slightly different behavior dependent
on the -selectionmode of the widget.

If the widget is disabled using the -state option, then its
view can still be adjusted and cells can still be selected,
but no insertion cursor will be displayed and no cell modifications
will take place.

The behavior of tables can be changed by defining new bindings
for individual widgets or by redefining the class bindings.
The default bindings are either compiled in or read
from a file expected to correspond to: «[lindex $tcl_pkgPath
0]/Tktable<version>/tkTable.tcl".

Performance Issues

The number of rows and columns or a table widget should not
significantly affect the speed of redraw. Recalculation and
redraw of table parameters and cells is restricted as much
as possible.

The display cell with the insert cursor is redrawn each time
the cursor blinks, which causes a steady stream of graphics
traffic. Set the -insertofftime option to 0 avoid this.
The use of a -command with the table without a cache can
cause significant slow-down, as the command is called once
for each request of a cell value.

Examples

Set the topleft title area to be one spanning cell. This
overestimates both row and column span by one, but the command
does all the constraining for us.

$table span [$table cget -roworigin],[$table cget -colorigin] [$table cget -titlerows],[$table cget -titlecols]
Force a table window refresh (useful for the slight chance
that a bug in the table is not causing proper refresh):
$table configure -padx [$table cget -padx]

Keywords

table, widget, extension

Table of Contents

Name

Synopsis

Standard Options

Widget-specific Options

Description

Initialization

Indices

Tags

Embedded Windows

the Selection

Row/Col Spanning

Command Substitution

Widget Command

Default Bindings

Performance Issues

Examples

Keywords


text:
package com.teamnayn.ceditor;

import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.egysoft.gdx.Assets;
import com.egysoft.gdx.Game;
import com.egysoft.gdx.GameState;

public class GameLoader extends GameState
{
	public GameLoader()
	{
		super(null);
	}

	private Stage stage;
	private Assets assets;
	private GameState toLoad;

	public GameState load(GameState state)
	{
		toLoad = state;
		assets.loadGroup(toLoad.getGroupName());

		return this;
	}

	@Override
	protected void create()
	{
		final Game instance = Game.instance;
		final int w = instance.getWidth(), h = instance.getHeight();
		stage = new Stage(new FitViewport(w,h));
		assets = instance.assets;
	}

	@Override
	protected void dispose()
	{
		stage.dispose();
		stage = null;
		assets = null;
	}

	@Override
	protected void pause()
	{

	}

	@Override
	protected void resume()
	{
	}

	@Override
	protected void resize(int w, int h)
	{
		stage.getViewport().update(w, h);
	}

	@Override
	public void render(float delta)
	{
		if(assets.update())
		{
			Game.instance.nextState(toLoad);
		}
		stage.act(delta);
		stage.draw();
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.keycloak.testsuite.model;

import org.jboss.resteasy.specimpl.MultivaluedMapImpl;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.ClientConnection;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.RequiredAction;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.TimeBasedOTP;
import org.keycloak.representations.PasswordToken;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.managers.AuthenticationManager.AuthenticationStatus;
import org.keycloak.services.managers.BruteForceProtector;
import org.keycloak.util.Time;

import javax.ws.rs.core.MultivaluedMap;
import java.util.UUID;

public class AuthenticationManagerTest extends AbstractModelTest {

    private AuthenticationManager am;
    private MultivaluedMap<String, String> formData;
    private TimeBasedOTP otp;
    private RealmModel realm;
    private UserModel user;
    private BruteForceProtector protector;
    private ClientConnection dummyConnection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return "127.0.0.1";

        }

        @Override
        public String getRemoteHost() {
            return "localhost";

        }

        @Override
        public int getReportPort() {
            return 8080;
        }
    };

    @Test
    public void authForm() {
        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.SUCCESS, status);
    }

    @Test
    public void authFormInvalidPassword() {
        formData.remove(CredentialRepresentation.PASSWORD);
        formData.add(CredentialRepresentation.PASSWORD, "invalid");

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormMissingUsername() {
        formData.remove("username");

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_USER, status);
    }

    @Test
    public void authFormMissingPassword() {
        formData.remove(CredentialRepresentation.PASSWORD);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.MISSING_PASSWORD, status);
    }

    @Test
    public void authFormRequiredAction() {
        realm.addRequiredCredential(CredentialRepresentation.TOTP);
        user.addRequiredAction(RequiredAction.CONFIGURE_TOTP);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.ACTIONS_REQUIRED, status);
    }

    @Test
    public void authFormUserDisabled() {
        user.setEnabled(false);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.ACCOUNT_DISABLED, status);
    }

    @Test
    public void authFormWithTotp() {
        realm.addRequiredCredential(CredentialRepresentation.TOTP);

        String totpSecret = UUID.randomUUID().toString();

        UserCredentialModel credential = new UserCredentialModel();
        credential.setType(CredentialRepresentation.TOTP);
        credential.setValue(totpSecret);

        user.updateCredential(credential);

        user.setTotp(true);

        String token = otp.generate(totpSecret);

        formData.add(CredentialRepresentation.TOTP, token);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.SUCCESS, status);
    }

    @Test
    public void authFormWithTotpInvalidPassword() {
        authFormWithTotp();

        formData.remove(CredentialRepresentation.PASSWORD);
        formData.add(CredentialRepresentation.PASSWORD, "invalid");

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormWithTotpMissingPassword() {
        authFormWithTotp();

        formData.remove(CredentialRepresentation.PASSWORD);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.MISSING_PASSWORD, status);
    }

    @Test
    public void authFormWithTotpInvalidTotp() {
        authFormWithTotp();

        formData.remove(CredentialRepresentation.TOTP);
        formData.add(CredentialRepresentation.TOTP, "invalid");

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormWithTotpMissingTotp() {
        authFormWithTotp();

        formData.remove(CredentialRepresentation.TOTP);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.MISSING_TOTP, status);
    }

    @Test
    public void authFormWithTotpPasswordToken() {
        realm.addRequiredCredential(CredentialRepresentation.TOTP);

        String totpSecret = UUID.randomUUID().toString();

        UserCredentialModel credential = new UserCredentialModel();
        credential.setType(CredentialRepresentation.TOTP);
        credential.setValue(totpSecret);

        user.updateCredential(credential);

        user.setTotp(true);

        String token = otp.generate(totpSecret);

        formData.add(CredentialRepresentation.TOTP, token);
        formData.remove(CredentialRepresentation.PASSWORD);

        String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), user.getId())).rsa256(realm.getPrivateKey());
        formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.SUCCESS, status);
    }

    @Test
    public void authFormWithTotpPasswordTokenInvalidKey() {
        authFormWithTotpPasswordToken();

        formData.remove(CredentialRepresentation.PASSWORD_TOKEN);
        String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), user.getId())).rsa256(realm.getPrivateKey());
        formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);

        KeycloakModelUtils.generateRealmKeys(realm);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormWithTotpPasswordTokenInvalidRealm() {
        authFormWithTotpPasswordToken();

        formData.remove(CredentialRepresentation.PASSWORD_TOKEN);
        String passwordToken = new JWSBuilder().jsonContent(new PasswordToken("invalid", user.getId())).rsa256(realm.getPrivateKey());
        formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormWithTotpPasswordTokenInvalidUser() {
        authFormWithTotpPasswordToken();

        formData.remove(CredentialRepresentation.PASSWORD_TOKEN);
        String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), "invalid")).rsa256(realm.getPrivateKey());
        formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);

        AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
        Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);
    }

    @Test
    public void authFormWithTotpPasswordTokenExpired() throws InterruptedException {
        int lifespan = realm.getAccessCodeLifespanUserAction();

        try {
            authFormWithTotpPasswordToken();

            realm.setAccessCodeLifespanUserAction(1);

            formData.remove(CredentialRepresentation.PASSWORD_TOKEN);
            String passwordToken = new JWSBuilder().jsonContent(new PasswordToken(realm.getName(), "invalid")).rsa256(realm.getPrivateKey());
            formData.add(CredentialRepresentation.PASSWORD_TOKEN, passwordToken);

            Time.setOffset(2);

            AuthenticationStatus status = am.authenticateForm(session, dummyConnection, realm, formData);
            Assert.assertEquals(AuthenticationStatus.INVALID_CREDENTIALS, status);

            Time.setOffset(0);
        } finally {
            realm.setAccessCodeLifespanUserAction(lifespan);
        }
    }

    @Before
    @Override
    public void before() throws Exception {
        super.before();

        realm = realmManager.createRealm("TestAuth");
        realm.setAccessCodeLifespan(100);
        realm.setAccessCodeLifespanUserAction(100);
        realm.setEnabled(true);
        realm.setName("TestAuth");

        KeycloakModelUtils.generateRealmKeys(realm);

        realm.setAccessTokenLifespan(1000);
        realm.addRequiredCredential(CredentialRepresentation.PASSWORD);

        protector = ResteasyProviderFactory.getContextData(BruteForceProtector.class);
        am = new AuthenticationManager(protector);

        user = realmManager.getSession().users().addUser(realm, "test");
        user.setEnabled(true);

        UserCredentialModel credential = new UserCredentialModel();
        credential.setType(CredentialRepresentation.PASSWORD);
        credential.setValue("password");

        user.updateCredential(credential);

        formData = new MultivaluedMapImpl<String, String>();
        formData.add("username", "test");
        formData.add(CredentialRepresentation.PASSWORD, "password");

        otp = new TimeBasedOTP();
    }

}


text:
require 'spec_helper'

module SSLCheck
  describe 'Checking Certificates' do
    context "when the certificate is missing" do
      before do
        SSLCheck::Client.timeout_seconds = 1
        @check = Checker.new.check("nossl.com")
      end
      it 'should not be valid' do
        expect(@check.valid?).to_not be
      end
      it 'should have errors' do
        expect(@check.errors).to_not be_empty
      end
    end
    context "when the certificate is valid" do
      before do
        @check = Checker.new.check("letsencrypt.org")
      end
      it 'should be valid' do
        expect(@check.valid?).to be
      end
      it 'should not have any errors' do
        expect(@check.errors).to be_empty
      end
      it 'should know the peer certificate' do
        expect(@check.peer_cert).to be
      end
      it 'should know the ca bundle' do
        expect(@check.ca_bundle).to be
      end
    end
    xcontext "when the certificate is on a subdomain, but not a wildcard cert" do
      before do
        @check = Checker.new.check("https://www.httpbin.org")
      end
      it 'should be valid' do
        expect(@check.valid?).to be
      end
      it 'should not have any errors' do
        expect(@check.errors).to be_empty
      end
    end
    context "when the common name is not correct" do
      before do
        @check = Checker.new.check('https://wrong.host.badssl.com/')
      end
      it 'should not be valid' do
        expect(@check.valid?).to_not be
      end
      it 'should have errors' do
        expect(@check.errors).to_not be_empty
      end
    end
  end
end


text:
package org.jboss.arquillian.warp.impl.client.event;

import org.jboss.arquillian.warp.Activity;
import org.jboss.arquillian.warp.impl.client.execution.WarpContext;

public class ExecuteWarp {

    private Activity activity;
    private WarpContext warpContext;

    public ExecuteWarp(Activity activity, WarpContext warpContext) {
        this.activity = activity;
        this.warpContext = warpContext;
    }

    public Activity getActivity() {
        return activity;
    }

    public WarpContext getWarpContext() {
        return warpContext;
    }

}


text:
{% if form.form_html %}
    {% if include_media %}{{ form.media }}{% endif %}
    {% if form_show_errors %}
        {% include "bootstrap3/errors.html" %}
    {% endif %}
    {{ form.form_html }}
{% else %}
    {% include "bootstrap3/uni_form.html" %}
{% endif %}


text:
using System;
using Microsoft.Extensions.Logging;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.Configuration;
using NakedFramework.Architecture.Menu;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.Core.Error;
using NakedFramework.Core.Util;

namespace NakedFramework.Metamodel.Component;

public sealed class MetamodelHolder : IMetamodelBuilder {
    private readonly ILogger<MetamodelHolder> logger;

    public MetamodelHolder(ISpecificationCache cache, ICoreConfiguration coreConfiguration, ILogger<MetamodelHolder> logger) {
        Cache = cache;
        CoreConfiguration = coreConfiguration;
        this.logger = logger;
    }

    public ICoreConfiguration CoreConfiguration { get; }

    private ITypeSpecImmutable GetSpecificationFromCache(Type type) {
        var key = TypeKeyUtils.GetKeyForType(type);
        TypeUtils.GetType(type.FullName); // This should ensure type is cached
        return Cache.GetSpecification(key);
    }

    #region IMetamodelBuilder Members

    public ITypeSpecImmutable[] AllSpecifications => Cache.AllSpecifications();

    private ITypeSpecImmutable ReturnOrError(ITypeSpecImmutable spec, Type type) =>
        spec switch {
            { } => spec,
            null when CoreConfiguration.UsePlaceholderForUnreflectedType => GetSpecification(typeof(UnreflectedTypePlaceholder)),
            _ => throw new NakedObjectSystemException(logger.LogAndReturn($"Failed to Load Specification for: {type?.FullName} error: unexpected null"))
        };

    public ITypeSpecImmutable GetSpecification(Type type) {
        try {
            return ReturnOrError(GetSpecificationFromCache(TypeKeyUtils.FilterNullableAndProxies(type)), type);
        }
        catch (Exception e) when (e is not NakedObjectSystemException) {
            throw new NakedObjectSystemException(logger.LogAndReturn($"Failed to Load Specification for: {type?.FullName} error: {e}"));
        }
    }

    public ITypeSpecImmutable GetSpecification(string name) => GetSpecification(TypeUtils.GetType(name));

    public void Add(Type type, ITypeSpecBuilder spec) => Cache.Cache(TypeKeyUtils.GetKeyForType(type), spec);

    public void AddMainMenu(IMenuImmutable menu) => Cache.Cache(menu);

    public void ReplaceCache(ISpecificationCache newCache) => Cache = newCache;

    public void SaveToFile(string filePath, Type[] additionalKnownTypes) => Cache.Serialize(filePath, additionalKnownTypes);

    public ISpecificationCache Cache { get; private set; }

    public IMenuImmutable[] MainMenus => Cache.MainMenus();

    #endregion
}


text:
'use strict'

const fs = require('fs')
const path = require('path')

const assist = require('./assist.js')
const config = require('./config.js')
const simple = require('./simple.js')

module.exports = {
  readyRepo,
  updateRepo,
  findOrigin
}

/**
 * ready repository
 * verify .git, remote
 *
 * @param  {String} cwd
 * @param  {String} repo
 * @return {Promise} ready
 */
function readyRepo(cwd, repo) {
  function resetRepo() {
    return assist.chainPromise([
        assist.safeExecute('rm', ['-rf', cwd]),
        assist.safeExecute('mkdir', ['-p', cwd]),
      ])
      .then(function() { return false })
  }

  if (!assist.existsPath(cwd)) {
    return resetRepo()
  }
  var rootFiles = fs.readdirSync(cwd)
  if (rootFiles.indexOf('.git') < 0) {
    if (rootFiles.length > 0) {
      // fix .git not found
      return resetRepo()
    }
  } else {
    var gitFiles = fs.readdirSync(path.join(cwd, '/.git'))
    if (gitFiles.indexOf('config') >= 0) {
      var configText = fs.readFileSync(path.join(cwd, '/.git/config'))
      if (gitFiles.indexOf('HEAD') >= 0 && configText.indexOf(repo) >= 0) {
        return Promise.resolve(true)
      }
    }
    return resetRepo()
  }
  return Promise.resolve(false)
}

/**
 * update repository to revision
 *
 * @param  {String} cwd
 * @param  {String} rev
 */
function updateRepo(cwd, rev) {
  var sshkey = config.getSSHKey()
  if (!sshkey) {
    return assist.nullSSHKey()
  }

  var execOptsWithSSH = { cwd, sshkey, ignore: true }

  var scriptTryUpdateChains = [
    assist.safeExecute('git', ['checkout', '-qf', rev], execOptsWithSSH),
    assist.safeExecute('git', ['pull'], execOptsWithSSH),
    assist.safeExecute('git', ['reset', '--hard', `origin/${rev}`], execOptsWithSSH),
    assist.safeExecute('git', ['fetch', '--tags'], execOptsWithSSH),
  ]

  var scriptFixBranchChains = [
    assist.safeExecute('git', ['branch', '-D', 'branch_used_to_delete_branch'], execOptsWithSSH),
    assist.safeExecute('git', ['checkout', '-b', 'branch_used_to_delete_branch'], execOptsWithSSH),
    assist.safeExecute('git', ['branch', '-D', rev], execOptsWithSSH),
    assist.safeExecute('git', ['remote', 'update'], execOptsWithSSH),
    assist.safeExecute('git', ['fetch', 'origin', rev], execOptsWithSSH),
    assist.safeExecute('git', ['checkout', '-q', '-b', rev, `origin/${rev}`], execOptsWithSSH),
    assist.safeExecute('git', ['branch', '-D', 'branch_used_to_delete_branch'], execOptsWithSSH),
  ]

  var scriptCleanRepoChains = [
    assist.safeExecute('git', ['remote', 'prune', 'origin'], execOptsWithSSH),
    assist.safeExecute('git', ['gc'], execOptsWithSSH)
  ]

  return Promise.resolve()
    .then(() => assist.chainPromise(scriptCleanRepoChains))
    .then(() => assist.chainPromise(scriptTryUpdateChains))
    .catch(error => {
      console.log(error)
      return assist.chainPromise(scriptFixBranchChains)
        .then(function () {
          return assist.chainPromise(scriptTryUpdateChains)
        })
    })
}

/**
 * find origin commits with same blobs in rev
 *
 * @param  {String} cwd
 * @param  {String} rev - revision
 * @return {Promise} { file: { blob, zero } }
 */
function findOrigin(cwd, rev) {
  return Promise.all([
      // get ref blob table
      simple.getBlobTable(cwd, rev, '$4,$3').then(function (table) {
        var maps = {}
        for (var i = 0; i < table.length; i += 2) {
          maps[table[i]] = { blob: table[i + 1], zero: null }
        }
        return maps
      }),

      // get all revs about cwd
      simple.getFileTrack(cwd, cwd)
    ])
    .then(function (batch) {
      var maps = batch[0]
      var revs = batch[1]
      // from oldest rev to latest rev
      var steps = revs.reverse().map(function (revI, i) {
        return function () {
          return simple.getBlobTable(cwd, revI, '$4,$3')
            .then(function (table) {
              for (var k = 0; k < table.length; k += 2) {
                let map = maps[table[k]]
                if (map && !map.zero && map.blob === table[k + 1]) {
                  map.zero = [revI, i]
                }
              }
            })
        }
      })
      return assist.chainPromise(steps)
        .then(function () {
          return Promise.resolve(maps)
        })
    })
}


text:
function [timebase_cs, e_total_cs, e_ports_cs] =  extract_cumulative_total_energy_from_wake_data(wake_data)
%
% wake data (structure): contains all the data from the wake postprocessing
%
% timebase_cs (vector): timebase in ns.
% e_total_cs (vector): cumulative sum of the total energy in the structure (nJ).
% e_ports_cs (vector): cumulative sum of the energy transmitted out of the ports (nJ).

if wake_data.port_time_data.total_energy ~=0
    t_step = wake_data.port_time_data.timebase(2) - wake_data.port_time_data.timebase(1);
    for jsff = length(wake_data.port_time_data.data):-1:1 % number of ports
        tmp = sum(wake_data.port_time_data.data{jsff},2);
        e_ports_cs(:,jsff) = cumsum(tmp.^2) * t_step * 1e9;
    end
    e_total_cs = sum(e_ports_cs,2) * 1e9;
else
    e_ports_cs = zeros(1,length(wake_data.port_time_data.data));
    e_total_cs = 0;
end
timebase_cs = wake_data.port_time_data.timebase *1e9;


text:
package org.apache.lucene.facet.search;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util._TestUtil;
import org.junit.Test;

import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.facet.FacetTestUtils;
import org.apache.lucene.facet.FacetTestUtils.IndexTaxonomyReaderPair;
import org.apache.lucene.facet.FacetTestUtils.IndexTaxonomyWriterPair;
import org.apache.lucene.facet.index.params.DefaultFacetIndexingParams;

public class TestTotalFacetCounts extends LuceneTestCase {

  private static void initCache(int numEntries) {
    TotalFacetCountsCache.getSingleton().clear();
    TotalFacetCountsCache.getSingleton().setCacheSize(numEntries); // Set to keep one in mem
  }

  @Test
  public void testWriteRead() throws IOException {
    doTestWriteRead(14);
    doTestWriteRead(100);
    doTestWriteRead(7);
    doTestWriteRead(3);
    doTestWriteRead(1);
  }

  private void doTestWriteRead(final int partitionSize) throws IOException {
    initCache(1);

    // Create temporary RAMDirectories
    Directory[][] dirs = FacetTestUtils.createIndexTaxonomyDirs(1);
    // Create our index/taxonomy writers
    IndexTaxonomyWriterPair[] writers = FacetTestUtils
    .createIndexTaxonomyWriterPair(dirs);
    DefaultFacetIndexingParams iParams = new DefaultFacetIndexingParams() {
      @Override
      protected int fixedPartitionSize() {
        return partitionSize;
      }
    };
    // The counts that the TotalFacetCountsArray should have after adding
    // the below facets to the index.
    int[] expectedCounts = new int[] { 0, 3, 1, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1 };

    // Add a facet to the index
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "a", "b");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "c", "d");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "a", "e");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "a", "d");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "c", "g");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "c", "z");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "b", "a");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "1", "2");
    TestTotalFacetCountsCache.addFacets(iParams, writers[0].indexWriter, writers[0].taxWriter, "b", "c");

    // Commit Changes
    writers[0].commit();
    writers[0].close();

    IndexTaxonomyReaderPair[] readers =
      FacetTestUtils.createIndexTaxonomyReaderPair(dirs);

    int[] intArray = new int[iParams.getPartitionSize()];

    TotalFacetCountsCache tfcc = TotalFacetCountsCache.getSingleton();
    File tmpFile = _TestUtil.createTempFile("test", "tmp", TEMP_DIR);
    tfcc.store(tmpFile, readers[0].indexReader, readers[0].taxReader, iParams, null);
    tfcc.clear(); // not really required because TFCC overrides on load(), but in the test we need not rely on this.
    tfcc.load(tmpFile, readers[0].indexReader, readers[0].taxReader, iParams);

    // now retrieve the one just loaded
    TotalFacetCounts totalCounts =
      tfcc.getTotalCounts(readers[0].indexReader, readers[0].taxReader, iParams, null);

    int partition = 0;
    for (int i=0; i<expectedCounts.length; i+=partitionSize) {
      totalCounts.fillTotalCountsForPartition(intArray, partition);
      int[] partitionExpectedCounts = new int[partitionSize];
      int nToCopy = Math.min(partitionSize,expectedCounts.length-i);
      System.arraycopy(expectedCounts, i, partitionExpectedCounts, 0, nToCopy);
      assertTrue("Wrong counts! for partition "+partition+
          "\nExpected:\n" + Arrays.toString(partitionExpectedCounts)+
          "\nActual:\n" + Arrays.toString(intArray),
          Arrays.equals(partitionExpectedCounts, intArray));
      ++partition;
    }
    readers[0].close();
    IOUtils.close(dirs[0]);
    tmpFile.delete();
  }

}


text:
layout: page
title: "JavaScript printf function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/printf:494
- /functions/view/printf
- /functions/view/494
- /functions/printf:494
- /functions/494
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's printf

{% codeblock strings/printf.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/printf.js raw on github %}
function printf () {
  // From: http://phpjs.org/functions
  // +   original by: Ash Searle (http://hexmen.com/blog/)
  // +   improved by: Michael White (http://getsprink.com)
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: sprintf
  // *     example 1: printf("%01.2f", 123.1);
  // *     returns 1: 6
  var body, elmt, d = this.window.document;
  var ret = '';

  var HTMLNS = 'http://www.w3.org/1999/xhtml';
  body = d.getElementsByTagNameNS ? (d.getElementsByTagNameNS(HTMLNS, 'body')[0] ? d.getElementsByTagNameNS(HTMLNS, 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0];

  if (!body) {
    return false;
  }

  ret = this.sprintf.apply(this, arguments);

  elmt = d.createTextNode(ret);
  body.appendChild(elmt);

  return ret.length;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/printf.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.

Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/printf.js)

### Example 1
This code
{% codeblock lang:js example %}
printf("%01.2f", 123.1);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
6
{% endcodeblock %}

### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}


text:
package org.apache.shardingsphere.infra.federation.optimizer.metadata.fixture;

import org.apache.shardingsphere.infra.rule.identifier.type.TableContainedRule;

import java.util.Collection;
import java.util.Collections;

public final class CommonFixtureRule implements TableContainedRule {

    @Override
    public Collection<String> getTables() {
        return Collections.singletonList("t_order_new");
    }

    @Override
    public String getType() {
        return CommonFixtureRule.class.getSimpleName();
    }
}


text:
/**
 * 	File contentente la classe ServiceModifyProcessTest
 *
 *	@file		ServiceModifyProcessTest.java
 *	@author		DeSQ
 *	@date		2014-05-14
 *	@version	1.0
 */

package com.sequenziatore.server.service.admin;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.Query;
import org.json.JSONObject;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;

import com.sequenziatore.server.databaseutil.util.HibernateUtil;
import com.sequenziatore.server.entity.IEntity;
import com.sequenziatore.server.entity.Process;
import com.sequenziatore.server.entity.Step;
import com.sequenziatore.server.entity.User;
import com.sequenziatore.server.entity.Step.EnumParallelism;

/**
 *	Classe contenente tutti i test di unità dei metodi della classe ServiceModifyProcess.
 *
 *	@author 	DeSQ
 */
public class ServiceModifyProcessTest {

	/**
	 * Pulisce il database prima di iniziare ad eseguire i test.
	 * @throws Exception segnala un problema di connessione al database
	 */
	@Before
	public void clean() throws Exception
	{
		//pulizia database
	    HibernateUtil.getSession().beginTransaction();

	    //elimina le data collection
	    Query deleteDataCollection = HibernateUtil.getSession().createQuery("delete DataCollection");
	    deleteDataCollection.executeUpdate();

	    //elimina le iscrizioni ai processi
	    Query unsubscribeToProcess = HibernateUtil.getSession().createQuery("delete Subscription");
	    unsubscribeToProcess.executeUpdate();

	    //elimina i passi di tutti i processi
	    Query deleteTestStep = HibernateUtil.getSession().createQuery("delete Step");
	    deleteTestStep.executeUpdate();

	    //elimina i processi
	    Query deleteTestProcess = HibernateUtil.getSession().createQuery("delete Process");
	    deleteTestProcess.executeUpdate();

	    //elimina gli utenti registrati
	    Query deleteTestUser = HibernateUtil.getSession().createQuery("delete User");
	    deleteTestUser.executeUpdate();

	    HibernateUtil.commitTransaction();
	}

	/**
	 *	Pulisce il database quando sono terminati tutti i test.
	 * @throws Exception segnala un problema di connessione al database
	 */
	@AfterClass
	public static void finalClean() throws Exception
	{
		//pulizia database
	    HibernateUtil.getSession().beginTransaction();

	    //elimina le data collection
	    Query deleteDataCollection = HibernateUtil.getSession().createQuery("delete DataCollection");
	    deleteDataCollection.executeUpdate();

	    //elimina le iscrizioni ai processi
	    Query unsubscribeToProcess = HibernateUtil.getSession().createQuery("delete Subscription");
	    unsubscribeToProcess.executeUpdate();

	    //elimina i passi di tutti i processi
	    Query deleteTestStep = HibernateUtil.getSession().createQuery("delete Step");
	    deleteTestStep.executeUpdate();

	    //elimina i processi
	    Query deleteTestProcess = HibernateUtil.getSession().createQuery("delete Process");
	    deleteTestProcess.executeUpdate();

	    //elimina gli utenti registrati
	    Query deleteTestUser = HibernateUtil.getSession().createQuery("delete User");
	    deleteTestUser.executeUpdate();

	    HibernateUtil.commitTransaction();
	}

	/**
	 *	Test del metodo serviceOperation() che permette la modifica di un processo.
	 * @throws Exception segnala un problema di connessione al database
	 */
	@Test
	public void testServiceOperation() throws Exception {
		ServiceModifyProcess serviceModifyProcessObject = new ServiceModifyProcess();

		//creazione ambiente per l'esecuzione della query
    	HibernateUtil.getSession().beginTransaction();

    	//creazione amministratore
        User testAdmin = new User();
        testAdmin.setEmail("asd@asd.com");
        testAdmin.setIsAdmin(true);
        testAdmin.setPassword("test");
        testAdmin.setUsername("testAdmin");
        HibernateUtil.getSession().saveOrUpdate(testAdmin);
        HibernateUtil.commitTransaction();

		//creazione processo
        Process testProcess = new Process();
        testProcess.setAdmin(testAdmin);
        testProcess.setAvailable(false);
        testProcess.setDescription("Processo di test");
        testProcess.setEndSubscriptionDate(new GregorianCalendar(2020,12,31,23,59,59));
        testProcess.setClosingDate(new GregorianCalendar(2020,12,31,23,59,59));
        testProcess.setName("test");
        testProcess.setPublicationDate(new GregorianCalendar(2012,12,31,23,59,59));
        testProcess.setTotalLevel(1);

        //creazione di un passo per il processo
        Step testStep = new Step();
        testStep.setAdminVerify(false);
        testStep.setDescription("test");
        testStep.setIsGeolocation(false);
        testStep.setIsPhoto(false);
        testStep.setIsText(false);
        testStep.setLevel(1);
        testStep.setParallelism(EnumParallelism.AND);
        testStep.setIdProcess(testProcess);

        //inserimento del passo nel processo
        List<Step> testStepList = new ArrayList<Step>();
        testStepList.add(testStep);
        testProcess.setSteps(testStepList);

        //creazione della lista di entità
	    List<IEntity> iEntityList = new ArrayList<IEntity>();
	    iEntityList.add(testProcess);

	    JSONObject jsonObject = serviceModifyProcessObject.serviceOperation(iEntityList);

	    assertEquals("receivedInfo", jsonObject.get("Confirmation"));
	}

}


text:
package sun.jvm.hotspot.asm.sparc;

import sun.jvm.hotspot.asm.*;

public class SPARCSaveInstruction extends SPARCFormat3AInstruction {
    final private boolean trivial;
    public SPARCSaveInstruction(SPARCRegister rs1, ImmediateOrRegister operand2, SPARCRegister rd) {
        super("save", SAVE, rs1, operand2, rd);
        SPARCRegister G0 = SPARCRegisters.G0;
        trivial = (rs1 == G0 && operand2 == G0 && rd == G0);
    }

    public boolean isTrivial() {
        return trivial;
    }

    protected String getOperand2String() {
        StringBuffer buf = new StringBuffer();
        if (operand2.isRegister()) {
            buf.append(operand2.toString());
        } else {
            Number number = ((Immediate)operand2).getNumber();
            int value = number.intValue();
            if (value < 0) {
                buf.append("-0x");
                value = -value;
            } else {
                buf.append("0x");
            }

            buf.append(Integer.toHexString(value));
        }
        return buf.toString();
    }

    protected String getDescription() {
        return (trivial) ? getName() : super.getDescription();
    }
}


text:
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> result = new ArrayList<>();
        if (nums1.length == 0 || nums2.length == 0) return result;

        PriorityQueue<Tuple> queue = new PriorityQueue<>();
        for (int i = 0; i < nums1.length; i++) {
            queue.offer(new Tuple(i, 0, nums1[i] + nums2[0]));
        }

        while (k-- != 0 && queue.size() > 0) {
            Tuple tuple = queue.poll();
            if (tuple.y + 1 < nums2.length)
                queue.offer(new Tuple(tuple.x, tuple.y + 1, nums1[tuple.x] + nums2[tuple.y + 1]));
            result.add(new int[]{nums1[tuple.x], nums2[tuple.y]});
        }
        return result;
    }
}

class Tuple implements Comparable<Tuple> {
    public int x, y, val;

    Tuple(int x, int y, int val) {
        this.x = x;     // index of num1
        this.y = y;     // index of num2
        this.val = val;
    }

    @Override
    public int compareTo(Tuple that) {
        return this.val - that.val;
    }
}


text:
ACCEPTED

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

#### Published in
Mitt. bot. Inst. tech. Hochsch. Wien 3(2): 67 (1926)

#### Original name
Pezizella acerina Mouton, 1897

### Remarks
null