text:
Date: Tue, 05 Nov 1996 00:32:21 GMT
Server: NCSA/1.5
Content-type: text/html
Last-modified: Fri, 16 Aug 1996 15:58:20 GMT
Content-length: 13462

<title> Lecture notes - Chapter 2 - SAL</title>

 Chapter 2 -- SAL

ABOUT SAL
---------

MOTIVATION for SAL:
     hiding the details of MAL, MIPS asm. lang. (on purpose!)
     SAL code will look more like HLL code -- to make student's transition
	  easier.
     Introducing one more level of abstraction in order to postpone
	  discussion of several topics.

     HLL           SAL         assembly          machine code

     each HLL statement maps into 1 or MORE SAL instructions
     each SAL instruction maps into 1 or MORE MAL instructions

     for this course, there is actually one more layer that
     students will be given

     HLL        SAL     MAL       TAL      MIPS RISC machine code

SAL

A subset of the functionality of most high level languages --
     no records/structures
     no formal arrays (see chapter 7 for their implementation)

What is required by a programming language?
  declarations
  arithmetic operations
  conditional execution (if then else)
  looping control structures
  communication w/user. . .(write statement)

About SAL:
 -- one instruction, declaration per line
 -- comments are anything on a line following `#'
    (comments may not span lines)

DECLARATIONS
------------

  - they give information about how much memory space is needed
  - they assign a name to the memory space

  SAL has 3 basic types: integer, float (real), character
  can build other types out of these,
       for example, boolean is really an integer with only 2 defined values.

  Pascal:
       var        variablename:  type;

  C:
       type     variablename;

  SAL:
       variablename:  type value

     type is       .word      if integer
		   .byte      if character
		   .float     if real (floating point)

     value is optional -- it gives the variable an initial value

  examples:
       flag:  .word   0

       counter:   .word   0

       variable3: .word

       e:  .float   2.71828

       uservalue:    .byte

       letter:    .byte 'a'

other useful rules:
  -- one declaration per line.
  -- default initial value is 0.

DIRECTIVES
----------
  a way to give information to the assembler.

  - all directives start with `.' (period)

    examples:

	 .byte
	 .word
	 .float

	 .data       # identifies the start of the declaration section
		     #   there can be more than 1 .data section in
		     #   a program

	 .text       # identifies where instructions are
		     #   there can be more than 1 .text section in
		     #   a program

	 .asciiz  "a string.\n"  # places a string into memory
				 # and null terminates the string.

	 .ascii  "new string."   # places a string into memory
				 # WITHOUT null termination.

ARITHMETIC operations
----------------------

     SAL             Pascal             C

     move x, y       x := y;           x = y;
     add x, y, z     x := y + z;       x = y + z;
     sub x, y, z     x := y - z;       x = y - z;
     mul x, y, z     x := y * z;       x = y * z;
     div x, y, z     x := y div z;     x = y / z;
     rem x, y, z     x := y mod z;     x = y % z;

   NOTES: 1. the operation result depends on the type of the variables.
	  2. cannot increase the number of operands.
	  3. y and/or z can be IMMEDIATES

   examples:

      move  count, 0

      mult  product, mult1, mult2

      add   sum, 2, addend

NOTE:  there are other instructions that implement boolean functions,
       but we don't cover them yet.

CONDITIONAL EXECUTION
---------------------
  sometimes an instruction (or a set of instructions) should
  be executed, and sometimes it (they) shouldn't.

  HLL -- simplest form is a go-to.  (Always discouraged.)

Pascal if-then-else
  (a conditional go-to!)

   if (condition) then
       statement
   else
       statement;

C if-then-else

   if (condition)
       statement;
   else
       statement;

SAL 'ifs' and 'gotos'
--------------------------------
    SAL                  Pascal

    b label             goto label;
    bltz x, label       if x < 0 then goto label;
    bgtz x, label       if x > 0 then goto label;
    blez x, label       if x <= 0 then goto label;
    bgez x, label       if x >= 0 then goto label;
    beqz x, label       if x = 0 then goto label;
    bnez x, label       if x <> 0 then goto label;
    beq x, y, label     if x = y then goto label;
    bne x, y, label     if x <> y then goto label;
    blt x, y, label     if x < y then goto label;
    bgt x, y, label     if x > y then goto label;
    ble x, y, label     if x <= y then goto label;
    bge x, y, label     if x >= y then goto label;

EXAMPLE:
--------
  Pascal if-then-else:

       if (count < 0) then
       begin
	   count := count + 1;
       end;

  C equivalent:

       if (count < 0)
	   count = count + 1;

SAL equiv to if-then-else:

                bltz count, ifstuff
	        b endif
      ifstuff:  add count, count, 1
      endif:      # next program instruction goes here

	 -- OR --

                bgez count, endif
	        add count, count, 1
      endif:      # next program instruction goes here

    WHICH ONE OF THESE IS BETTER?

Structured loops can be built out of IF's and GOTO's
                                  (test and branch)

EXAMPLES:
---------

while loop example

  Pascal:

       while ( count > 0 ) do
       begin
	   a := a mod count;
	   count := count - 1;
       end;

  BAD STYLE Pascal:

       while: if  (count <= 0) then goto endwhile;
	      a := a mod count;
	      count := count - 1;
	      goto while;
       endwhile:

  C:

       while (count > 0) {
	   a = a % count;
	   count --;
       }

  SAL:

      while: blez  count, endwhile
             rem a, a, count
             sub count, count, 1
             b while
      endwhile:    # next program instruction goes here

repeat loop example

  Pascal:

       /* do statement until expression is TRUE */
       repeat
	   if (a  b) then
	      a := a - 1;
       until a = b;

  C:
       /* do statement while expression is TRUE */
       /*   when expression is FALSE, exit loop */
       do {
	   if (a  b)
	       a--;
       } while( a != b);

  SAL:

      repeat:    bge a, b, secondif
                 add a, a, 1
      secondif:  ble a, b, until
	         sub a, a, 1
      until:     bne repeat

while loop example
  Pascal:

           while (count < limit) and (c = d) do
	   begin
	      /* loop's code goes here */
	   end;

  C:

           while ( (count<limit) && (c==d) )
           {
	      /* loop's code goes here */
           }
  SAL:

        while:   bge count, limit, endwhile
                 bne c, d, endwhile

                 # loop's code goes here

                 b while
        endwhile:

for loop example

  Pascal:

           for i:= 3 to 8 do
           begin
               a := a + i;
           end;

  C:

	   for ( i = 3; i <= 8; i++)
	   {
	       a = a + i;
	   }

  SAL:

                 move i, 3
        for:     bgt  i, 8, endfor
                 add  a, a, i
                 add  i, i, 1
		 b for
        endfor:

COMMUNICATION WITH THE USER (I/O operations)
--------------------------------------------
     SAL              Pascal

     put x           write(x);
     get x           readln(x);
     puts 'string'   write('string');

SAL doesn't have any oddities about
testing for eoln or eof.  A carriage return is just another
character to be read or written.  It is '\n'

get  has the most irregularities!
---
  get intvariable
    places  first integer variable it "finds" into intvariable,
    then throws away the rest of the line.

    if the first value read does not match the type requested, then
    the value 0 is placed in variable intvariable.

  get charvariable
    placed the first character variable it has into charvariable

EXAMPLES:

  INPUT:

  23 abc
   -13
  1234fgh!

  SAL CODE:

     get int1        # int1 <- 23
     get int2        # int2 <- -13
     get int3        # int3 <- 1234

  OR:

     get char1       # char1 <- '2'
     get int1        # int1 <- 3, and throw away rest of line
     get char2       # char2 <- ' ', there is a space character before
		     #    the -13

  OR:

     get char1       # char1 <- '2'
     get char2       # char2 <- '3'
     get int1        # int1 <- 0, because the first value read (ignoring
		     #   the white space) is not a digit, so the type does
		     #   not match.

So, if you want to get more than one non-character value from
a single line, you must read in character by character, and
convert to whatever form is desired.  More about this in
chapter 4.

PROGRAM EXAMPLE:
----------------

# this simple program adds up 2 integers and prints their sum and products.

   .data

 prompt1:  .asciiz "Enter an integer: "
 prompt2:  .asciiz "Enter a second integer: "
 linefeed: .byte '\n'
 msg1:     .asciiz "The sum of "
 msg2:     .asciiz " and "
 msg3:     .asciiz " is "
 msg4:     .asciiz "The product of "
 int1:     .word  0
 int2:     .word  0
 sum:      .word
 product:  .word

   .text

      # get the 2 integers from user
           puts prompt1
           get int1
           put linefeed
           puts prompt2
           get int2
           put linefeed

      # calculate the sum and products
           add sum, int1, int2
           mul product, int1, int2

      # print out the sum and products
           puts msg1
           put int1
           puts msg2
           put int2
           puts msg3
           put sum
           put linefeed

           puts msg4
           put int1
           puts msg2
           put int2
           puts msg3
           put product
           put linefeed
           done

Another simple SAL example program
----------------------------------

# A SAL program to print out a multiplication table

 .data
start:    .word 0  # entered by user
finish:   .word 0  # entered by user
ii:       .word    # loop induction variable
jj:       .word    # loop induction variable
product:  .word
prompt1:  .asciiz "Enter starting value: "
prompt2:  .asciiz "Enter ending value: "
newline:  .byte '\n'
x_symbol: .byte 'X'
equals:   .byte '='
space:    .byte ' '

 .text

__start:    puts prompt1                # get user input
            get  start
            puts prompt2
            get  finish

            move ii, start
for:        bgt  ii, finish, all_done   # nested for loop to print out
            move jj, start              # the table
nested:     bgt  jj, finish, next_iter
            mul  product, ii, jj

            # print one line of table
            put  ii
            put  space
            put  x_symbol
            put  space
            put  jj
            put  space
            put  equals
            put  space
            put  product
            put  newline

            add  jj, jj, 1
            b    nested
next_iter:  add ii, ii, 1
            put  newline
            b    for

all_done:   done

PROCEDURES
----------

SAL has a rudimentary method for procedure call and return.
There is no mechanism for parameter passing or function return
values.

procedure parts:
  1. call

     SAL procedure call:
         b procname

  2. execute procedure

     procname:  #code for procedure goes here

  3. return

     "the hard part"
     could be a branch, if we had a label for the return place.

            b procname
   rtn1:     # more code here

  procname:  # procedure code here
         .
         .
         .
            b rtn1

    This does not work.  It just jumps to a different place in the
    code!  It cannot be called from more than one location.

Needed:  an ADDRESS to return to!

Convenient SAL instruction:

       la  var1, label

       la stands for Load Address

       Operation: the address implied by label is placed into var1.
       NOTE:  var1 must be declared as an integer (.word)

       Notice difference between address and contents of
       the address.

       label       address      contents
        aa:          103           6
        bb:          104           'a'
        cc:          105          2001

       The SAL instruction
	 la cc, bb
       changes the table above to be:

       label       address      contents
        aa:          103           6
        bb:          104           'a'
        cc:          105       **  104  **

For procedure call and return, save a return address
before branching to the procedure.

             la  procname_ret, rtn1
	     b procname
  rtn1:      # more code here
  .
  .
  .
  procname:  # procedure code here
             .
             .
             .
             b procname_ret

THIS STILL DOESN'T WORK!
  It branches to label procname_ret.  But, procname_ret
  is a variable!  Can't branch to a variable!
  To solve the problem, there is a special form of the b
  instruction used just for procedure return.

  b  (var1)     #parentheses identify the special form

  branches to the contents of var1, not to var1 itself.

So, the complete call/return code is:

             la  procname_ret, rtn1
	     b   procname
  rtn1:      # more code here

  .
  .
  .

             la  procname_ret, rtn2
	     b   procname
  rtn2:      # more code here
  .
  .
  .
  procname:  # procedure code here
             .
             .
             .
             b (procname_ret)


text:
The [example_test.py](example_test.py) is a heavily commented example of a test case that uses both
the RPC and P2P interfaces. If you are writing your first test, copy that file
and modify to fit your needs.

#### Coverage

Running `test_runner.py` with the `--coverage` argument tracks which RPCs are
called by the tests and prints a report of uncovered RPCs in the summary. This
can be used (along with the `--extended` argument) to find out which RPCs we
don't have test cases for.

#### Style guidelines

- Where possible, try to adhere to [PEP-8 guidelines](https://www.python.org/dev/peps/pep-0008/)
- Use a python linter like flake8 before submitting PRs to catch common style
  nits (eg trailing whitespace, unused imports, etc)
- Avoid wildcard imports where possible
- Use a module-level docstring to describe what the test is testing, and how it
  is testing it.
- When subclassing the StarwelsTestFramwork, place overrides for the
  `set_test_params()`, `add_options()` and `setup_xxxx()` methods at the top of
  the subclass, then locally-defined helper methods, then the `run_test()` method.

#### Naming guidelines

- Name the test `<area>_test.py`, where area can be one of the following:
    - `feature` for tests for full features that aren't wallet/mining/mempool, eg `feature_rbf.py`
    - `interface` for tests for other interfaces (REST, ZMQ, etc), eg `interface_rest.py`
    - `mempool` for tests for mempool behaviour, eg `mempool_reorg.py`
    - `mining` for tests for mining features, eg `mining_prioritisetransaction.py`
    - `p2p` for tests that explicitly test the p2p interface, eg `p2p_disconnect_ban.py`
    - `rpc` for tests for individual RPC methods or features, eg `rpc_listtransactions.py`
    - `wallet` for tests for wallet features, eg `wallet_keypool.py`
- use an underscore to separate words
    - exception: for tests for specific RPCs or command line options which don't include underscores, name the test after the exact RPC or argument name, eg `rpc_decodescript.py`, not `rpc_decode_script.py`
- Don't use the redundant word `test` in the name, eg `interface_zmq.py`, not `interface_zmq_test.py`

#### General test-writing advice

- Set `self.num_nodes` to the minimum number of nodes necessary for the test.
  Having additional unrequired nodes adds to the execution time of the test as
  well as memory/CPU/disk requirements (which is important when running tests in
  parallel or on Travis).
- Avoid stop-starting the nodes multiple times during the test if possible. A
  stop-start takes several seconds, so doing it several times blows up the
  runtime of the test.
- Set the `self.setup_clean_chain` variable in `set_test_params()` to control whether
  or not to use the cached data directories. The cached data directories
  contain a 200-block pre-mined blockchain and wallets for four nodes. Each node
  has 25 mature blocks (25x50=1250 USDH) in its wallet.
- When calling RPCs with lots of arguments, consider using named keyword
  arguments instead of positional arguments to make the intent of the call
  clear to readers.

#### RPC and P2P definitions

Test writers may find it helpful to refer to the definitions for the RPC and
P2P messages. These can be found in the following source files:

- `/src/rpc/*` for RPCs
- `/src/wallet/rpc*` for wallet RPCs
- `ProcessMessage()` in `/src/net_processing.cpp` for parsing P2P messages

#### Using the P2P interface

- `mininode.py` contains all the definitions for objects that pass
over the network (`CBlock`, `CTransaction`, etc, along with the network-level
wrappers for them, `msg_block`, `msg_tx`, etc).

- P2P tests have two threads. One thread handles all network communication
with the starwelsd(s) being tested (using python's asyncore package); the other
implements the test logic.

- `P2PConnection` is the class used to connect to a starwelsd.  `P2PInterface`
contains the higher level logic for processing P2P payloads and connecting to
the Starwels node application logic. For custom behaviour, subclass the
P2PInterface object and override the callback methods.

- Call `network_thread_start()` after all `P2PInterface` objects are created to
start the networking thread.  (Continue with the test logic in your existing
thread.)

- Can be used to write tests where specific P2P protocol behavior is tested.
Examples tests are `p2p_unrequested_blocks.py`, `p2p_compactblocks.py`.

#### Comptool

- Comptool is a Testing framework for writing tests that compare the block/tx acceptance
behavior of a starwelsd against 1 or more other starwelsd instances. It should not be used
to write static tests with known outcomes, since that type of test is easier to write and
maintain using the standard StarwelsTestFramework.

- Set the `num_nodes` variable (defined in `ComparisonTestFramework`) to start up
1 or more nodes.  If using 1 node, then `--testbinary` can be used as a command line
option to change the starwelsd binary used by the test.  If using 2 or more nodes,
then `--refbinary` can be optionally used to change the starwelsd that will be used
on nodes 2 and up.

- Implement a (generator) function called `get_tests()` which yields `TestInstance`s.
Each `TestInstance` consists of:
  - A list of `[object, outcome, hash]` entries
    * `object` is a `CBlock`, `CTransaction`, or
    `CBlockHeader`.  `CBlock`'s and `CTransaction`'s are tested for
    acceptance.  `CBlockHeader`s can be used so that the test runner can deliver
    complete headers-chains when requested from the starwelsd, to allow writing
    tests where blocks can be delivered out of order but still processed by
    headers-first starwelsd's.
    * `outcome` is `True`, `False`, or `None`.  If `True`
    or `False`, the tip is compared with the expected tip -- either the
    block passed in, or the hash specified as the optional 3rd entry.  If
    `None` is specified, then the test will compare all the starwelsd's
    being tested to see if they all agree on what the best tip is.
    * `hash` is the block hash of the tip to compare against. Optional to
    specify; if left out then the hash of the block passed in will be used as
    the expected tip.  This allows for specifying an expected tip while testing
    the handling of either invalid blocks or blocks delivered out of order,
    which complete a longer chain.
  - `sync_every_block`: `True/False`.  If `False`, then all blocks
    are inv'ed together, and the test runner waits until the node receives the
    last one, and tests only the last block for tip acceptance using the
    outcome and specified tip.  If `True`, then each block is tested in
    sequence and synced (this is slower when processing many blocks).
  - `sync_every_transaction`: `True/False`.  Analogous to
    `sync_every_block`, except if the outcome on the last tx is "None",
    then the contents of the entire mempool are compared across all starwelsd
    connections.  If `True` or `False`, then only the last tx's
    acceptance is tested against the given outcome.

- For examples of tests written in this framework, see
  `p2p_invalid_block.py` and `feature_block.py`.

### test-framework modules

#### [test_framework/authproxy.py](test_framework/authproxy.py)
Taken from the [python-starwelsrpc repository](https://github.com/jgarzik/python-bitcoinrpc).

#### [test_framework/test_framework.py](test_framework/test_framework.py)
Base class for functional tests.

#### [test_framework/util.py](test_framework/util.py)
Generally useful functions.

#### [test_framework/mininode.py](test_framework/mininode.py)
Basic code to support P2P connectivity to a starwelsd.

#### [test_framework/comptool.py](test_framework/comptool.py)
Framework for comparison-tool style, P2P tests.

#### [test_framework/script.py](test_framework/script.py)
Utilities for manipulating transaction scripts (originally from python-starwelslib)

#### [test_framework/blockstore.py](test_framework/blockstore.py)
Implements disk-backed block and tx storage.

#### [test_framework/key.py](test_framework/key.py)
Wrapper around OpenSSL EC_Key (originally from python-starwelslib)

#### [test_framework/bignum.py](test_framework/bignum.py)
Helpers for script.py

#### [test_framework/blocktools.py](test_framework/blocktools.py)
Helper functions for creating blocks and transactions.

redpajama_set_name: RedPajamaGithub


text:
const _                         = require('lodash');
const Stream                    = require('mithril/stream');
const Mixins                    = require('models/mixins/model_mixins');
const Routes                    = require('gen/js-routes');
const CrudMixins                = require('models/mixins/crud_mixins');
const PluggableInstanceSettings = require('models/shared/plugin_infos/pluggable_instance_settings');
const Capabilities              = require('models/shared/plugin_infos/capabilities');
const About                     = require('models/shared/plugin_infos/about');

const PluginInfos = function (data) {
  Mixins.HasMany.call(this, {
    factory:    PluginInfos.PluginInfo.createByType,
    as:         'PluginInfo',
    collection: data,
    uniqueOn:   'id'
  });

  this.findById = function (id) {
    return this.findPluginInfo((pi) => pi.id() === id);
  };

  this.filterByType = function (type) {
    return new PluginInfos(this.filterPluginInfo((pi) => pi.type() === type));
  };

  this.pluggableTasksTypes = function () {
    const pluggableTasks = {};
    this.filterByType('task').eachPluginInfo((pluginInfo) => {
      pluggableTasks[pluginInfo.id()] = {description: pluginInfo.id()};
    });

    return pluggableTasks;
  };

};

PluginInfos.API_VERSION = 'v3';

CrudMixins.Index({
  type:     PluginInfos,
  indexUrl: Routes.apiv3AdminPluginInfoIndexPath(),
  version:  PluginInfos.API_VERSION,
  dataPath: '_embedded.plugin_info'
});

PluginInfos.PluginInfo = function (type, {id, version, about, imageUrl}) {
  this.constructor.modelType = 'pluginInfo';
  this.parent                = Mixins.GetterSetter();
  Mixins.HasUUID.call(this);

  this.type = Stream(type);

  this.id       = Stream(id);
  this.version  = Stream(version);
  this.about    = Stream(about);
  this.imageUrl = Stream(imageUrl);
};

PluginInfos.PluginInfo.Authentication = function (data) {
  PluginInfos.PluginInfo.call(this, "authentication", data);
};

PluginInfos.PluginInfo.Authentication.fromJSON = (data = {}) => new PluginInfos.PluginInfo.Authentication({
  id:       data.id,
  version:  data.version,
  about:    About.fromJSON(data.about),
  imageUrl: _.get(data, '_links.image.href')
});

PluginInfos.PluginInfo.Notification = function (data) {
  PluginInfos.PluginInfo.call(this, "notification", data);
};

PluginInfos.PluginInfo.Notification.fromJSON = (data = {}) => new PluginInfos.PluginInfo.Notification({
  id:       data.id,
  version:  data.version,
  about:    About.fromJSON(data.about),
  imageUrl: _.get(data, '_links.image.href')
});

PluginInfos.PluginInfo.PackageRepository = function (data) {
  PluginInfos.PluginInfo.call(this, "package-repository", data);

  this.packageSettings    = Stream(data.packageSettings);
  this.repositorySettings = Stream(data.repositorySettings);
};

PluginInfos.PluginInfo.PackageRepository.fromJSON = (data = {}) => new PluginInfos.PluginInfo.PackageRepository({
  id:                 data.id,
  version:            data.version,
  about:              About.fromJSON(data.about),
  packageSettings:    PluggableInstanceSettings.fromJSON(data.package_settings),
  repositorySettings: PluggableInstanceSettings.fromJSON(data.repository_settings),
  imageUrl:           _.get(data, '_links.image.href')
});

PluginInfos.PluginInfo.Task = function (data) {
  PluginInfos.PluginInfo.call(this, "task", data);

  this.taskSettings = Stream(data.taskSettings);
};

PluginInfos.PluginInfo.Task.fromJSON = (data = {}) => new PluginInfos.PluginInfo.Task({
  id:           data.id,
  version:      data.version,
  about:        About.fromJSON(data.about),
  taskSettings: PluggableInstanceSettings.fromJSON(data.task_settings),
  imageUrl:     _.get(data, '_links.image.href'),
});

PluginInfos.PluginInfo.SCM = function (data) {
  PluginInfos.PluginInfo.call(this, "scm", data);

  this.scmSettings = Stream(data.scmSettings);
};

PluginInfos.PluginInfo.SCM.fromJSON = (data = {}) => new PluginInfos.PluginInfo.SCM({
  id:          data.id,
  version:     data.version,
  about:       About.fromJSON(data.about),
  scmSettings: PluggableInstanceSettings.fromJSON(data.scm_settings),
  imageUrl:    _.get(data, '_links.image.href'),
});

PluginInfos.PluginInfo.Authorization = function (data) {
  PluginInfos.PluginInfo.call(this, "authorization", data);

  this.authConfigSettings = Stream(data.authConfigSettings);
  this.roleSettings       = Stream(data.roleSettings);
  this.capabilities       = Stream(data.capabilities);

};

PluginInfos.PluginInfo.Authorization.fromJSON = (data = {}) => new PluginInfos.PluginInfo.Authorization({
  id:                 data.id,
  version:            data.version,
  about:              About.fromJSON(data.about),
  authConfigSettings: PluggableInstanceSettings.fromJSON(data.auth_config_settings),
  roleSettings:       PluggableInstanceSettings.fromJSON(data.role_settings),
  capabilities:       Capabilities.fromJSON(data.capabilities),
  imageUrl:           _.get(data, '_links.image.href'),
});

PluginInfos.PluginInfo.ElasticAgent = function (data) {
  PluginInfos.PluginInfo.call(this, "elastic-agent", data);
  this.profileSettings = Stream(data.profileSettings);
};

PluginInfos.PluginInfo.ElasticAgent.fromJSON = (data = {}) => new PluginInfos.PluginInfo.ElasticAgent({
  id:              data.id,
  version:         data.version,
  about:           About.fromJSON(data.about),
  profileSettings: PluggableInstanceSettings.fromJSON(data.profile_settings),
  imageUrl:        _.get(data, '_links.image.href'),
});

PluginInfos.PluginInfo.createByType = ({type}) => new PluginInfos.Types[type]({});

PluginInfos.PluginInfo.fromJSON = (data = {}) => PluginInfos.Types[data.type].fromJSON(data);

PluginInfos.Types = {
  'authentication':     PluginInfos.PluginInfo.Authentication,
  'authorization':      PluginInfos.PluginInfo.Authorization,
  'notification':       PluginInfos.PluginInfo.Notification,
  'elastic-agent':      PluginInfos.PluginInfo.ElasticAgent,
  'package-repository': PluginInfos.PluginInfo.PackageRepository,
  'task':               PluginInfos.PluginInfo.Task,
  'scm':                PluginInfos.PluginInfo.SCM,
};

Mixins.fromJSONCollection({
  parentType: PluginInfos,
  childType:  PluginInfos.PluginInfo,
  via:        'addPluginInfo'
});

module.exports = PluginInfos;


text:
typedef struct profile_t
{
    // Inline the integers to avoid having to deal with pointer lifetime:
    size_t material_length;
    unsigned long long opslimit;
    unsigned long long memlimit;

    // These are always set to global pointers to PROFILE_20##_* constants:
    char * profile_name;
    char * username_salt;
    char * openssh_salt;
    char * openpgp_salt;

    unsigned char * material;

    // Inline these to keep them in the sodium_malloc() buffer:
    char passphrase[256];
    char username[90];

    char openssh_secret[crypto_sign_ed25519_SECRETKEYBYTES];
    // Note that PGP stores the seed ("d") and computes the actual private key
    // for every signature. Internally it just stores "d".
    unsigned char openpgp_secret[crypto_sign_ed25519_SEEDBYTES];

    char openssh_public[crypto_sign_ed25519_PUBLICKEYBYTES];
    unsigned char openpgp_public[crypto_sign_ed25519_PUBLICKEYBYTES];
} profile_t;

bool is_valid_profile_name(const char *profile_name);

struct profile_t * generate_profile(const char *profile_name, const char *username, const char *passphrase);

bool generate_openssh_keypair(struct profile_t * profile);
bool generate_openpgp_keypair(struct profile_t * profile);

bool free_profile_t(struct profile_t * profile);

#endif


text:
package com.android.volley;

import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.test.UiThreadTest;
import android.test.suitebuilder.annotation.LargeTest;

import com.android.volley.Request.Priority;
import com.android.volley.mock.MockNetwork;
import com.android.volley.mock.MockRequest;
import com.android.volley.toolbox.NoCache;
import com.android.volley.utils.CacheTestUtils;
import com.android.volley.utils.ImmediateResponseDelivery;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@LargeTest
public class RequestQueueTest extends InstrumentationTestCase {
    private ResponseDelivery mDelivery;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mDelivery = new ImmediateResponseDelivery();
    }

    /**
     * Make a list of requests with random priorities.
     *
     * @param count Number of requests to make
     */
    private List<MockRequest> makeRequests(int count) {
        Request.Priority[] allPriorities = Request.Priority.values();
        Random random = new Random();

        List<MockRequest> requests = new ArrayList<MockRequest>();
        for (int i = 0; i < count; i++) {
            MockRequest request = new MockRequest();
            Request.Priority priority = allPriorities[random.nextInt(allPriorities.length)];
            request.setCacheKey(String.valueOf(i));
            request.setPriority(priority);
            requests.add(request);
        }
        return requests;
    }

    @UiThreadTest
    public void testAdd_requestProcessedInCorrectOrder() throws Exception {
        int requestsToMake = 100;

        OrderCheckingNetwork network = new OrderCheckingNetwork();
        RequestQueue queue = new RequestQueue(new NoCache(), network, 1, mDelivery);

        for (Request<?> request : makeRequests(requestsToMake)) {
            queue.add(request);
        }

        network.setExpectedRequests(requestsToMake);
        queue.start();
        network.waitUntilExpectedDone(2000); // 2 seconds
        queue.stop();
    }

    public void testAdd_dedupeByCacheKey() throws Exception {
        OrderCheckingNetwork network = new OrderCheckingNetwork();
        final AtomicInteger parsed = new AtomicInteger();
        final AtomicInteger delivered = new AtomicInteger();
        // Enqueue 2 requests with the same cache key. The first request takes 1.5s. Assert that the
        // second request is only handled after the first one has been parsed and delivered.
        DelayedRequest req1 = new DelayedRequest(1500, parsed, delivered);
        DelayedRequest req2 = new DelayedRequest(0, parsed, delivered) {
            @Override
            protected Response<Object> parseNetworkResponse(NetworkResponse response) {
                assertEquals(1, parsed.get());  // req1 must have been parsed.
                assertEquals(1, delivered.get());  // req1 must have been parsed.
                return super.parseNetworkResponse(response);
            }
        };
        network.setExpectedRequests(2);
        RequestQueue queue = new RequestQueue(new NoCache(), network, 3, mDelivery);
        queue.add(req1);
        queue.add(req2);
        queue.start();
        network.waitUntilExpectedDone(2000);
        queue.stop();
    }

    public void testCancelAll_onlyCorrectTag() throws Exception {
        MockNetwork network = new MockNetwork();
        RequestQueue queue = new RequestQueue(new NoCache(), network, 3, mDelivery);
        Object tagA = new Object();
        Object tagB = new Object();
        MockRequest req1 = new MockRequest();
        req1.setTag(tagA);
        MockRequest req2 = new MockRequest();
        req2.setTag(tagB);
        MockRequest req3 = new MockRequest();
        req3.setTag(tagA);
        MockRequest req4 = new MockRequest();
        req4.setTag(tagA);

        queue.add(req1); // A
        queue.add(req2); // B
        queue.add(req3); // A
        queue.cancelAll(tagA);
        queue.add(req4); // A

        assertTrue(req1.cancel_called); // A cancelled
        assertFalse(req2.cancel_called); // B not cancelled
        assertTrue(req3.cancel_called); // A cancelled
        assertFalse(req4.cancel_called); // A added after cancel not cancelled
    }

    private class OrderCheckingNetwork implements Network {
        private Priority mLastPriority = Priority.IMMEDIATE;
        private int mLastSequence = -1;
        private Semaphore mSemaphore;

        public void setExpectedRequests(int expectedRequests) {
            // Leave one permit available so the waiter can find it.
            expectedRequests--;
            mSemaphore = new Semaphore(-expectedRequests);
        }

        public void waitUntilExpectedDone(long timeout) throws InterruptedException, TimeoutError {
            if (mSemaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS) == false) {
                throw new TimeoutError();
            }
        }

        @Override
        public NetworkResponse performRequest(Request<?> request) {
            Priority thisPriority = request.getPriority();
            int thisSequence = request.getSequence();

            int priorityDiff = thisPriority.compareTo(mLastPriority);

            // Should never experience a higher priority after a lower priority
            assertFalse(priorityDiff > 0);

            // If we're not transitioning to a new priority block, check sequence numbers
            if (priorityDiff == 0) {
                assertTrue(thisSequence > mLastSequence);
            }
            mLastSequence = thisSequence;
            mLastPriority = thisPriority;

            mSemaphore.release();
            return new NetworkResponse(new byte[16]);
        }
    }

    private class DelayedRequest extends Request<Object> {
        private final long mDelayMillis;
        private final AtomicInteger mParsedCount;
        private final AtomicInteger mDeliveredCount;

        public DelayedRequest(long delayMillis, AtomicInteger parsed, AtomicInteger delivered) {
            super("http://buganizer/", null);
            mDelayMillis = delayMillis;
            mParsedCount = parsed;
            mDeliveredCount = delivered;
        }

        @Override
        protected Response<Object> parseNetworkResponse(NetworkResponse response) {
            mParsedCount.incrementAndGet();
            SystemClock.sleep(mDelayMillis);
            return Response.success(new Object(), CacheTestUtils.makeRandomCacheEntry(null));
        }

        @Override
        protected void deliverResponse(Object response) {
            mDeliveredCount.incrementAndGet();
        }
    }

}


text:
;; Unspec defintions.
;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
;; Contributed by ARM Ltd.

;; This file is part of GCC.

;; GCC is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.

;; GCC is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;; License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GCC; see the file COPYING3.  If not see
;; <http://www.gnu.org/licenses/>.

;; UNSPEC Usage:
;; Note: sin and cos are no-longer used.
;; Unspec enumerators for Neon are defined in neon.md.
;; Unspec enumerators for iwmmxt2 are defined in iwmmxt2.md

(define_c_enum "unspec" [
  UNSPEC_PUSH_MULT      ; `push multiple' operation:
                        ;   operand 0 is the first register,
                        ;   subsequent registers are in parallel (use ...)
                        ;   expressions.
  UNSPEC_PIC_SYM        ; A symbol that has been treated properly for pic
                        ; usage, that is, we will add the pic_register
                        ; value to it before trying to dereference it.
  UNSPEC_PIC_BASE       ; Add PC and all but the last operand together,
                        ; The last operand is the number of a PIC_LABEL
                        ; that points at the containing instruction.
  UNSPEC_PRLG_STK       ; A special barrier that prevents frame accesses
                        ; being scheduled before the stack adjustment insn.
  UNSPEC_REGISTER_USE   ; As USE insns are not meaningful after reload,
                        ; this unspec is used to prevent the deletion of
                        ; instructions setting registers for EH handling
                        ; and stack frame generation.  Operand 0 is the
                        ; register to "use".
  UNSPEC_CHECK_ARCH     ; Set CCs to indicate 26-bit or 32-bit mode.
  UNSPEC_WSHUFH         ; Used by the intrinsic form of the iWMMXt WSHUFH instruction.
  UNSPEC_WACC           ; Used by the intrinsic form of the iWMMXt WACC instruction.
  UNSPEC_TMOVMSK        ; Used by the intrinsic form of the iWMMXt TMOVMSK instruction.
  UNSPEC_WSAD           ; Used by the intrinsic form of the iWMMXt WSAD instruction.
  UNSPEC_WSADZ          ; Used by the intrinsic form of the iWMMXt WSADZ instruction.
  UNSPEC_WMACS          ; Used by the intrinsic form of the iWMMXt WMACS instruction.
  UNSPEC_WMACU          ; Used by the intrinsic form of the iWMMXt WMACU instruction.
  UNSPEC_WMACSZ         ; Used by the intrinsic form of the iWMMXt WMACSZ instruction.
  UNSPEC_WMACUZ         ; Used by the intrinsic form of the iWMMXt WMACUZ instruction.
  UNSPEC_CLRDI          ; Used by the intrinsic form of the iWMMXt CLRDI instruction.
  UNSPEC_WALIGNI        ; Used by the intrinsic form of the iWMMXt WALIGN instruction.
  UNSPEC_TLS            ; A symbol that has been treated properly for TLS usage.
  UNSPEC_PIC_LABEL      ; A label used for PIC access that does not appear in the
                        ; instruction stream.
  UNSPEC_PIC_OFFSET     ; A symbolic 12-bit OFFSET that has been treated
                        ; correctly for PIC usage.
  UNSPEC_GOTSYM_OFF     ; The offset of the start of the GOT from a
                        ; a given symbolic address.
  UNSPEC_THUMB1_CASESI  ; A Thumb1 compressed dispatch-table call.
  UNSPEC_RBIT           ; rbit operation.
  UNSPEC_SYMBOL_OFFSET  ; The offset of the start of the symbol from
                        ; another symbolic address.
  UNSPEC_MEMORY_BARRIER ; Represent a memory barrier.
  UNSPEC_UNALIGNED_LOAD	; Used to represent ldr/ldrh instructions that access
			; unaligned locations, on architectures which support
			; that.
  UNSPEC_UNALIGNED_STORE ; Same for str/strh.
  UNSPEC_PIC_UNIFIED    ; Create a common pic addressing form.
  UNSPEC_LL		; Represent an unpaired load-register-exclusive.
  UNSPEC_VRINTZ         ; Represent a float to integral float rounding
                        ; towards zero.
  UNSPEC_VRINTP         ; Represent a float to integral float rounding
                        ; towards +Inf.
  UNSPEC_VRINTM         ; Represent a float to integral float rounding
                        ; towards -Inf.
  UNSPEC_VRINTR         ; Represent a float to integral float rounding
                        ; FPSCR rounding mode.
  UNSPEC_VRINTX         ; Represent a float to integral float rounding
                        ; FPSCR rounding mode and signal inexactness.
  UNSPEC_VRINTA         ; Represent a float to integral float rounding
                        ; towards nearest, ties away from zero.
])

(define_c_enum "unspec" [
  UNSPEC_WADDC		; Used by the intrinsic form of the iWMMXt WADDC instruction.
  UNSPEC_WABS		; Used by the intrinsic form of the iWMMXt WABS instruction.
  UNSPEC_WQMULWMR	; Used by the intrinsic form of the iWMMXt WQMULWMR instruction.
  UNSPEC_WQMULMR	; Used by the intrinsic form of the iWMMXt WQMULMR instruction.
  UNSPEC_WQMULWM	; Used by the intrinsic form of the iWMMXt WQMULWM instruction.
  UNSPEC_WQMULM		; Used by the intrinsic form of the iWMMXt WQMULM instruction.
  UNSPEC_WQMIAxyn	; Used by the intrinsic form of the iWMMXt WMIAxyn instruction.
  UNSPEC_WQMIAxy	; Used by the intrinsic form of the iWMMXt WMIAxy instruction.
  UNSPEC_TANDC		; Used by the intrinsic form of the iWMMXt TANDC instruction.
  UNSPEC_TORC		; Used by the intrinsic form of the iWMMXt TORC instruction.
  UNSPEC_TORVSC		; Used by the intrinsic form of the iWMMXt TORVSC instruction.
  UNSPEC_TEXTRC		; Used by the intrinsic form of the iWMMXt TEXTRC instruction.
])

;; UNSPEC_VOLATILE Usage:

(define_c_enum "unspecv" [
  VUNSPEC_BLOCKAGE      ; `blockage' insn to prevent scheduling across an
                        ;   insn in the code.
  VUNSPEC_EPILOGUE      ; `epilogue' insn, used to represent any part of the
                        ;   instruction epilogue sequence that isn't expanded
                        ;   into normal RTL.  Used for both normal and sibcall
                        ;   epilogues.
  VUNSPEC_THUMB1_INTERWORK ; `prologue_thumb1_interwork' insn, used to swap
			;   modes from arm to thumb.
  VUNSPEC_ALIGN         ; `align' insn.  Used at the head of a minipool table
                        ;   for inlined constants.
  VUNSPEC_POOL_END      ; `end-of-table'.  Used to mark the end of a minipool
                        ;   table.
  VUNSPEC_POOL_1        ; `pool-entry(1)'.  An entry in the constant pool for
                        ;   an 8-bit object.
  VUNSPEC_POOL_2        ; `pool-entry(2)'.  An entry in the constant pool for
                        ;   a 16-bit object.
  VUNSPEC_POOL_4        ; `pool-entry(4)'.  An entry in the constant pool for
                        ;   a 32-bit object.
  VUNSPEC_POOL_8        ; `pool-entry(8)'.  An entry in the constant pool for
                        ;   a 64-bit object.
  VUNSPEC_POOL_16       ; `pool-entry(16)'.  An entry in the constant pool for
                        ;   a 128-bit object.
  VUNSPEC_TMRC          ; Used by the iWMMXt TMRC instruction.
  VUNSPEC_TMCR          ; Used by the iWMMXt TMCR instruction.
  VUNSPEC_ALIGN8        ; 8-byte alignment version of VUNSPEC_ALIGN
  VUNSPEC_WCMP_EQ       ; Used by the iWMMXt WCMPEQ instructions
  VUNSPEC_WCMP_GTU      ; Used by the iWMMXt WCMPGTU instructions
  VUNSPEC_WCMP_GT       ; Used by the iwMMXT WCMPGT instructions
  VUNSPEC_EH_RETURN     ; Use to override the return address for exception
                        ; handling.
  VUNSPEC_ATOMIC_CAS	; Represent an atomic compare swap.
  VUNSPEC_ATOMIC_XCHG	; Represent an atomic exchange.
  VUNSPEC_ATOMIC_OP	; Represent an atomic operation.
  VUNSPEC_LL		; Represent a load-register-exclusive.
  VUNSPEC_SC		; Represent a store-register-exclusive.
])

;; Enumerators for NEON unspecs.
(define_c_enum "unspec" [
  UNSPEC_ASHIFT_SIGNED
  UNSPEC_ASHIFT_UNSIGNED
  UNSPEC_LOAD_COUNT
  UNSPEC_VABD
  UNSPEC_VABDL
  UNSPEC_VADD
  UNSPEC_VADDHN
  UNSPEC_VADDL
  UNSPEC_VADDW
  UNSPEC_VBSL
  UNSPEC_VCAGE
  UNSPEC_VCAGT
  UNSPEC_VCEQ
  UNSPEC_VCGE
  UNSPEC_VCGEU
  UNSPEC_VCGT
  UNSPEC_VCGTU
  UNSPEC_VCLS
  UNSPEC_VCONCAT
  UNSPEC_VCVT
  UNSPEC_VCVT_N
  UNSPEC_VEXT
  UNSPEC_VHADD
  UNSPEC_VHSUB
  UNSPEC_VLD1
  UNSPEC_VLD1_LANE
  UNSPEC_VLD2
  UNSPEC_VLD2_DUP
  UNSPEC_VLD2_LANE
  UNSPEC_VLD3
  UNSPEC_VLD3A
  UNSPEC_VLD3B
  UNSPEC_VLD3_DUP
  UNSPEC_VLD3_LANE
  UNSPEC_VLD4
  UNSPEC_VLD4A
  UNSPEC_VLD4B
  UNSPEC_VLD4_DUP
  UNSPEC_VLD4_LANE
  UNSPEC_VMAX
  UNSPEC_VMIN
  UNSPEC_VMLA
  UNSPEC_VMLAL
  UNSPEC_VMLA_LANE
  UNSPEC_VMLAL_LANE
  UNSPEC_VMLS
  UNSPEC_VMLSL
  UNSPEC_VMLS_LANE
  UNSPEC_VMLSL_LANE
  UNSPEC_VMOVL
  UNSPEC_VMOVN
  UNSPEC_VMUL
  UNSPEC_VMULL
  UNSPEC_VMUL_LANE
  UNSPEC_VMULL_LANE
  UNSPEC_VPADAL
  UNSPEC_VPADD
  UNSPEC_VPADDL
  UNSPEC_VPMAX
  UNSPEC_VPMIN
  UNSPEC_VPSMAX
  UNSPEC_VPSMIN
  UNSPEC_VPUMAX
  UNSPEC_VPUMIN
  UNSPEC_VQABS
  UNSPEC_VQADD
  UNSPEC_VQDMLAL
  UNSPEC_VQDMLAL_LANE
  UNSPEC_VQDMLSL
  UNSPEC_VQDMLSL_LANE
  UNSPEC_VQDMULH
  UNSPEC_VQDMULH_LANE
  UNSPEC_VQDMULL
  UNSPEC_VQDMULL_LANE
  UNSPEC_VQMOVN
  UNSPEC_VQMOVUN
  UNSPEC_VQNEG
  UNSPEC_VQSHL
  UNSPEC_VQSHL_N
  UNSPEC_VQSHLU_N
  UNSPEC_VQSHRN_N
  UNSPEC_VQSHRUN_N
  UNSPEC_VQSUB
  UNSPEC_VRECPE
  UNSPEC_VRECPS
  UNSPEC_VREV16
  UNSPEC_VREV32
  UNSPEC_VREV64
  UNSPEC_VRSQRTE
  UNSPEC_VRSQRTS
  UNSPEC_VSHL
  UNSPEC_VSHLL_N
  UNSPEC_VSHL_N
  UNSPEC_VSHR_N
  UNSPEC_VSHRN_N
  UNSPEC_VSLI
  UNSPEC_VSRA_N
  UNSPEC_VSRI
  UNSPEC_VST1
  UNSPEC_VST1_LANE
  UNSPEC_VST2
  UNSPEC_VST2_LANE
  UNSPEC_VST3
  UNSPEC_VST3A
  UNSPEC_VST3B
  UNSPEC_VST3_LANE
  UNSPEC_VST4
  UNSPEC_VST4A
  UNSPEC_VST4B
  UNSPEC_VST4_LANE
  UNSPEC_VSTRUCTDUMMY
  UNSPEC_VSUB
  UNSPEC_VSUBHN
  UNSPEC_VSUBL
  UNSPEC_VSUBW
  UNSPEC_VTBL
  UNSPEC_VTBX
  UNSPEC_VTRN1
  UNSPEC_VTRN2
  UNSPEC_VTST
  UNSPEC_VUZP1
  UNSPEC_VUZP2
  UNSPEC_VZIP1
  UNSPEC_VZIP2
  UNSPEC_MISALIGNED_ACCESS
  UNSPEC_VCLE
  UNSPEC_VCLT
  UNSPEC_NVRINTZ
  UNSPEC_NVRINTP
  UNSPEC_NVRINTM
  UNSPEC_NVRINTX
  UNSPEC_NVRINTA
  UNSPEC_NVRINTN
])


text:
#ifndef LEELOO_PORT_INTERVAL_H
#define LEELOO_PORT_INTERVAL_H

#include <leeloo/exports.h>
#include <leeloo/port.h>
#include <leeloo/interval.h>

namespace leeloo {

class port_interval: public interval<uint32_t>
{
public:
	using interval<uint32_t>::interval;
	using interval<uint32_t>::operator=;

public:
	inline port port_lower() const { return port(lower()); }

	// WARNING: here we show the interval as a closed one!
	// That's why we can't just do
	// typedef port_interval interval<uint32_t>
	// TODO: we should try to use closed intervals internally
	// and check the performance difference
	inline port port_upper() const { return port(upper() - 1); }
};

} // leeloo

#endif


text:
"""Search Engine Keywords Highlighter"""
__version__ = '0.4'
__license__ = 'BSD License'

__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'

__url__ = 'https://github.com/Fantomas42/django-sekh'


text:
package com.pr.carjoin.adapters;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.pr.carjoin.Constants;
import com.pr.carjoin.R;
import com.pr.carjoin.Util;
import com.pr.carjoin.pojos.Trip;
import com.pr.carjoin.pojos.TripQueue;
import com.pr.carjoin.pojos.TripQueueMap;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by vishnu on 29/3/17.
 */

public class TripsRecyclerAdapter extends RecyclerView.Adapter<TripsRecyclerAdapter.ViewHolder> implements View.OnClickListener {
    private static final String LOG_LABEL = "adapters.TripsRecyclerAdapter";
    private final HashMap<Trip, TripQueueMap> tripTripQueueMapHashMap;
    private final ArrayList<Trip> trips;
    private static final String DATE_TIME_FORMAT = "dd:MM:yy HH:mm";
    private final WeakReference<Activity> activityWeakReference;

    public TripsRecyclerAdapter(Activity activity, HashMap<Trip, TripQueueMap> tripTripQueueMapHashMap) {
        this.activityWeakReference = new WeakReference<Activity>(activity);
        this.tripTripQueueMapHashMap = tripTripQueueMapHashMap;
        this.trips = new ArrayList<>(tripTripQueueMapHashMap.keySet());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.single_trip_view, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final Trip trip = trips.get(holder.getAdapterPosition());
        TripQueueMap tripQueueMap = tripTripQueueMapHashMap.get(trip);
        final Context context = holder.getImageView().getContext();
        Glide.with(holder.getImageView().getContext()).load(trip.owner.photoURL).into(holder.getImageView());
        holder.getUserName().setText(trip.owner.name);
        holder.getUserEmail().setText(trip.owner.email);
        holder.getStartDate().append(" : " + new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault())
                .format(new Date(trip.beginDateTimeMills)));
        holder.getEndDate().append("   : " + new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault())
                .format(new Date(trip.endDateTimeMills)));

        TripQueue tripQueue = checkIfUserAlreadyExistsInTripQueue(tripQueueMap);
        if (tripQueue != null) {
            switch (tripQueue.status) {
                case Constants.PENDING:
                    holder.getRequest().setText(context.getString(R.string.string_pending));
                    break;
                case Constants.ACCEPTED:
                    holder.getRequest().setText(context.getString(R.string.string_accepted));
                    break;
                case Constants.REJECTED:
                    holder.getRequest().setText(context.getString(R.string.string_rejected));
                    break;
            }
        } else {
            holder.getRequest().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    v.setOnClickListener(null);
                    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(Util.TRIP_QUEUE)
                            .child(trip.id).child(firebaseUser.getUid());
                    TripQueue newTripQueue = new TripQueue();
                    newTripQueue.name = firebaseUser.getDisplayName();
                    newTripQueue.status = Constants.PENDING;
                    newTripQueue.type = Constants.COMMUTER;
                    databaseReference.setValue(newTripQueue).addOnCompleteListener(activityWeakReference.get(), new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                ((Button) v).setText(context.getString(R.string.string_pending));
                            }
                        }
                    });
                }
            });
        }
    }

    private TripQueue checkIfUserAlreadyExistsInTripQueue(HashMap<String, TripQueue> tripQueueHashMap) {
        if (tripQueueHashMap != null && tripQueueHashMap.size() > 0) {
            String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
            if (tripQueueHashMap.keySet().contains(userId)) {
                return tripQueueHashMap.get(userId);
            }
        }
        return null;
    }

    @Override
    public int getItemCount() {
        return trips.size();
    }

    @Override
    public void onClick(View v) {

    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView imageView;
        private Button request;
        private TextView userName, startDate, endDate, userEmail;

        public ViewHolder(View itemView) {
            super(itemView);

            imageView = (CircleImageView) itemView.findViewById(R.id.user_photo);
            request = (Button) itemView.findViewById(R.id.status);
            userName = (TextView) itemView.findViewById(R.id.user_name);
            startDate = (TextView) itemView.findViewById(R.id.start_date_text_view);
            endDate = (TextView) itemView.findViewById(R.id.end_date_text_view);
            userEmail = (TextView) itemView.findViewById(R.id.user_email);
        }

        public CircleImageView getImageView() {
            return imageView;
        }

        public Button getRequest() {
            return request;
        }

        public TextView getUserName() {
            return userName;
        }

        public TextView getStartDate() {
            return startDate;
        }

        public TextView getEndDate() {
            return endDate;
        }

        public TextView getUserEmail() {
            return userEmail;
        }
    }
}


text:
<?php
/*
 * ntlm_sasl_client.php
 *
 * @(#) $Id: ntlm_sasl_client.php,v 1.3 2004/11/17 08:00:37 mlemos Exp $
 *
 */

define('SASL_NTLM_STATE_START', 0);
define('SASL_NTLM_STATE_IDENTIFY_DOMAIN', 1);
define('SASL_NTLM_STATE_RESPOND_CHALLENGE', 2);
define('SASL_NTLM_STATE_DONE', 3);
define('SASL_FAIL', -1);
define('SASL_CONTINUE', 1);

class ntlm_sasl_client_class
{
    public $credentials = [];
    public $state = SASL_NTLM_STATE_START;

    public function initialize(&$client)
    {
        if (! function_exists($function = 'mcrypt_encrypt')
            || ! function_exists($function = 'mhash')
        ) {
            $extensions = [
                'mcrypt_encrypt' => 'mcrypt',
                'mhash' => 'mhash',
            ];
            $client->error = 'the extension '.$extensions[$function].
                ' required by the NTLM SASL client class is not available in this PHP configuration';

            return 0;
        }

        return 1;
    }

    public function ASCIIToUnicode($ascii)
    {
        for ($unicode = '', $a = 0; $a < strlen($ascii); $a++) {
            $unicode .= substr($ascii, $a, 1).chr(0);
        }

        return $unicode;
    }

    public function typeMsg1($domain, $workstation)
    {
        $domain_length = strlen($domain);
        $workstation_length = strlen($workstation);
        $workstation_offset = 32;
        $domain_offset = $workstation_offset + $workstation_length;

        return
            "NTLMSSP\0".
            "\x01\x00\x00\x00".
            "\x07\x32\x00\x00".
            pack('v', $domain_length).
            pack('v', $domain_length).
            pack('V', $domain_offset).
            pack('v', $workstation_length).
            pack('v', $workstation_length).
            pack('V', $workstation_offset).
            $workstation.
            $domain;
    }

    public function NTLMResponse($challenge, $password)
    {
        $unicode = $this->ASCIIToUnicode($password);
        $md4 = mhash(MHASH_MD4, $unicode);
        $padded = $md4.str_repeat(chr(0), 21 - strlen($md4));
        $iv_size = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        for ($response = '', $third = 0; $third < 21; $third += 7) {
            for ($packed = '', $p = $third; $p < $third + 7; $p++) {
                $packed .= str_pad(decbin(ord(substr($padded, $p, 1))), 8, '0', STR_PAD_LEFT);
            }
            for ($key = '', $p = 0; $p < strlen($packed); $p += 7) {
                $s = substr($packed, $p, 7);
                $b = $s.((substr_count($s, '1') % 2) ? '0' : '1');
                $key .= chr(bindec($b));
            }
            $ciphertext = mcrypt_encrypt(MCRYPT_DES, $key, $challenge, MCRYPT_MODE_ECB, $iv);
            $response .= $ciphertext;
        }

        return $response;
    }

    public function typeMsg3($ntlm_response, $user, $domain, $workstation)
    {
        $domain_unicode = $this->ASCIIToUnicode($domain);
        $domain_length = strlen($domain_unicode);
        $domain_offset = 64;
        $user_unicode = $this->ASCIIToUnicode($user);
        $user_length = strlen($user_unicode);
        $user_offset = $domain_offset + $domain_length;
        $workstation_unicode = $this->ASCIIToUnicode($workstation);
        $workstation_length = strlen($workstation_unicode);
        $workstation_offset = $user_offset + $user_length;
        $lm = '';
        $lm_length = strlen($lm);
        $lm_offset = $workstation_offset + $workstation_length;
        $ntlm = $ntlm_response;
        $ntlm_length = strlen($ntlm);
        $ntlm_offset = $lm_offset + $lm_length;
        $session = '';
        $session_length = strlen($session);
        $session_offset = $ntlm_offset + $ntlm_length;

        return
            "NTLMSSP\0".
            "\x03\x00\x00\x00".
            pack('v', $lm_length).
            pack('v', $lm_length).
            pack('V', $lm_offset).
            pack('v', $ntlm_length).
            pack('v', $ntlm_length).
            pack('V', $ntlm_offset).
            pack('v', $domain_length).
            pack('v', $domain_length).
            pack('V', $domain_offset).
            pack('v', $user_length).
            pack('v', $user_length).
            pack('V', $user_offset).
            pack('v', $workstation_length).
            pack('v', $workstation_length).
            pack('V', $workstation_offset).
            pack('v', $session_length).
            pack('v', $session_length).
            pack('V', $session_offset).
            "\x01\x02\x00\x00".
            $domain_unicode.
            $user_unicode.
            $workstation_unicode.
            $lm.
            $ntlm;
    }

    public function start(&$client, &$message, &$interactions)
    {
        if ($this->state != SASL_NTLM_STATE_START) {
            $client->error = 'NTLM authentication state is not at the start';

            return SASL_FAIL;
        }
        $this->credentials = [
            'user' => '',
            'password' => '',
            'realm' => '',
            'workstation' => '',
        ];
        $defaults = [];
        $status = $client->GetCredentials($this->credentials, $defaults, $interactions);
        if ($status == SASL_CONTINUE) {
            $this->state = SASL_NTLM_STATE_IDENTIFY_DOMAIN;
        }
        unset($message);

        return $status;
    }

    public function step(&$client, $response, &$message, &$interactions)
    {
        switch ($this->state) {
            case SASL_NTLM_STATE_IDENTIFY_DOMAIN:
                $message = $this->TypeMsg1($this->credentials['realm'], $this->credentials['workstation']);
                $this->state = SASL_NTLM_STATE_RESPOND_CHALLENGE;
                break;
            case SASL_NTLM_STATE_RESPOND_CHALLENGE:
                $ntlm_response = $this->NTLMResponse(substr($response, 24, 8), $this->credentials['password']);
                $message = $this->TypeMsg3(
                    $ntlm_response,
                    $this->credentials['user'],
                    $this->credentials['realm'],
                    $this->credentials['workstation']
                );
                $this->state = SASL_NTLM_STATE_DONE;
                break;
            case SASL_NTLM_STATE_DONE:
                $client->error = 'NTLM authentication was finished without success';

                return SASL_FAIL;
            default:
                $client->error = 'invalid NTLM authentication step state';

                return SASL_FAIL;
        }

        return SASL_CONTINUE;
    }
}


text:
package com.o2d.pkayjava.editor.view.stage.tools;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Align;
import com.o2d.pkayjava.editor.Overlap2DFacade;
import com.o2d.pkayjava.editor.factory.ItemFactory;
import com.o2d.pkayjava.editor.proxy.CursorManager;
import com.o2d.pkayjava.runtime.factory.EntityFactory;
import com.o2d.pkayjava.editor.view.stage.tools.*;
import com.o2d.pkayjava.editor.view.stage.tools.ItemDropTool;

/**
 * Created by azakhary on 4/30/2015.
 */
public class TextTool extends ItemDropTool {

    private static final String TAG;
    public static final String NAME;

    static {
        TAG = TextTool.class.getName();
        NAME = TAG;
    }

    private String fontFamily;
    private boolean isBold;
    private boolean isItalic;
    private int fontSize;
    private int letterSpacing;
    private Color color;
    private boolean kerningEnabled;
    private int align;

    public TextTool() {
        fontFamily = "arial";
        fontSize = 20;
        color = Color.WHITE;
        kerningEnabled = true;
        align = Align.left;
    }

    @Override
    public void initTool() {
        super.initTool();
        CursorManager cursorManager = Overlap2DFacade.getInstance().retrieveProxy(CursorManager.NAME);
        if (cursorManager != null) {
            cursorManager.setCursor(CursorManager.TEXT_TOOL);
        }
    }

    @Override
    public Entity putItem(float x, float y) {
        return ItemFactory.get().createLabel(this, new Vector2(x, y));
    }

    @Override
    public int[] listItemFilters() {
        int[] filter = {EntityFactory.LABEL_TYPE};
        return filter;
    }

    public int getAlign() {
        return align;
    }

    public void setAlign(int align) {
        this.align = align;
    }

    public String getFontFamily() {
        return fontFamily;
    }

    public void setFontFamily(String fontFamily) {
        this.fontFamily = fontFamily;
    }

    public boolean isBold() {
        return isBold;
    }

    public void setBold(boolean isBold) {
        this.isBold = isBold;
    }

    public boolean isItalic() {
        return isItalic;
    }

    public void setItalic(boolean isItalic) {
        this.isItalic = isItalic;
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public int getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(int letterSpacing) {
        this.letterSpacing = letterSpacing;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public boolean isKerningEnabled() {
        return kerningEnabled;
    }

    public void setKerningEnabled(boolean kerningEnabled) {
        this.kerningEnabled = kerningEnabled;
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>libguac: guacamole/instruction-types.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libguac
    0.9.7

Main Page

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

guacamole

Enumerations

instruction-types.h File Reference

Type definitions related to Guacamole instructions.
More...

Go to the source code of this file.

Enumerations

enum  	guac_instruction_parse_state { GUAC_INSTRUCTION_PARSE_LENGTH,
GUAC_INSTRUCTION_PARSE_CONTENT,
GUAC_INSTRUCTION_PARSE_COMPLETE,
GUAC_INSTRUCTION_PARSE_ERROR
 }

 	All possible states of the instruction parser.  More...

Detailed Description

Type definitions related to Guacamole instructions.

Enumeration Type Documentation

          enum guac_instruction_parse_state

All possible states of the instruction parser.

Enumerator

GUAC_INSTRUCTION_PARSE_LENGTH

The parser is currently waiting for data to complete the length prefix of the current element of the instruction.

GUAC_INSTRUCTION_PARSE_CONTENT

The parser has finished reading the length prefix and is currently waiting for data to complete the content of the instruction.

GUAC_INSTRUCTION_PARSE_COMPLETE

The instruction has been fully parsed.

GUAC_INSTRUCTION_PARSE_ERROR

The instruction cannot be parsed because of a protocol error.

<address class="footer">
Generated on Wed Jun 10 2015 21:39:32 for libguac by

 1.8.9.1
</address>


text:
!function($){

  "use strict"; // jshint ;_;

 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    if (this.options.target) this.$target = $(this.options.target)
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
    this.updater = this.options.updater || this.updater
    this.source = this.options.source
    this.strict = this.options.strict
    this.$menu = $(this.options.menu)
    this.shown = false

    if (typeof this.source == 'string') {
        this.url = this.source
        this.source = this.searchAjax
    }

    if (element.nodeName == 'SELECT') this.replaceSelect()

    this.text = this.$element.val()

    this.$element
      .attr('data-text', this.value)
      .attr('autocomplete', "off")

    if (typeof this.$target != 'undefined') this.$element.attr('data-value', this.$target.val())
      else if (typeof this.$element.attr('data-value') == 'undefined') this.$element.attr('data-value', this.strict ? '' : this.value)

    this.$menu.css('min-width', this.$element.width() + 12)

    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , replaceSelect: function () {
      this.$target = this.$element
      this.$element = $('<input type="text" />')

      this.source = {}
      this.strict = true

      var options = this.$target.find('option')
      var $option;
      for (var i=0; i<options.length; i++) {
        $option = $(options[i]);
        if ($option.val() === '') {
          this.$element.attr('placeholder', $option.html());
          continue;
        }

        this.source[$option.val()] = $option.html()
        if (this.$target.val() == $option.val()) this.$element.val($option.html())
      }

      var attr = this.$target[0].attributes
      for (i=0; i<attr.length; i++) {
        if (attr[i].nodeName != 'type' && attr[i].nodeName != 'name' && attr[i].nodeName != 'id' && attr[i].nodeName != 'data-provide' && !attr[i].nodeName.match(/^on/)) {
          this.$element.attr(attr[i].nodeName, attr[i].nodeValue)
        }
      }

      this.$element.insertAfter(this.$target)
      if (this.$target.attr('autofocus')) this.$element.trigger('focus').select()
      this.$target.attr('autofocus', false)
      this.$target.hide()
    }

  , destroyReplacement: function () {
      // Detroy replacement element, so it doesn't mess up the browsers autofill on refresh
      if (typeof this.$target != 'undefined' && this.$target[0].nodeName == 'SELECT') {
        this.$element.replaceWith('');
      }
    }

  , select: function () {
      var li = this.$menu.find('.active')
        , val = li.attr('data-value')
        , text = li.find('.item-text').length > 0 ? li.find('.item-text').text() : li.text()

      val = this.updater(val, 'value')
      text = this.updater(text, 'text')

      this.$element
        .val(text)
        .attr('data-value', val)

      this.text = text

      if (typeof this.$target != 'undefined') {
        this.$target
          .val(val)
          .trigger('change')
      }

      this.$element.trigger('change')

      return this.hide()
    }

  , updater: function (text, type) {
      return text
    }

  , show: function () {
      var pos = $.extend({}, this.$element.position(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu
        .insertAfter(this.$element)
        .css({
          top: pos.top + pos.height
        , left: pos.left
        })
        .show()

      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var items

      this.query = this.$element.val()

      if (!this.query || this.query.length < this.options.minLength) {
        return this.shown ? this.hide() : this
      }

      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

      return items ? this.process(items) : this
    }

  , process: function (items) {
      return $.isArray(items) ? this.processArray(items) : this.processObject(items)
    }

  , processArray: function (items) {
      var that = this

      items = $.grep(items, function (item) {
        return that.matcher(item)
      })

      items = this.sorter(items)

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , processObject: function (itemsIn) {
      var that = this
        , items = {}
        , i = 0

      $.each(itemsIn, function (key, item) {
        if (that.matcher(item)) items[key] = item
      })

      items = this.sorter(items)

      if ($.isEmptyObject(items)) {
        return this.shown ? this.hide() : this
      }

      $.each(items, function(key, item) {
        if (i++ >= that.options.items) delete items[key]
      })

      return this.render(items).show()
    }

  , searchAjax: function (query, process) {
      var that = this

      if (this.ajaxTimeout) clearTimeout(this.ajaxTimeout)

      this.ajaxTimeout = setTimeout(function () {
        if (that.ajaxTimeout) clearTimeout(that.ajaxTimeout)

        if (query === "") {
          that.hide()
          return
        }

        $.get(that.url, {'q': query, 'limit': that.options.items }, function (items) {
          if (typeof items == 'string') items = JSON.parse(items)
          process(items)
        })
      }, this.options.ajaxdelay)
  }

  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      return $.isArray(items) ? this.sortArray(items) : this.sortObject(items)
    }

  , sortArray: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , sortObject: function (items) {
      var sorted = {}
        , key;

      for (key in items) {
        if (!items[key].toLowerCase().indexOf(this.query.toLowerCase())) {
          sorted[key] = items[key];
          delete items[key]
        }
      }

      for (key in items) {
        if (~items[key].indexOf(this.query)) {
          sorted[key] = items[key];
          delete items[key]
        }
      }

      for (key in items) {
        sorted[key] = items[key]
      }

      return sorted
    }

  , highlighter: function (item) {
      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
        return '' + match + ''
      })
    }

  , render: function (items) {
      var that = this
        , list = $([])

      $.map(items, function (item, value) {
        if (list.length >= that.options.items) return

        var li
          , a

        if ($.isArray(items)) value = item

        li = $(that.options.item)
        a = li.find('a').length ? li.find('a') : li
        a.html(that.highlighter(item))

        li.attr('data-value', value)
        if (li.find('a').length === 0) li.addClass('dropdown-header')

        list.push(li[0])
      })

      list.not('.dropdown-header').first().addClass('active')

      this.$menu.html(list)

      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.nextAll('li:not(.dropdown-header)').first()

      if (!next.length) {
        next = $(this.$menu.find('li:not(.dropdown-header)')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prevAll('li:not(.dropdown-header)').first()

      if (!prev.length) {
        prev = this.$menu.find('li:not(.dropdown-header)').last()
      }

      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('focus',    $.proxy(this.focus, this))
        .on('blur',     $.proxy(this.blur, this))
        .on('change',   $.proxy(this.change, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if (this.eventSupported('keydown')) {
        this.$element.on('keydown', $.proxy(this.keydown, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))

      $(window).on('unload', $.proxy(this.destroyReplacement, this))
    }

  , eventSupported: function(eventName) {
      var isSupported = eventName in this.$element
      if (!isSupported) {
        this.$element.setAttribute(eventName, 'return;')
        isSupported = typeof this.$element[eventName] === 'function'
      }
      return isSupported
    }

  , move: function (e) {
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }

      e.stopPropagation()
    }

  , keydown: function (e) {
      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
      this.move(e)
    }

  , keypress: function (e) {
      if (this.suppressKeyPressRepeat) return
      this.move(e)
    }

  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
        case 16: // shift
        case 17: // ctrl
        case 18: // alt
          break

        case 9: // tab
        case 13: // enter
          if (!this.shown) return
          this.select()
          break

        case 27: // escape
          if (!this.shown) return
          this.hide()
          break

        default:
          this.lookup()
      }

      e.stopPropagation()
      e.preventDefault()
  }

  , change: function (e) {
      var value

      if (this.$element.val() != this.text) {
        value = this.$element.val() === '' || this.strict ? '' : this.$element.val()

        this.$element.val(value)
        this.$element.attr('data-value', value)
        this.text = value
        if (typeof this.$target != 'undefined') this.$target.val(value)
      }
    }

  , focus: function (e) {
      this.focused = true
    }

  , blur: function (e) {
      this.focused = false
      if (!this.mousedover && this.shown) this.hide()
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
      this.$element.focus()
    }

  , mouseenter: function (e) {
      this.mousedover = true
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  , mouseleave: function (e) {
      this.mousedover = false
      if (!this.focused && this.shown) this.hide()
    }

  }

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  var old = $.fn.typeahead

  $.fn.typeahead = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    source: []
  , items: 8
  , menu: '

'
  , item: '

'
  , ajaxdelay: 400
  , minLength: 1
  }

  $.fn.typeahead.Constructor = Typeahead

 /* TYPEAHEAD NO CONFLICT
  * =================== */

  $.fn.typeahead.noConflict = function () {
    $.fn.typeahead = old
    return this
  }

 /* TYPEAHEAD DATA-API
  * ================== */

  $(document)
    .off('focus.typeahead.data-api')  // overwriting Twitter's typeahead
    .on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      if ($this.is('select')) $this.attr('autofocus', true)
      e.preventDefault()
      $this.typeahead($this.data())
  })

}(window.jQuery);
/* ===========================================================
 * bootstrap-inputmask.js j2
 * http://twitter.github.com/bootstrap/javascript.html#tooltips
 * Based on Masked Input plugin by Josh Bush (digitalbush.com)
 * ===========================================================
 * Copyright 2012 Jasny BV, Netherlands.
 *
 * 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.
 * ========================================================== */

!function ($) {

  "use strict"; // jshint ;_;

  var isIphone = (window.orientation !== undefined),
      isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1

 /* INPUTMASK PUBLIC CLASS DEFINITION
  * ================================= */

  var Inputmask = function (element, options) {
    if (isAndroid) return // No support because caret positioning doesn't work on Android

    this.$element = $(element)
    this.options = $.extend({}, $.fn.inputmask.defaults, options)
    this.mask = String(options.mask)

    this.init()
    this.listen()

    this.checkVal() //Perform initial check for existing values
  }

  Inputmask.prototype = {

    init: function() {
      var defs = this.options.definitions
      var len = this.mask.length

      this.tests = []
      this.partialPosition = this.mask.length
      this.firstNonMaskPos = null

      $.each(this.mask.split(""), $.proxy(function(i, c) {
        if (c == '?') {
          len--
          this.partialPosition = i
        } else if (defs[c]) {
          this.tests.push(new RegExp(defs[c]))
          if(this.firstNonMaskPos === null)
            this.firstNonMaskPos =  this.tests.length - 1
        } else {
          this.tests.push(null)
        }
      }, this))

      this.buffer = $.map(this.mask.split(""), $.proxy(function(c, i) {
        if (c != '?') return defs[c] ? this.options.placeholder : c
      }, this))

      this.focusText = this.$element.val()

      this.$element.data("rawMaskFn", $.proxy(function() {
        return $.map(this.buffer, function(c, i) {
          return this.tests[i] && c != this.options.placeholder ? c : null
        }).join('')
      }, this))
    },

    listen: function() {
      if (this.$element.attr("readonly")) return

      var pasteEventName = (navigator.userAgent.match(/msie/i) ? 'paste' : 'input') + ".mask"

      this.$element
        .on("unmask", $.proxy(this.unmask, this))

        .on("focus.mask", $.proxy(this.focusEvent, this))
        .on("blur.mask", $.proxy(this.blurEvent, this))

        .on("keydown.mask", $.proxy(this.keydownEvent, this))
        .on("keypress.mask", $.proxy(this.keypressEvent, this))

        .on(pasteEventName, $.proxy(this.pasteEvent, this))
    },

    //Helper Function for Caret positioning
    caret: function(begin, end) {
      if (this.$element.length === 0) return
      if (typeof begin == 'number') {
        end = (typeof end == 'number') ? end : begin
        return this.$element.each(function() {
          if (this.setSelectionRange) {
            this.setSelectionRange(begin, end)
          } else if (this.createTextRange) {
            var range = this.createTextRange()
            range.collapse(true)
            range.moveEnd('character', end)
            range.moveStart('character', begin)
            range.select()
          }
        })
      } else {
        if (this.$element[0].setSelectionRange) {
          begin = this.$element[0].selectionStart
          end = this.$element[0].selectionEnd
        } else if (document.selection && document.selection.createRange) {
          var range = document.selection.createRange()
          begin = 0 - range.duplicate().moveStart('character', -100000)
          end = begin + range.text.length
        }
        return {
          begin: begin,
          end: end
        }
      }
    },

    seekNext: function(pos) {
      var len = this.mask.length
      while (++pos <= len && !this.tests[pos]);

      return pos
    },

    seekPrev: function(pos) {
      while (--pos >= 0 && !this.tests[pos]);

      return pos
    },

    shiftL: function(begin,end) {
      var len = this.mask.length

      if(begin<0) return

      for (var i = begin,j = this.seekNext(end); i < len; i++) {
        if (this.tests[i]) {
          if (j < len && this.tests[i].test(this.buffer[j])) {
            this.buffer[i] = this.buffer[j]
            this.buffer[j] = this.options.placeholder
          } else
            break
          j = this.seekNext(j)
        }
      }
      this.writeBuffer()
      this.caret(Math.max(this.firstNonMaskPos, begin))
    },

    shiftR: function(pos) {
      var len = this.mask.length

      for (var i = pos, c = this.options.placeholder; i < len; i++) {
        if (this.tests[i]) {
          var j = this.seekNext(i)
          var t = this.buffer[i]
          this.buffer[i] = c
          if (j < len && this.tests[j].test(t))
            c = t
          else
            break
        }
      }
    },

    unmask: function() {
      this.$element
        .unbind(".mask")
        .removeData("inputmask")
    },

    focusEvent: function() {
      this.focusText = this.$element.val()
      var len = this.mask.length
      var pos = this.checkVal()
      this.writeBuffer()

      var that = this
      var moveCaret = function() {
        if (pos == len)
          that.caret(0, pos)
        else
          that.caret(pos)
      }

      if ($.browser.msie)
        moveCaret()
      else
        setTimeout(moveCaret, 0)
    },

    blurEvent: function() {
      this.checkVal()
      if (this.$element.val() != this.focusText)
        this.$element.trigger('change')
    },

    keydownEvent: function(e) {
      var k=e.which

      //backspace, delete, and escape get special treatment
      if (k == 8 || k == 46 || (isIphone && k == 127)) {
        var pos = this.caret(),
        begin = pos.begin,
        end = pos.end

        if (end-begin === 0) {
          begin = k!=46 ? this.seekPrev(begin) : (end=this.seekNext(begin-1))
          end = k==46 ? this.seekNext(end) : end
        }
        this.clearBuffer(begin, end)
        this.shiftL(begin,end-1)

        return false
      } else if (k == 27) {//escape
        this.$element.val(this.focusText)
        this.caret(0, this.checkVal())
        return false
      }
    },

    keypressEvent: function(e) {
      var len = this.mask.length

      var k = e.which,
      pos = this.caret()

      if (e.ctrlKey || e.altKey || e.metaKey || k<32)  {//Ignore
        return true
      } else if (k) {
        if (pos.end - pos.begin !== 0) {
          this.clearBuffer(pos.begin, pos.end)
          this.shiftL(pos.begin, pos.end-1)
        }

        var p = this.seekNext(pos.begin - 1)
        if (p < len) {
          var c = String.fromCharCode(k)
          if (this.tests[p].test(c)) {
            this.shiftR(p)
            this.buffer[p] = c
            this.writeBuffer()
            var next = this.seekNext(p)
            this.caret(next)
          }
        }
        return false
      }
    },

    pasteEvent: function() {
      var that = this

      setTimeout(function() {
        that.caret(that.checkVal(true))
      }, 0)
    },

    clearBuffer: function(start, end) {
      var len = this.mask.length

      for (var i = start; i < end && i < len; i++) {
        if (this.tests[i])
          this.buffer[i] = this.options.placeholder
      }
    },

    writeBuffer: function() {
      return this.$element.val(this.buffer.join('')).val()
    },

    checkVal: function(allow) {
      var len = this.mask.length
      //try to place characters where they belong
      var test = this.$element.val()
      var lastMatch = -1

      for (var i = 0, pos = 0; i < len; i++) {
        if (this.tests[i]) {
          this.buffer[i] = this.options.placeholder
          while (pos++ < test.length) {
            var c = test.charAt(pos - 1)
            if (this.tests[i].test(c)) {
              this.buffer[i] = c
              lastMatch = i
              break
            }
          }
          if (pos > test.length)
            break
        } else if (this.buffer[i] == test.charAt(pos) && i != this.partialPosition) {
          pos++
          lastMatch = i
        }
      }
      if (!allow && lastMatch + 1 < this.partialPosition) {
        this.$element.val("")
        this.clearBuffer(0, len)
      } else if (allow || lastMatch + 1 >= this.partialPosition) {
        this.writeBuffer()
        if (!allow) this.$element.val(this.$element.val().substring(0, lastMatch + 1))
      }
      return (this.partialPosition ? i : this.firstNonMaskPos)
    }
  }

 /* INPUTMASK PLUGIN DEFINITION
  * =========================== */

  $.fn.inputmask = function (options) {
    return this.each(function () {
      var $this = $(this)
      , data = $this.data('inputmask')
      if (!data) $this.data('inputmask', (data = new Inputmask(this, options)))
    })
  }

  $.fn.inputmask.defaults = {
    mask: "",
    placeholder: "_",
    definitions: {
      '9': "[0-9]",
      'a': "[A-Za-z]",
      '?': "[A-Za-z0-9]",
      '*': "."
    }
  }

  $.fn.inputmask.Constructor = Inputmask

 /* INPUTMASK DATA-API
  * ================== */

  $(document).on('focus.inputmask.data-api', '[data-mask]', function (e) {
    var $this = $(this)
    if ($this.data('inputmask')) return
    e.preventDefault()
    $this.inputmask($this.data())
  })

}(window.jQuery);
/* ============================================================
 * bootstrap-rowlink.js j1
 * http://jasny.github.com/bootstrap/javascript.html#rowlink
 * ============================================================
 * Copyright 2012 Jasny BV, Netherlands.
 *
 * 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.
 * ============================================================ */

!function ($) {

  "use strict"; // jshint ;_;

  var Rowlink = function (element, options) {
    options = $.extend({}, $.fn.rowlink.defaults, options)
    var tr = element.nodeName.toLowerCase() == 'tr' ? $(element) : $(element).find('tr:has(td)')

    tr.each(function() {
      var link = $(this).find(options.target).first()
      if (!link.length) return

      var href = link.attr('href')

      $(this).find('td').not('.nolink').click(function() {
        window.location = href;
      })

      $(this).addClass('rowlink')
      link.replaceWith(link.html())
    })
  }

 /* ROWLINK PLUGIN DEFINITION
  * =========================== */

  $.fn.rowlink = function (options) {
    return this.each(function () {
      var $this = $(this)
      , data = $this.data('rowlink')
      if (!data) $this.data('rowlink', (data = new Rowlink(this, options)))
    })
  }

  $.fn.rowlink.defaults = {
    target: "a"
  }

  $.fn.rowlink.Constructor = Rowlink

 /* ROWLINK DATA-API
  * ================== */

  $(function () {
    $('[data-provide="rowlink"],[data-provides="rowlink"]').each(function () {
      $(this).rowlink($(this).data())
    })
  })

}(window.jQuery);
/* ===========================================================
 * bootstrap-fileupload.js j2
 * http://jasny.github.com/bootstrap/javascript.html#fileupload
 * ===========================================================
 * Copyright 2012 Jasny BV, Netherlands.
 *
 * 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.
 * ========================================================== */

!function ($) {

  "use strict"; // jshint ;_

 /* FILEUPLOAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Fileupload = function (element, options) {
    this.$element = $(element)
    this.type = this.$element.data('uploadtype') || (this.$element.find('.thumbnail').length > 0 ? "image" : "file")

    this.$input = this.$element.find(':file')
    if (this.$input.length === 0) return

    this.name = this.$input.attr('name') || options.name

    this.$hidden = this.$element.find('input[type=hidden][name="'+this.name+'"]')
    if (this.$hidden.length === 0) {
      this.$hidden = $('<input type="hidden" />')
      this.$element.prepend(this.$hidden)
    }

    this.$preview = this.$element.find('.fileupload-preview')
    var height = this.$preview.css('height')
    if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height)

    this.original = {
      'exists': this.$element.hasClass('fileupload-exists'),
      'preview': this.$preview.html(),
      'hiddenVal': this.$hidden.val()
    }

    this.$remove = this.$element.find('[data-dismiss="fileupload"]')

    this.$element.find('[data-trigger="fileupload"]').on('click.fileupload', $.proxy(this.trigger, this))

    this.listen()
  }

  Fileupload.prototype = {

    listen: function() {
      this.$input.on('change.fileupload', $.proxy(this.change, this))
      $(this.$input[0].form).on('reset.fileupload', $.proxy(this.reset, this))
      if (this.$remove) this.$remove.on('click.fileupload', $.proxy(this.clear, this))
    },

    change: function(e, invoked) {
      if (invoked === 'clear') return

      var file = e.target.files !== undefined ? e.target.files[0] : (e.target.value ? { name: e.target.value.replace(/^.+\\/, '') } : null)

      if (!file) {
        this.clear()
        return
      }

      this.$hidden.val('')
      this.$hidden.attr('name', '')
      this.$input.attr('name', this.name)

      if (this.type === "image" && this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match('image.*') : file.name.match('\\.(gif|png|jpe?g)$')) && typeof FileReader !== "undefined") {
        var reader = new FileReader()
        var preview = this.$preview
        var element = this.$element

        reader.onload = function(e) {
          preview.html('')
          element.addClass('fileupload-exists').removeClass('fileupload-new')
        }

        reader.readAsDataURL(file)
      } else {
        this.$preview.text(file.name)
        this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
      }
    },

    clear: function(e) {
      this.$hidden.val('')
      this.$hidden.attr('name', this.name)
      this.$input.attr('name', '')

      //ie8+ doesn't support changing the value of input with type=file so clone instead
      if (navigator.userAgent.match(/msie/i)){
          var inputClone = this.$input.clone(true);
          this.$input.after(inputClone);
          this.$input.remove();
          this.$input = inputClone;
      }else{
          this.$input.val('')
      }

      this.$preview.html('')
      this.$element.addClass('fileupload-new').removeClass('fileupload-exists')

      if (e) {
        this.$input.trigger('change', [ 'clear' ])
        e.preventDefault()
      }
    },

    reset: function(e) {
      this.clear()

      this.$hidden.val(this.original.hiddenVal)
      this.$preview.html(this.original.preview)

      if (this.original.exists) this.$element.addClass('fileupload-exists').removeClass('fileupload-new')
       else this.$element.addClass('fileupload-new').removeClass('fileupload-exists')
    },

    trigger: function(e) {
      this.$input.trigger('click')
      e.preventDefault()
    }
  }

 /* FILEUPLOAD PLUGIN DEFINITION
  * =========================== */

  $.fn.fileupload = function (options) {
    return this.each(function () {
      var $this = $(this)
      , data = $this.data('fileupload')
      if (!data) $this.data('fileupload', (data = new Fileupload(this, options)))
      if (typeof options == 'string') data[options]()
    })
  }

  $.fn.fileupload.Constructor = Fileupload

 /* FILEUPLOAD DATA-API
  * ================== */

  $(document).on('click.fileupload.data-api', '[data-provides="fileupload"]', function (e) {
    var $this = $(this)
    if ($this.data('fileupload')) return
    $this.fileupload($this.data())

    var $target = $(e.target).closest('[data-dismiss="fileupload"],[data-trigger="fileupload"]');
    if ($target.length > 0) {
      $target.trigger('click.fileupload')
      e.preventDefault()
    }
  })

}(window.jQuery);