text:
#include "sqliteInt.h"

/*
** Process an UPDATE statement.
**
**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
**          \_______/ \________/     \______/       \________________/
*            onError   pTabList      pChanges             pWhere
*/
void sqliteUpdate(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table in which we should change things */
  ExprList *pChanges,    /* Things to be changed */
  Expr *pWhere,          /* The WHERE clause.  May be null */
  int onError            /* How to handle constraint errors */
){
  int i, j;              /* Loop counters */
  Table *pTab;           /* The table to be updated */
  int loopStart;         /* VDBE instruction address of the start of the loop */
  int jumpInst;          /* Addr of VDBE instruction to jump out of loop */
  WhereInfo *pWInfo;     /* Information about the WHERE clause */
  Vdbe *v;               /* The virtual database engine */
  Index *pIdx;           /* For looping over indices */
  int nIdx;              /* Number of indices that need updating */
  int nIdxTotal;         /* Total number of indices */
  int iCur;              /* VDBE Cursor number of pTab */
  sqlite *db;            /* The database structure */
  Index **apIdx = 0;     /* An array of indices that need updating too */
  char *aIdxUsed = 0;    /* aIdxUsed[i]==1 if the i-th index is used */
  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
                         ** an expression for the i-th column of the table.
                         ** aXRef[i]==-1 if the i-th column is not changed. */
  int chngRecno;         /* True if the record number is being changed */
  Expr *pRecnoExpr;      /* Expression defining the new record number */
  int openAll;           /* True if all indices need to be opened */
  int isView;            /* Trying to update a view */
  int iStackDepth;       /* Index of memory cell holding stack depth */
  AuthContext sContext;  /* The authorization context */

  int before_triggers;         /* True if there are any BEFORE triggers */
  int after_triggers;          /* True if there are any AFTER triggers */
  int row_triggers_exist = 0;  /* True if any row triggers exist */

  int newIdx      = -1;  /* index of trigger "new" temp table       */
  int oldIdx      = -1;  /* index of trigger "old" temp table       */

  sContext.pParse = 0;
  if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
  db = pParse->db;
  assert( pTabList->nSrc==1 );
  iStackDepth = pParse->nMem++;

  /* Locate the table which we want to update.
  */
  pTab = sqliteSrcListLookup(pParse, pTabList);
  if( pTab==0 ) goto update_cleanup;
  before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
            TK_UPDATE, TK_BEFORE, TK_ROW, pChanges);
  after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
            TK_UPDATE, TK_AFTER, TK_ROW, pChanges);
  row_triggers_exist = before_triggers || after_triggers;
  isView = pTab->pSelect!=0;
  if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
    goto update_cleanup;
  }
  if( isView ){
    if( sqliteViewGetColumnNames(pParse, pTab) ){
      goto update_cleanup;
    }
  }
  aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
  if( aXRef==0 ) goto update_cleanup;
  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;

  /* If there are FOR EACH ROW triggers, allocate cursors for the
  ** special OLD and NEW tables
  */
  if( row_triggers_exist ){
    newIdx = pParse->nTab++;
    oldIdx = pParse->nTab++;
  }

  /* Allocate a cursors for the main database table and for all indices.
  ** The index cursors might not be used, but if they are used they
  ** need to occur right after the database cursor.  So go ahead and
  ** allocate enough space, just in case.
  */
  pTabList->a[0].iCursor = iCur = pParse->nTab++;
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
    pParse->nTab++;
  }

  /* Resolve the column names in all the expressions of the
  ** of the UPDATE statement.  Also find the column index
  ** for each column to be updated in the pChanges array.  For each
  ** column to be updated, make sure we have authorization to change
  ** that column.
  */
  chngRecno = 0;
  for(i=0; i<pChanges->nExpr; i++){
    if( sqliteExprResolveIds(pParse, pTabList, 0, pChanges->a[i].pExpr) ){
      goto update_cleanup;
    }
    if( sqliteExprCheck(pParse, pChanges->a[i].pExpr, 0, 0) ){
      goto update_cleanup;
    }
    for(j=0; j<pTab->nCol; j++){
      if( sqliteStrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
        if( j==pTab->iPKey ){
          chngRecno = 1;
          pRecnoExpr = pChanges->a[i].pExpr;
        }
        aXRef[j] = i;
        break;
      }
    }
    if( j>=pTab->nCol ){
      if( sqliteIsRowid(pChanges->a[i].zName) ){
        chngRecno = 1;
        pRecnoExpr = pChanges->a[i].pExpr;
      }else{
        sqliteErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
        goto update_cleanup;
      }
    }
#ifndef SQLITE_OMIT_AUTHORIZATION
    {
      int rc;
      rc = sqliteAuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
                           pTab->aCol[j].zName, db->aDb[pTab->iDb].zName);
      if( rc==SQLITE_DENY ){
        goto update_cleanup;
      }else if( rc==SQLITE_IGNORE ){
        aXRef[j] = -1;
      }
    }
#endif
  }

  /* Allocate memory for the array apIdx[] and fill it with pointers to every
  ** index that needs to be updated.  Indices only need updating if their
  ** key includes one of the columns named in pChanges or if the record
  ** number of the original table entry is changing.
  */
  for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
    if( chngRecno ){
      i = 0;
    }else {
      for(i=0; i<pIdx->nColumn; i++){
        if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
      }
    }
    if( i<pIdx->nColumn ) nIdx++;
  }
  if( nIdxTotal>0 ){
    apIdx = sqliteMalloc( sizeof(Index*) * nIdx + nIdxTotal );
    if( apIdx==0 ) goto update_cleanup;
    aIdxUsed = (char*)&apIdx[nIdx];
  }
  for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
    if( chngRecno ){
      i = 0;
    }else{
      for(i=0; i<pIdx->nColumn; i++){
        if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
      }
    }
    if( i<pIdx->nColumn ){
      apIdx[nIdx++] = pIdx;
      aIdxUsed[j] = 1;
    }else{
      aIdxUsed[j] = 0;
    }
  }

  /* Resolve the column names in all the expressions in the
  ** WHERE clause.
  */
  if( pWhere ){
    if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
      goto update_cleanup;
    }
    if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
      goto update_cleanup;
    }
  }

  /* Start the view context
  */
  if( isView ){
    sqliteAuthContextPush(pParse, &sContext, pTab->zName);
  }

  /* Begin generating code.
  */
  v = sqliteGetVdbe(pParse);
  if( v==0 ) goto update_cleanup;
  sqliteBeginWriteOperation(pParse, 1, pTab->iDb);

  /* If we are trying to update a view, construct that view into
  ** a temporary table.
  */
  if( isView ){
    Select *pView;
    pView = sqliteSelectDup(pTab->pSelect);
    sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
    sqliteSelectDelete(pView);
  }

  /* Begin the database scan
  */
  pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
  if( pWInfo==0 ) goto update_cleanup;

  /* Remember the index of every item to be updated.
  */
  sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);

  /* End the database scan loop.
  */
  sqliteWhereEnd(pWInfo);

  /* Initialize the count of updated rows
  */
  if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
    sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  }

  if( row_triggers_exist ){
    /* Create pseudo-tables for NEW and OLD
    */
    sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
    sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);

    /* The top of the update loop for when there are triggers.
    */
    sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
    sqliteVdbeAddOp(v, OP_StackDepth, 0, 0);
    sqliteVdbeAddOp(v, OP_MemStore, iStackDepth, 1);
    loopStart = sqliteVdbeAddOp(v, OP_MemLoad, iStackDepth, 0);
    sqliteVdbeAddOp(v, OP_StackReset, 0, 0);
    jumpInst = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
    sqliteVdbeAddOp(v, OP_Dup, 0, 0);

    /* Open a cursor and make it point to the record that is
    ** being updated.
    */
    sqliteVdbeAddOp(v, OP_Dup, 0, 0);
    if( !isView ){
      sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
      sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
    }
    sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);

    /* Generate the OLD table
    */
    sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
    sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
    sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);

    /* Generate the NEW table
    */
    if( chngRecno ){
      sqliteExprCode(pParse, pRecnoExpr);
    }else{
      sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
    }
    for(i=0; i<pTab->nCol; i++){
      if( i==pTab->iPKey ){
        sqliteVdbeAddOp(v, OP_String, 0, 0);
        continue;
      }
      j = aXRef[i];
      if( j<0 ){
        sqliteVdbeAddOp(v, OP_Column, iCur, i);
      }else{
        sqliteExprCode(pParse, pChanges->a[j].pExpr);
      }
    }
    sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
    sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
    if( !isView ){
      sqliteVdbeAddOp(v, OP_Close, iCur, 0);
    }

    /* Fire the BEFORE and INSTEAD OF triggers
    */
    if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, pTab,
          newIdx, oldIdx, onError, loopStart) ){
      goto update_cleanup;
    }
  }

  if( !isView ){
    /*
    ** Open every index that needs updating.  Note that if any
    ** index could potentially invoke a REPLACE conflict resolution
    ** action, then we need to open all indices because we might need
    ** to be deleting some records.
    */
    sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
    sqliteVdbeAddOp(v, OP_OpenWrite, iCur, pTab->tnum);
    if( onError==OE_Replace ){
      openAll = 1;
    }else{
      openAll = 0;
      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
        if( pIdx->onError==OE_Replace ){
          openAll = 1;
          break;
        }
      }
    }
    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
      if( openAll || aIdxUsed[i] ){
        sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
        sqliteVdbeAddOp(v, OP_OpenWrite, iCur+i+1, pIdx->tnum);
        assert( pParse->nTab>iCur+i+1 );
      }
    }

    /* Loop over every record that needs updating.  We have to load
    ** the old data for each record to be updated because some columns
    ** might not change and we will need to copy the old value.
    ** Also, the old data is needed to delete the old index entries.
    ** So make the cursor point at the old record.
    */
    if( !row_triggers_exist ){
      sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
      jumpInst = loopStart = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
      sqliteVdbeAddOp(v, OP_Dup, 0, 0);
    }
    sqliteVdbeAddOp(v, OP_NotExists, iCur, loopStart);

    /* If the record number will change, push the record number as it
    ** will be after the update. (The old record number is currently
    ** on top of the stack.)
    */
    if( chngRecno ){
      sqliteExprCode(pParse, pRecnoExpr);
      sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
    }

    /* Compute new data for this record.
    */
    for(i=0; i<pTab->nCol; i++){
      if( i==pTab->iPKey ){
        sqliteVdbeAddOp(v, OP_String, 0, 0);
        continue;
      }
      j = aXRef[i];
      if( j<0 ){
        sqliteVdbeAddOp(v, OP_Column, iCur, i);
      }else{
        sqliteExprCode(pParse, pChanges->a[j].pExpr);
      }
    }

    /* Do constraint checks
    */
    sqliteGenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRecno, 1,
                                   onError, loopStart);

    /* Delete the old indices for the current record.
    */
    sqliteGenerateRowIndexDelete(db, v, pTab, iCur, aIdxUsed);

    /* If changing the record number, delete the old record.
    */
    if( chngRecno ){
      sqliteVdbeAddOp(v, OP_Delete, iCur, 0);
    }

    /* Create the new index entries and the new record.
    */
    sqliteCompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRecno, 1, -1);
  }

  /* Increment the row counter
  */
  if( db->flags & SQLITE_CountRows && !pParse->trigStack){
    sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
  }

  /* If there are triggers, close all the cursors after each iteration
  ** through the loop.  The fire the after triggers.
  */
  if( row_triggers_exist ){
    if( !isView ){
      for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
        if( openAll || aIdxUsed[i] )
          sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
      }
      sqliteVdbeAddOp(v, OP_Close, iCur, 0);
      pParse->nTab = iCur;
    }
    if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, pTab,
          newIdx, oldIdx, onError, loopStart) ){
      goto update_cleanup;
    }
  }

  /* Repeat the above with the next record to be updated, until
  ** all record selected by the WHERE clause have been updated.
  */
  sqliteVdbeAddOp(v, OP_Goto, 0, loopStart);
  sqliteVdbeChangeP2(v, jumpInst, sqliteVdbeCurrentAddr(v));
  sqliteVdbeAddOp(v, OP_ListReset, 0, 0);

  /* Close all tables if there were no FOR EACH ROW triggers */
  if( !row_triggers_exist ){
    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
      if( openAll || aIdxUsed[i] ){
        sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
      }
    }
    sqliteVdbeAddOp(v, OP_Close, iCur, 0);
    pParse->nTab = iCur;
  }else{
    sqliteVdbeAddOp(v, OP_Close, newIdx, 0);
    sqliteVdbeAddOp(v, OP_Close, oldIdx, 0);
  }

  sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
  sqliteEndWriteOperation(pParse);

  /*
  ** Return the number of rows that were changed.
  */
  if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
    sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows updated", P3_STATIC);
    sqliteVdbeAddOp(v, OP_Callback, 1, 0);
  }

update_cleanup:
  sqliteAuthContextPop(&sContext);
  sqliteFree(apIdx);
  sqliteFree(aXRef);
  sqliteSrcListDelete(pTabList);
  sqliteExprListDelete(pChanges);
  sqliteExprDelete(pWhere);
  return;
}


text:
<?php

namespace HWI\Bundle\OAuthBundle\Tests\Security\Core\Authentication\Token;

use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;

class OAuthTokenTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var OAuthToken
     */
    protected $token;

    public function setUp()
    {
        $this->token = new OAuthToken('access_token', array('ROLE_TEST'));
        $this->token->setResourceOwnerName('github');
    }

    public function testGets()
    {
        $expectedToken = array(
            'access_token'  => 'access_token',
            'refresh_token' => 'refresh_token',
            'expires_in'    => '666',
        );
        $token = new OAuthToken($expectedToken, array('ROLE_TEST'));
        $token->setResourceOwnerName('github');

        $this->assertEquals($expectedToken, $token->getRawToken());
        $this->assertEquals($expectedToken['access_token'], $token->getAccessToken());
        $this->assertEquals($expectedToken['refresh_token'], $token->getRefreshToken());
        $this->assertEquals($expectedToken['expires_in'], $token->getExpiresIn());
        $this->assertEquals('github', $token->getResourceOwnerName());
    }

    public function testIsAuthenticated()
    {
        $this->assertTrue($this->token->isAuthenticated());
    }

    public function testGetSetResourceOwnerName()
    {
        $this->assertEquals('github', $this->token->getResourceOwnerName());
        $this->token->setResourceOwnerName('foobar');
        $this->assertEquals('foobar', $this->token->getResourceOwnerName());
    }

    public function testSerialization()
    {
        /**
         * @var $token OAuthToken
         */
        $token = unserialize(serialize($this->token));

        $this->assertEquals('access_token', $token->getAccessToken());
        $this->assertEquals('github', $token->getResourceOwnerName());
    }

    public function testSerializationOfOAuth1Token()
    {
        $oauth1Token = new OAuthToken(array(
            'oauth_token' => 'oauth1_access_token',
            'oauth_token_secret' => 'oauth1_token_secret'
        ), array('ROLE_TEST'));

        $oauth1Token->setResourceOwnerName('twitter');

        $oauth1Token = unserialize(serialize($oauth1Token));

        $this->assertEquals('oauth1_access_token', $oauth1Token->getAccessToken());
        $this->assertEquals('oauth1_token_secret', $oauth1Token->getTokenSecret());
        $this->assertEquals('twitter', $oauth1Token->getResourceOwnerName());
    }
}

redpajama_set_name: RedPajamaGithub


text:
Any Valid
=========
The AnyValid class is a wrapper class to be used with, for example, [formencode.validators](http://www.formencode.org/en/latest/modules/validators.html#module-formencode.validators), that lets you partially specify what kind of objects it should match.  To see the usefulness of this, it might be easier to first have a look at mock's ANY object ([from unittest.mock's documentation](http://docs.python.org/3/library/unittest.mock.html#any)):

> Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of call_args and make more complex assertions on them.

> To ignore certain arguments you can pass in objects that compare equal to everything. Calls to assert_called_with() and assert_called_once_with() will then succeed no matter what was passed in.

> ```python
>>>
>>> mock = Mock(return_value=None)
>>> mock('foo', bar=object())
>>> mock.assert_called_once_with('foo', bar=ANY)
```
> ANY can also be used in comparisons with call lists like mock_calls:
> ```python
>>>
>>> m = MagicMock(return_value=None)
>>> m(1)
>>> m(1, 2)
>>> m(object())
>>> m.mock_calls == [call(1), call(1, 2), ANY]
True
```

Now, what if you would like to make certain assertions about an argument, but perhaps don't know the exact value, or want to avoid certain values (for example ```None```).  This is where AnyValid might come in handy.  It provides a really simple way to leverage all the great work that has been put into formencode's validators, so that your testing code can make advanced assertions while being easy to read and maintain.

Examples
========
Simple argument matching:
```python
>>>
>>> from mock import Mock
>>> from any_valid import AnyValid, Int, String
>>>
>>> def check_call(foo, bar):
...     try:
...         mock = Mock(return_value=None)
...         mock(foo, bar=bar)
...         mock.assert_called_once_with(AnyValid(String(min_lenght=3)),
...                                      bar=AnyValid(Int(min=2)))
...     except AssertionError:
...         return False
...     return True
...
>>> check_call('fo', 1)
False
>>> check_call(8, 0)
False
>>> check_call('foo', 2)
True
```

Matching a loosely defined dict argument:
```python
>>> from any_valid import AnyValid, Number, OneOf
>>> valid_input = {
...     'core_temperature': AnyValid(Number(min=35, max=41.5)),
...     'protocol': AnyValid(OneOf(['https', 'http'])),
...     }
>>> mock = Mock(return_value=None)
>>> mock({'core_temperature': 36.8, 'protocol': 'https'})
>>> mock.assert_called_with(valid_input)
>>>
```


text:
define(['angular','common/module-name','angular-ui-router'], function (angular,moduleName) {

    /**
     * Config
     */
    var templateUrl = 'js/common/ui-router-breadcrumbs/uiBreadcrumbs.tpl.html';

        module = angular.module(moduleName);

    module.directive('uiRouterBreadcrumbs', ['$interpolate', '$state','$transitions','$state', function($interpolate, $state,$transitions) {
        return {
            restrict: 'E',
            templateUrl: function(elem, attrs) {
                return attrs.templateUrl || templateUrl;
            },
            scope: {
                displaynameProperty: '@',
                abstractProxyProperty: '@?'
            },
            link: function($scope) {
                $scope.breadcrumbs = [];
                $scope.lastBreadcrumbs = [];
               /* if ($state.$current.name !== '') {
                    updateBreadcrumbsArray();
                }
                */

                $transitions.onSuccess({},function(transition){
                   var toState = transition.to();
                   var toParams = transition.params();
                   if(toState.data !== undefined ) {
                       if (toState.data.noBreadcrumb && toState.data.noBreadcrumb == true) {
                           //console.log('Skipping breadcrumb for ',toState)
                       } else {
                           updateBreadcrumbs(toState, toParams);
                       }
                   }

                });

                function updateLastBreadcrumbs(){
                        $scope.lastBreadcrumbs = $scope.breadcrumbs.slice(Math.max($scope.breadcrumbs.length - 2,0));
                    }

                function getBreadcrumbKey(state){
                    return state.name;
                }

                function getDisplayName(state) {
                    return state.data.displayName || state.name;
                }

                function isBreadcrumbRoot(state){
                    return state.data.breadcrumbRoot && state.data.breadcrumbRoot == true;
                }

                function addBreadcrumb(state, params){
                    var breadcrumbKey = getBreadcrumbKey(state);
                    var copyParams = {}
                    if(params ) {
                        angular.extend(copyParams, params);
                    }
                    var displayName = getDisplayName(state);
                    $scope.breadcrumbs.push({
                        key:breadcrumbKey,
                        displayName: displayName,
                        route: state.name,
                        params:copyParams
                    });

                    updateLastBreadcrumbs();
                }
                $scope.navigate = function(crumb) {
                    $state.go(crumb.route,crumb.params);
                }

                function getBreadcrumbIndex(state){
                    var breadcrumbKey = getBreadcrumbKey(state);
                    var matchingState = _.find($scope.breadcrumbs,function(breadcrumb){
                        return breadcrumb.key == breadcrumbKey;
                    });
                    if(matchingState){
                        return _.indexOf($scope.breadcrumbs,matchingState)
                    }
                    return -1;
                }
                function updateBreadcrumbs(state,params){
                    var index = getBreadcrumbIndex(state);
                    if(isBreadcrumbRoot(state)){
                        index = 0;
                    }
                    if(index == -1){
                        addBreadcrumb(state,params);
                    }
                    else {
                        //back track until we get to this index and then replace it with the incoming one
                        $scope.breadcrumbs =  $scope.breadcrumbs.slice(0,index);
                        addBreadcrumb(state,params);
                    }
                }
                /**
                 * Resolve the displayName of the specified state. Take the property specified by the `displayname-property`
                 * attribute and look up the corresponding property on the state's config object. The specified string can be interpolated against any resolved
                 * properties on the state config object, by using the usual {{ }} syntax.
                 * @param currentState
                 * @returns {*}
                 */
                function getDisplayName1(currentState) {
                    var interpolationContext;
                    var propertyReference;
                    var displayName;

                    if (!$scope.displaynameProperty) {
                        // if the displayname-property attribute was not specified, default to the state's name
                        return currentState.name;
                    }
                    propertyReference = getObjectValue($scope.displaynameProperty, currentState);

                    if (propertyReference === false) {
                        return false;
                    } else if (typeof propertyReference === 'undefined') {
                        return currentState.name;
                    } else {
                        // use the $interpolate service to handle any bindings in the propertyReference string.
                        interpolationContext =  (typeof currentState.locals !== 'undefined') ? currentState.locals.globals : currentState;
                        displayName = $interpolate(propertyReference)(interpolationContext);
                        return displayName;
                    }
                }

                /**
                 * Given a string of the type 'object.property.property', traverse the given context (eg the current $state object) and return the
                 * value found at that path.
                 *
                 * @param objectPath
                 * @param context
                 * @returns {*}
                 */
                function getObjectValue(objectPath, context) {
                    var i;
                    var propertyArray = objectPath.split('.');
                    var propertyReference = context;

                    for (i = 0; i < propertyArray.length; i ++) {
                        if (angular.isDefined(propertyReference[propertyArray[i]])) {
                            propertyReference = propertyReference[propertyArray[i]];
                        } else {
                            // if the specified property was not found, default to the state's name
                            return undefined;
                        }
                    }
                    return propertyReference;
                }

            }
        };
    }]);
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
********************************************************************************
* Ant Script Library - Java project module
* Contains ant targets related project information and setup
* Module property prefix: "java-project"
********************************************************************************
* Copyright 2009 Joe Schmetzer
*
* 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.
********************************************************************************
 -->
<project name="asl-java-project">
    <dirname property="java-project.basedir" file="${ant.file.asl-java-project}"/>
    <import file="${java-project.basedir}/asl-common.xml"/>
    <import file="${java-project.basedir}/asl-java-build.xml"/>
    <import file="${java-project.basedir}/asl-java-test.xml"/>
    <import file="${java-project.basedir}/asl-java-report.xml"/>

    <!-- ***********************************************************************
    * Default values for java-project properties.
    ************************************************************************ -->

    <!-- ***********************************************************************
    * target: project-show-dirs
    ************************************************************************ -->
    <target name="project-show-dirs"
            description="Shows the directories configured for this project">

        <echo>Directories for Java Project ${ant.project.name}</echo>
        <echo>=========================================================================</echo>
        <echo>Main source (java-build.src-dir): ${java-build.src-dir}</echo>
        <echo>Test source (java-test.src-dir):  ${java-test.src-dir}</echo>
        <echo>Libraries (java-build.lib-dir):   ${java-build.lib-dir}</echo>
        <echo>Build output (common.target-dir): ${common.target-dir}</echo>
        <echo>Distributable (common.dist-dir):  ${common.dist-dir}</echo>
        <echo>Reports (java-report.report-dir): ${java-report.report-dir}</echo>
    </target>

    <!-- ***********************************************************************
    * target: project-show-dirs
    ************************************************************************ -->
    <target name="project-mkdirs"
            description="Creates the directories configured for this project">
        <mkdir dir="${java-build.src-dir}"/>
        <mkdir dir="${java-test.src-dir}"/>
        <mkdir dir="${java-build.lib-dir}"/>
    </target>
</project>


text:
import numpy, pandas
from sklearn.base import TransformerMixin
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression, mutual_info_regression

class SelectNAndKBest(
	TransformerMixin,
):
	"""
	Selects the first N features plus the K best other features.
	"""

	def __init__(self, n, k, func=None):
		self._n = n
		self._k = k
		self._func = mutual_info_regression if func is None else func

	def fit(self, X, y):
		if self._k > X.shape[1]-self._n:
			use_k = 'all'
		else:
			use_k = self._k

		if X.shape[1]-self._n <=0:
			self._feature_selector = None
		elif isinstance(X, pandas.DataFrame):
			self._feature_selector = SelectKBest(self._func, k=use_k).fit(X.iloc[:,self._n:], y)
		else:
			self._feature_selector = SelectKBest(self._func, k=use_k).fit(X[:,self._n:], y)
		return self

	def transform(self, X):
		if isinstance(X, pandas.DataFrame):
			X_outside = X.iloc[:,self._n:]
			if self._feature_selector is None:
				X2 = X_outside
			else:
				X2 = self._feature_selector.transform(X_outside)
				X2 = pandas.DataFrame(X2, index=X.index, columns=X_outside.columns[self._feature_selector.get_support()])
			return pandas.concat([X.iloc[:,:self._n], X2], axis=1)
		else:
			if self._feature_selector is None:
				X2 = X[:,self._n:]
			else:
				X2 = self._feature_selector.transform(X[:,self._n:])
			return numpy.concatenate([X[:,:self._n], X2], axis=1)


text:
"""
The problem is to deliver some orders to several clients with a single truck.
Each order consists of a given quantity of a product of a certain type.
A product type is an integer in {0, 1, 2}.
Loading the truck with at least one product of a given type requires some
specific installations. The truck can be configured in order to handle one,
two or three different types of product. There are 7 different configurations
for the truck, corresponding to the 7 possible combinations of product types:
 - configuration 0: all products are of type 0,
 - configuration 1: all products are of type 1,
 - configuration 2: all products are of type 2,
 - configuration 3: products are of type 0 or 1,
 - configuration 4: products are of type 0 or 2,
 - configuration 5: products are of type 1 or 2,
 - configuration 6: products are of type 0 or 1 or 2.
The cost for configuring the truck from a configuration A to a configuration B
depends on A and B.
The configuration of the truck determines its capacity and its loading cost.
A delivery consists of loading the truck with one or several orders for the
same customer.
Both the cost (for configuring and loading the truck) and the number of
deliveries needed to deliver all the orders must be minimized, the cost being
the most important criterion.

Please refer to documentation for appropriate setup of solving configuration.
"""

from docplex.cp.model import CpoModel
from sys import stdout

#-----------------------------------------------------------------------------
# Initialize the problem data
#-----------------------------------------------------------------------------

# List of possible truck configurations. Each tuple is (load, cost) with:
#    load: max truck load for this configuration,
#    cost: cost for loading the truck in this configuration
TRUCK_CONFIGURATIONS = ((11, 2), (11, 2), (11, 2), (11, 3), (10, 3), (10, 3), (10, 4))

# List of customer orders.
# Each tuple is (customer index, volume, product type)
CUSTOMER_ORDERS = ((0, 3, 1), (0, 4, 2), (0, 3, 0), (0, 2, 1), (0, 5, 1), (0, 4, 1), (0, 11, 0),
                   (1, 4, 0), (1, 5, 0), (1, 2, 0), (1, 4, 2), (1, 7, 2), (1, 3, 2), (1, 5, 0), (1, 2, 2),
                   (2, 5, 1), (2, 6, 0), (2, 11, 2), (2, 1, 0), (2, 6, 0), (2, 3, 0))

# Transition costs between configurations.
# Tuple (A, B, TCost) means that the cost of  modifying the truck from configuration A to configuration B is TCost
CONFIGURATION_TRANSITION_COST = ((0, 0,  0), (0, 1,  0), (0, 2,  0), (0, 3, 10), (0, 4, 10),
                                 (0, 5, 10), (0, 6, 15), (1, 0,  0), (1, 1,  0), (1, 2,  0),
                                 (1, 3, 10), (1, 4, 10), (1, 5, 10), (1, 6, 15), (2, 0,  0),
                                 (2, 1,  0), (2, 2,  0), (2, 3, 10), (2, 4, 10), (2, 5, 10),
                                 (2, 6, 15), (3, 0,  3), (3, 1,  3), (3, 2,  3), (3, 3,  0),
                                 (3, 4, 10), (3, 5, 10), (3, 6, 15), (4, 0,  3), (4, 1,  3),
                                 (4, 2,  3), (4, 3, 10), (4, 4,  0), (4, 5, 10), (4, 6, 15),
                                 (5, 0,  3), (5, 1,  3), (5, 2,  3), (5, 3, 10), (5, 4, 10),
                                 (5, 5,  0), (5, 6, 15), (6, 0,  3), (6, 1,  3), (6, 2,  3),
                                 (6, 3, 10), (6, 4, 10), (6, 5, 10), (6, 6,  0)
                                 )

# Compatibility between the product types and the configuration of the truck
# allowedContainerConfigs[i] = the array of all the configurations that accept products of type i
ALLOWED_CONTAINER_CONFIGS = ((0, 3, 4, 6),
                             (1, 3, 5, 6),
                             (2, 4, 5, 6))

#-----------------------------------------------------------------------------
# Prepare the data for modeling
#-----------------------------------------------------------------------------

nbTruckConfigs = len(TRUCK_CONFIGURATIONS)
maxTruckConfigLoad = [tc[0] for tc in TRUCK_CONFIGURATIONS]
truckCost = [tc[1] for tc in TRUCK_CONFIGURATIONS]
maxLoad = max(maxTruckConfigLoad)

nbOrders = len(CUSTOMER_ORDERS)
nbCustomers = 1 + max(co[0] for co in CUSTOMER_ORDERS)
volumes = [co[1] for co in CUSTOMER_ORDERS]
productType = [co[2] for co in CUSTOMER_ORDERS]

# Max number of truck deliveries (estimated upper bound, to be increased if no solution)
maxDeliveries = 15

#-----------------------------------------------------------------------------
# Build the model
#-----------------------------------------------------------------------------

# Create CPO model
mdl = CpoModel()

# Configuration of the truck for each delivery
truckConfigs = mdl.integer_var_list(maxDeliveries, 0, nbTruckConfigs - 1, "truckConfigs")
# In which delivery is an order
where = mdl.integer_var_list(nbOrders, 0, maxDeliveries - 1, "where")
# Load of a truck
load = mdl.integer_var_list(maxDeliveries, 0, maxLoad, "load")
# Number of deliveries that are required
nbDeliveries = mdl.integer_var(0, maxDeliveries)
# Identification of which customer is assigned to a delivery
customerOfDelivery = mdl.integer_var_list(maxDeliveries, 0, nbCustomers, "customerOfTruck")
# Transition cost for each delivery
transitionCost = mdl.integer_var_list(maxDeliveries - 1, 0, 1000, "transitionCost")

# transitionCost[i] = transition cost between configurations i and i+1
for i in range(1, maxDeliveries):
    auxVars = (truckConfigs[i - 1], truckConfigs[i], transitionCost[i - 1])
    mdl.add(mdl.allowed_assignments(auxVars, CONFIGURATION_TRANSITION_COST))

# Constrain the volume of the orders in each truck
mdl.add(mdl.pack(load, where, volumes, nbDeliveries))
for i in range(0, maxDeliveries):
    mdl.add(load[i] <= mdl.element(truckConfigs[i], maxTruckConfigLoad))

# Compatibility between the product type of an order and the configuration of its truck
for j in range(0, nbOrders):
    configOfContainer = mdl.integer_var(ALLOWED_CONTAINER_CONFIGS[productType[j]])
    mdl.add(configOfContainer == mdl.element(truckConfigs, where[j]))

# Only one customer per delivery
for j in range(0, nbOrders):
    mdl.add(mdl.element(customerOfDelivery, where[j]) == CUSTOMER_ORDERS[j][0])

# Non-used deliveries are at the end
for j in range(1, maxDeliveries):
    mdl.add((load[j - 1] > 0) | (load[j] == 0))

# Dominance: the non used deliveries keep the last used configuration
mdl.add(load[0] > 0)
for i in range(1, maxDeliveries):
    mdl.add((load[i] > 0) | (truckConfigs[i] == truckConfigs[i - 1]))

# Dominance: regroup deliveries with same configuration
for i in range(maxDeliveries - 2, 0, -1):
    ct = mdl.logical_and([(truckConfigs[p] != truckConfigs[i - 1]) for p in range(i + 1, maxDeliveries)])
    mdl.add((truckConfigs[i] == truckConfigs[i - 1]) | ct)

# Objective: first criterion for minimizing the cost for configuring and loading trucks
#            second criterion for minimizing the number of deliveries
cost = sum(transitionCost) + sum(mdl.element(truckConfigs[i], truckCost) * (load[i] != 0) for i in range(maxDeliveries))
mdl.add(mdl.minimize_static_lex([cost, nbDeliveries]))

# Search strategy: first assign order to truck
mdl.set_search_phases([mdl.search_phase(where)])

#-----------------------------------------------------------------------------
# Solve the model and display the result
#-----------------------------------------------------------------------------

# Solve model
print("\nSolving model....")
msol = mdl.solve(TimeLimit=20, LogPeriod=3000)

# Print solution
if msol.is_solution():
    print("Solution: ")
    ovals = msol.get_objective_values()
    print("   Configuration cost: {}, number of deliveries: {}".format(ovals[0], ovals[1]))
    for i in range(maxDeliveries):
        ld = msol.get_value(load[i])
        if ld > 0:
            stdout.write("   Delivery {:2d}: config={}".format(i,msol.get_value(truckConfigs[i])))
            stdout.write(", items=")
            for j in range(nbOrders):
                if (msol.get_value(where[j]) == i):
                    stdout.write(" <{}, {}, {}>".format(j, productType[j], volumes[j]))
            stdout.write('\n')
else:
    stdout.write("Solve status: {}\n".format(msol.get_solve_status()))


text:
<?php

class Product extends Octopus_Model {
    protected $fields = array(
        'name' => array(
            // 'required' => true
        ),
        'group' => array(
            'type' => 'manyToMany',
        )
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Group extends Octopus_Model {
    protected $fields = array(
        'name' => array(
            // 'required' => true,
        ),
        'product' => array(
            'type' => 'manyToMany',
        )
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Nail extends Octopus_Model {
    protected $fields = array(
        'name' => array(
            // 'required' => true
        ),
        'hammer' => array(
            'type' => 'hasMany',
        ),
        'active' => array(
            'type' => 'boolean',
        ),
        'favorite' => array(
            'type' => 'hasMany',
            'model' => 'sledgehammer',
            'key' => 'favorite_nail',
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Hammer extends Octopus_Model {
    protected $fields = array(
        'name' => array(
            // 'required' => true,
        ),
        'slug' => array(
            'type' => 'slug',
            'onEmpty' => 'to_unique_slug',
        ),
        'nail' => array(
            'type' => 'hasOne',
            // 'required' => true
        ),
        'active' => array(
            'type' => 'boolean',
        ),
        'display_order' => array(
            'type' => 'numeric',
        ),
        'created',
        'updated',
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Sledgehammer extends Octopus_Model {
    protected $fields = array(
        'name' => array(
            // 'required' => true,
        ),
        'favorite_nail' => array(
            'type' => 'hasOne',
            'model' => 'nail',
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Lack extends Octopus_Model {
    protected $fields = array(
        'notitle' => array(),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Notext extends Octopus_Model {
    protected $fields = array(
        'number' => array(
            'type' => 'numeric',
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class FindAuthor extends Octopus_Model {

    protected $fields = array(
        'name' => array('type' => 'string'),
        'posts' => array(
            'type' => 'hasMany',
            'model' => 'FindPost'
        ),
        'favorite_food' => array('type' => 'hasOne', 'model' => 'FindFood'),
        'active'
    );

}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class FindCategory extends Octopus_Model {

    protected $fields = array(
        'name',
    );

}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class FindFood extends Octopus_Model {
    protected $fields = array('name');
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class FindPost extends Octopus_Model {

    protected $fields = array(
        'title' => array(
            'type' => 'string'
        ),
        'slug' => array(
            'type' => 'slug'
        ),
        'body' => array(
            'type' => 'html'
        ),
        'author' => array(
            'model' => 'FindAuthor',
            'type' => 'hasOne'
        ),
        'category' => array(
            'type' => 'manyToMany',
            'model' => 'FindCategory'
        ),
        'active' => array(
            'type' => 'boolean',
        ),
        'display_order' => array(
            'type' => 'order',
        ),
        'created',
        'updated',

    );

    public $search = array('title', 'author');

    public static function &create($row) {

        $obj = new FindPost();

        return $obj;

    }

}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Comment extends Octopus_Model {
    protected $fields = array(
        'content' => array(
            'type' => 'text',
            'onCreate' => 'triggerCreate',
        ),
        'creator' => array(
            'type' => 'hasOne',
            'model' => 'CommentUser',
        ),
        'parent' => array(
            'type' => 'hasOne',
            'filter' => true
        ),
        'item_type',
        'item_id' => array(
            'type' => 'numeric',
        ),
    );

    public function triggerCreate($model, $field) {
        return $field->accessValue($model);
    }
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class CommentUser extends Octopus_Model {
    protected $fields = array(
        'name',
        'comments' => array(
            'type' => 'hasMany',
        ),

    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Car extends Octopus_Model {
    protected $fields = array(
        'name',
        'comment' => array(
            'type' => 'hasMany',
            'filter' => true,
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Boat extends Octopus_Model {
    protected $fields = array(
        'name',
        'comment' => array(
            'type' => 'hasMany',
            'filter' => true,
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Schemab extends Octopus_Model {
    protected $fields = array(
        'title',
        'display_order' => array(
            'type' => 'numeric',
        ),
        'cost' => array(
            'type' => 'numeric',
            'decimal_places' => 2,
        ),
        'lowcost' => array(
            'type' => 'numeric',
            'decimal_places' => 2,
            'precision' => 4,
        ),
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Schemac extends Octopus_Model {
    protected $indexes = array('display_order', 'title', array('one', 'two'));
    protected $fields = array(
        'title',
        'display_order' => array(
            'type' => 'numeric',
        ),
        'one',
        'two',
    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class Schemad extends Octopus_Model {
    protected $fields = array(
        'title' => array(
            'index' => 'unique',
        ),
        'display_order' => array(
            'type' => 'numeric',
            'index' => true,
        ),

    );
}

/**
 * @internal
 * @copyright (c) 2012 Codestruck, LLC.
 * @license http://opensource.org/licenses/mit-license.php/
 */
class HtmlTablePerson extends Octopus_Model {

    protected $fields = array(
        'name' => array(
            'sortable' => false,
            'filter' => true
        ),
        'age' => array('type' => 'numeric')
    );

    public function method_uppercase($str) {
        return strtoupper($str);
    }

}


text:
require 'net/http'
require 'json'
require 'logger'
require 'csv'
require 'cgi'

module PPMS

  class PPMS_Error < StandardError
  end

  class PPMS
    include ::I18n

    @@affiliation2id = {'CRUK' => 1,
                        'Charity' => 2,
                        'RC / UKGov' => 5,
                        'EC / ERC' => 6,
                        'WT' => 7,
                        'Commercial' => 8,
                        'Core' => 9,
                        'F.I.R.' => 8}

    def csv2dict(data,indexKey,headerRow: 0)
      rows = ::CSV.parse(data)
      hdrRow = rows[headerRow].map{|x| x.strip}
      index = hdrRow.find_index(indexKey)
      inames = hdrRow
      data = {}
      rows.each_index do |i|
        next if i <= headerRow
        rdata = {}
        row = rows[i]
        row = row.map{|x| x.nil? ? nil : x.strip}
        next if row.blank?
        row.each_index do |col|
          rdata[inames[col]] = row[col]
        end
        data[row[index]] = rdata
      end
      return data
    end

    def initialize(host: nil, key: nil)
      @host = host.nil? ? Setting.plugin_ppms['api_url'] : host
      @key = key.nil? ? Setting.plugin_ppms['api_key'] : key
      @uri = URI("https://#{@host}/pumapi/")
      @prices = nil
    end

    def makeRequest(req,tag,verbose)
      result = nil
      Net::HTTP.start(@uri.host,@uri.port, :use_ssl => true) do |conn|
        result = conn.request(req)
      end
      if result.nil? or !result.is_a?(Net::HTTPResponse)
        $ppmslog.error("Failed #{tag}: response not a 'Net::HTTPResponse' object (#{result.class})") if verbose
        return nil
      elsif result.code != "200"
        $ppmslog.error("Failed #{tag}: response code == '#{result.code}'") if verbose
        return nil
      elsif result.body.strip == "error: request not authorized"
        $ppmslog.error("Failed #{tag}: bad API key '#{@key}'") if verbose
        return nil
      end
      return result
    end

    def isConnected(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getsystems", "format" => "json")
      result = makeRequest(req,__method__,verbose)
      return false if result.nil?
      return result.code == "200"
    end

    def getUser(id,verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getuser", "login" => id, "format" => "json")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        data = JSON.parse(result.body)
        if !data.nil?
          data.each do |k,v|
            data[k] = CGI.unescapeHTML(v) if v.is_a?(String)
          end
        end
      rescue JSON::ParserError
        $ppmslog.error("Failed getUser: userid not found '#{id}'") if verbose
        data = nil
      end
      return data
    end

    def listUsers(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getusers")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        data = result.body.split.map{|x| CGI.unescapeHTML(x)}
      rescue
        $ppmslog.error("Failed listUsers: result = '#{result.body}'") if verbose
        data = nil
      end
      return data
    end

    def getSystems(verbose: false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getsystems")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      data = csv2dict(result.body,"System id")
      return data
    end

    def getSystemUsers(system,verbose: false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getsysrights", "id" => system)
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      data = result.body.split.map{|x| x.split(":")[1]}
      return data
    end

    def getServices(core: 7,verbose: false)
      if core.nil?
        $ppmslog.error("#{__method__}: 'core' parameter must not be nil.") if verbose
        return nil
      end
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getservices", "coreid" => core)
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      data = csv2dict(result.body,"Name")
      data = data.select{|k,v| v["Group"] != "Admin" and v["Active"] == "True"}
      return data
    end

    def getServiceID(core: 7,name: "Hours",verbose: false)
      data = getServices(core: core,verbose: verbose)
      return data[name]["Service id"]
    end

    def getProjects(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getprojects", "format" => "json", "ExpirationDate" => "true")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      data = JSON.parse(result.body)
      return data
    end

    def getGroups(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getgroups")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        data = result.body.split
      rescue
        $ppmslog.error("Failed #{__method__}: result = '#{result.body}'") if verbose
        data = nil
      end
      return data
    end

    def getGroup(gp,verbose=false)
      cf = CustomField.find_by(name: 'PPMS Group ID')
      gpname = nil
      if cf
        cfid = cf.id
        ppms_ids = gp.custom_values.select{|x| x.custom_field_id == cfid}
        if ppms_ids.length > 0
          gpname = ppms_ids[0].value
        end
      end
      gpname = I18n.transliterate(gp.name.strip) if gpname.blank?
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getgroup","unitlogin" => gpname)
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        tdata = csv2dict(result.body,"unitlogin")
        data = tdata[tdata.keys()[0]]
      rescue
        $ppmslog.error("Failed #{__method__}: result = '#{result.body}'") if verbose
        data = nil
      end
      return data
    end

    def getOrders(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getorders")
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        data = csv2dict(result.body,"Order ref.",headerRow: 1)
      rescue
        $ppmslog.error("Failed #{__method__}: result = '#{result.body}'") if verbose
        data = nil
      end
      return data
    end

    def getOrder(id,verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key, "action" => "getorderlines", "orderref" => id)
      result = makeRequest(req,__method__,verbose)
      return result if result.nil?
      begin
        data = csv2dict(result.body,"Order ID",headerRow: 0)
      rescue
        $ppmslog.error("Failed #{__method__}: result = '#{result.body}'") if verbose
        data = nil
      end
      return data
    end

    def submitOrder(service,login,quant,project,cdate,verbose=true)
      ddate = cdate.to_s
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key,
                        "action" => "createorder",
                        "serviceid" => service,
                        "login" => login,
                        "quantity" => quant,
                        "projectid" => project,
                        "accepted" => true,
                        "completed" => true,
                        "completeddate" => ddate)
      result = makeRequest(req,__method__,verbose)
      ok = /^\d+$/ =~ result.body
      if ok.nil?
        raise PPMS_Error.new(result.body)
      end
      return result.body.to_i
    end

    def loadPrices(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key,
                        "action" => "getpriceslist",
                        "format" => "csv")
      result = makeRequest(req,__method__,verbose)
      rows = ::CSV.parse(result.body)
      hdrRow = rows[0].map{|x| x.strip}
      affCol = hdrRow.find_index("affiliationid")
      projCol = hdrRow.find_index("projectid")
      priceCol = hdrRow.find_index("Price")
      @prices = Hash.new(default=0)
      rows[1..rows.length-1].each do |row|
        affId = row[affCol].to_i
        projId = row[projCol].to_i
        price = row[priceCol].to_f
        if !@prices.include?(affId)
          @prices[affId] = Hash.new(default=0)
        end
        @prices[affId][projId] = price
      end
      return @prices
    end

    def getPrice(units,affiliation: nil,costCode: nil)
      if @prices.nil?
        loadPrices()
      end
      affId = @@affiliation2id[affiliation]
      affId = (affId.nil? || !@prices.include?(affId)) ? 0 : affId
      costId = costCode.nil? ? 0 : costCode
      price = 0
      if affId == 0
        if @prices[affId].include? costId
          price = @prices[affId][costId]
        end
      else
        if @prices[affId].include? costId
          price = @prices[affId][costId]
        else
          price = @prices[affId][0]
        end
      end
      return units.to_f * price
    end

    def getBcodes(verbose=false)
      req = Net::HTTP::Post.new(@uri)
      req.set_form_data("apikey" => @key,
                        "action" => "getbcodes")
      result = makeRequest(req,__method__,verbose)
      data = csv2dict(result.body,"Bcode",headerRow: 0)
      return data
    end

  end
end


text:
require "spec_helper"

describe "Authentication" do
  let(:client) { Checkr::Canada::Client.new("test_api_key") }
  subject { client.reports.all }

  context "successful" do
    before do
      stub_request(:get, "https://api.checkr.com/ca/v1/reports").to_return(
        body: { data: [], object: "list", count: 0 }.to_json
      )
    end

    it "build basic auth from api_key" do
      subject

      expect(
        a_request(:get, "https://api.checkr.com/ca/v1/reports")
          .with(basic_auth: ["test_api_key", ""])
      ).to have_been_made
    end
  end

  context "failed" do
    before do
      stub_request(:get, "https://api.checkr.com/ca/v1/reports").to_return(
        body: { error: 'Not authorized' }.to_json, status: 401
      )
    end

    it "raises error" do
      expect { subject }.to raise_error(Evil::Client::Operation::ResponseError)

      expect(
        a_request(:get, "https://api.checkr.com/ca/v1/reports")
          .with(basic_auth: ["test_api_key", ""])
      ).to have_been_made
    end
  end
end


text:
define(["smocker", "test/scenarios/display_dashboards_data_scenario"], function(smocker) {
  smocker.scenario('dashboard_write_operations', function() {
    this.post('/ajax/dashboard').respondWith(function(url, requestData) {
      var data = JSON.parse(requestData);

      if ("test new-dashboard" === data.name) {
        return {
          status: 201,
          content: { id: "dashboard_4", name: "test new-dashboard", monitors: [] },
        };
      }
      throw "unexpected data in the POST request: " + requestData;
    });

    this.put('/ajax/dashboard/dashboard_1').respondWith(function(url, requestData) {
      var data = JSON.parse(requestData);

      if ("dashboard_new_name" === data.name) {
        return { status: 204 };
      }
      throw "unexpected data in the " + method + " request: " + requestData;
    });

    this.delete('/ajax/dashboard/dashboard_2').respondWith({ status: 204 });
  });

  smocker.groupScenarios('dashboard_actions', ['display_dashboards_data', 'dashboard_write_operations']);
});


text:
import config from '../config/config';

export default {
  getImagePathForItem: function getImagePathForItem(itemSource) {
    return config.STEAM_IMAGES_URL + itemSource;
  },
};


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/html; charset=utf-8" />
    <title>出错啦!</title>
    <meta name="robots" content="noindex, nofollow" />

Error 抱歉,您请求的页面现在无法打开!

您要查看的网页可能已被删除、或者暂时不可用。

<< 返回首页


text:
import os
import sys

sys.path.append(os.pardir)

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import settings
from linkedct import operations, models

CONFIG = settings.CONFIG

urls = models.Url.objects.filter(status='inprocess')
while len(urls)>0:
    url_list = urls[:25]
    for trial_url in url_list:
        if trial_url.status=='inprocess':
            trial_url.status = 'submitted'
            trial_url.save()
    for trial_url in url_list:
        if trial_url.status=='submitted':
            trial_url.status = 'inprocess_again'
            trial_url.save()
            #uri = 'http://data.linkedct.org:8081/processxml/' + trial_url + '/'
            #uri = 'http://newyork.isl.sandbox/linkedct/processxml/' + trial_url.url + '/'
            #uri = 'http://localhost:8081/processxml/' + trial_url.url + '/'
            try:
                operations.process_xml(trial_url.url, 10000*1024, '127.0.0.1', 'utf-8', True)
                trial_url.status = 'done'
                trial_url.save()
                print 'Done with ' + trial_url.url
            except:
                trial_url.status = 'error'
                trial_url.save()
                print 'Error in URL: ' + trial_url.url
    urls = models.Url.objects.filter(status='inprocess')

urls = models.Url.objects.filter(status='inprocess_again')
while len(urls)>0:
    url_list = urls[:25]
    for trial_url in url_list:
        if trial_url.status=='inprocess_again':
            trial_url.status = 'submitted'
            trial_url.save()
    for trial_url in url_list:
        if trial_url.status=='submitted':
            trial_url.status = 'inprocess'
            trial_url.save()
            #uri = 'http://data.linkedct.org:8081/processxml/' + trial_url + '/'
            #uri = 'http://newyork.isl.sandbox/linkedct/processxml/' + trial_url.url + '/'
            #uri = 'http://localhost:8081/processxml/' + trial_url.url + '/'
            try:
                operations.process_xml(trial_url.url, 10000*1024, '127.0.0.1', 'utf-8', True)
                trial_url.status = 'done'
                trial_url.save()
                print 'Done with ' + trial_url.url
            except:
                trial_url.status = 'error'
                trial_url.save()
                print 'Error in URL: ' + trial_url.url
    urls = models.Url.objects.filter(status='inprocess')

urls = models.Url.objects.filter(status='error')
if len(urls)>0:
    url_list = urls
    for trial_url in url_list:
        if trial_url.status=='error':
            trial_url.status = 'submitted'
            trial_url.save()
    for trial_url in url_list:
        if trial_url.status=='submitted':
            trial_url.status = 'inprocess'
            trial_url.save()
            #uri = 'http://data.linkedct.org:8081/processxml/' + trial_url + '/'
            #uri = 'http://newyork.isl.sandbox/linkedct/processxml/' + trial_url.url + '/'
            #uri = 'http://localhost:8081/processxml/' + trial_url.url + '/'
            try:
                operations.process_xml(trial_url.url, 10000*1024, '127.0.0.1', 'utf-8', True)
                trial_url.status = 'done'
                trial_url.save()
                print 'Done with ' + trial_url.url
            except:
                trial_url.status = 'error'
                trial_url.save()
                print 'Error in URL: ' + trial_url.url
    #urls = models.Url.objects.filter(status='error')


text:
@interface Loser : Winner {}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <prerequisites>
        <maven>3.0.5</maven>
    </prerequisites>
    <groupId>com.btmatthews.havoc</groupId>
    <artifactId>havoc</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>Havoc Build System</name>
    <description></description>
    <modules>
        <module>havoc-core</module>
        <module>havoc-project-xml</module>
        <module>havoc-task-processor</module>
        <module>havoc-java-support</module>
    </modules>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.btmatthews.havoc</groupId>
                <artifactId>havoc-core</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>com.btmatthews.havoc</groupId>
                <artifactId>havoc-java-support</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>com.btmatthews.havoc</groupId>
                <artifactId>havoc-task-processor</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.jgrapht</groupId>
                <artifactId>jgrapht-core</artifactId>
                <version>0.9.0</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class UploadSiteHostedPictures(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the UploadSiteHostedPictures Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(UploadSiteHostedPictures, self).__init__(temboo_session, '/Library/eBay/Trading/UploadSiteHostedPictures')

    def new_input_set(self):
        return UploadSiteHostedPicturesInputSet()

    def _make_result_set(self, result, path):
        return UploadSiteHostedPicturesResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return UploadSiteHostedPicturesChoreographyExecution(session, exec_id, path)

class UploadSiteHostedPicturesInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the UploadSiteHostedPictures
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_ExtensionInDays(self, value):
        """
        Set the value of the ExtensionInDays input for this Choreo. ((optional, integer) The number of days to extend the expiration date for the specified image, after a listing has ended.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('ExtensionInDays', value)
    def set_ExternalPictureURL(self, value):
        """
        Set the value of the ExternalPictureURL input for this Choreo. ((conditional, string) The URL of an image to upload. Required unless providing PictureData. Max image size is 7 MB. Max URL length is 1024. Formats supported are: JPG, GIF, PNG, BMP, and TIF.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('ExternalPictureURL', value)
    def set_PictureData(self, value):
        """
        Set the value of the PictureData input for this Choreo. ((conditional, string) The Base64 encoded string for an the image data. Required unless providing the ExternalPictureURL. Max image size is 7 MB. Formats supported are: JPG, GIF, PNG, BMP, and TIF.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('PictureData', value)
    def set_PictureName(self, value):
        """
        Set the value of the PictureName input for this Choreo. ((optional, string) The name of the picture.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('PictureName', value)
    def set_PictureSet(self, value):
        """
        Set the value of the PictureSet input for this Choreo. ((optional, string) The image sizes that will be generated. Valid values are: Standard and Supersize.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('PictureSet', value)
    def set_PictureUploadPolicy(self, value):
        """
        Set the value of the PictureUploadPolicy input for this Choreo. ((optional, string) Indicates that an uploaded picture is available to a seller on the eBay site. Valid values are: Add and ClearAndAdd.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('PictureUploadPolicy', value)
    def set_PictureWatermark(self, value):
        """
        Set the value of the PictureWatermark input for this Choreo. ((optional, string) The type of watermark that should be applied to the pictures hosted by the eBay Picture Services. Valid values are: User and Icon.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('PictureWatermark', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('ResponseFormat', value)
    def set_SandboxMode(self, value):
        """
        Set the value of the SandboxMode input for this Choreo. ((conditional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('SandboxMode', value)
    def set_SiteID(self, value):
        """
        Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('SiteID', value)
    def set_UserToken(self, value):
        """
        Set the value of the UserToken input for this Choreo. ((required, string) A valid eBay Auth Token.)
        """
        super(UploadSiteHostedPicturesInputSet, self)._set_input('UserToken', value)

class UploadSiteHostedPicturesResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the UploadSiteHostedPictures Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.)
        """
        return self._output.get('Response', None)

class UploadSiteHostedPicturesChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return UploadSiteHostedPicturesResultSet(response, path)


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.containeranalysis.v1.model;

/**
 * A summary of how many vulnerability occurrences there are per resource and severity type.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Container Analysis API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VulnerabilityOccurrencesSummary extends com.google.api.client.json.GenericJson {

  /**
   * A listing by resource of the number of fixable and total vulnerabilities.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<FixableTotalByDigest> counts;

  static {
    // hack to force ProGuard to consider FixableTotalByDigest used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(FixableTotalByDigest.class);
  }

  /**
   * A listing by resource of the number of fixable and total vulnerabilities.
   * @return value or {@code null} for none
   */
  public java.util.List<FixableTotalByDigest> getCounts() {
    return counts;
  }

  /**
   * A listing by resource of the number of fixable and total vulnerabilities.
   * @param counts counts or {@code null} for none
   */
  public VulnerabilityOccurrencesSummary setCounts(java.util.List<FixableTotalByDigest> counts) {
    this.counts = counts;
    return this;
  }

  @Override
  public VulnerabilityOccurrencesSummary set(String fieldName, Object value) {
    return (VulnerabilityOccurrencesSummary) super.set(fieldName, value);
  }

  @Override
  public VulnerabilityOccurrencesSummary clone() {
    return (VulnerabilityOccurrencesSummary) super.clone();
  }

}


text:
package com.xwh.whatsapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
/**
 * Ö÷activity
 *
 * @author xwh
 *
 */
public class MainActivity extends Activity {

	// Á½¸ö¿ØÖÆÌøתµÄImageButton
	private ImageButton btn_hellowords;
	private ImageButton btn_zhaiyan;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btn_hellowords = (ImageButton) findViewById(R.id.btn_hellowords);
		btn_zhaiyan = (ImageButton) findViewById(R.id.btn_zhaiyan);

		// ¹Ø±ÕÒýµ¼Ò³
		closeGuide(MainActivity.this);

		// ·Ö±ðÉèÖõã»÷'þµÄ¼àÌýÆ÷
		btn_hellowords.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						HellowordsActivity.class);
				startActivity(intent);
			}
		});
		btn_zhaiyan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						ZhaiyanActivity.class);
				startActivity(intent);
			}
		});
	}

	private void closeGuide(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(
				SplashActivity.SHAREDPREFERENCES_NAME, MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.putBoolean(SplashActivity.KEY_GUIDE_ACTIVITY, false);
		editor.commit();
	}

	// Á½´Î·µ»Ø¼üÍ˳ö³ÌÐò
	private long exitTime = 0;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "ÔÙ°´Ò»´ÎÍ˳ö³ÌÐò",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}


text:
/* 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.
 */
package org.flowable.idm.engine.impl.cmd;

import java.io.Serializable;

import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.common.impl.persistence.entity.Entity;
import org.flowable.idm.api.Token;
import org.flowable.idm.engine.impl.persistence.entity.TokenEntity;
import org.flowable.idm.engine.impl.util.CommandContextUtil;

/**
 * @author Tijs Rademakers
 */
public class SaveTokenCmd implements Command<Void>, Serializable {

    private static final long serialVersionUID = 1L;
    protected Token token;

    public SaveTokenCmd(Token token) {
        this.token = token;
    }

    public Void execute(CommandContext commandContext) {
        if (token == null) {
            throw new FlowableIllegalArgumentException("token is null");
        }

        if (CommandContextUtil.getTokenEntityManager(commandContext).isNewToken(token)) {
            if (token instanceof TokenEntity) {
                CommandContextUtil.getTokenEntityManager(commandContext).insert((TokenEntity) token, true);
            } else {
                CommandContextUtil.getDbSqlSession(commandContext).insert((Entity) token);
            }
        } else {
            CommandContextUtil.getTokenEntityManager(commandContext).updateToken(token);
        }

        return null;
    }
}


text:
//a member variable/object to cache a pointer/object for the shared library function
ExodusFunctorBase efb_initcompany;

//a member function with the right arguments, returning a var or void
var initcompany(in nextcompanycode)
{

 //first time link to the shared lib and create/cache an object from it
 //passing current standard variables in mv
 if (efb_initcompany.pmemberfunction_==NULL)
  efb_initcompany.init("initcompany","exodusprogrambasecreatedelete_",mv);

 //define a function type (pExodusProgramBaseMemberFunction)
 //that can call the shared library object member function
 //with the right arguments and returning a var or void
 typedef var (ExodusProgramBase::*pExodusProgramBaseMemberFunction)(in);

 //call the shared library object main function with the right args,
 // returning a var or void
 return CALLMEMBERFUNCTION(*(efb_initcompany.pobject_),
 ((pExodusProgramBaseMemberFunction) (efb_initcompany.pmemberfunction_)))
  (nextcompanycode);

}
//#endif


text:
*A parallel Monte-Carlo Markov Chain package*

| **Documentation**   | **PackageEvaluator**                          |      **Build Status**        |
|:-------------------:|:---------------------------------------------:|:----------------------------:|
| [![][docs-stable-img]][docs-stable-url] [![][docs-latest-img]][docs-latest-url] | [![][pkg-0.4-img]][pkg-0.4-url] [![][pkg-0.5-img]][pkg-0.5-url] | [![][travis-img]][travis-url] [![][codecov-img]][codecov-url] |

Code base for the Generalized Metropolis-Hastings (GMH) algorithm [(Calderhead, 2014)](#refs).

## Documentation

- [**STABLE**][docs-stable-url] — **most recently tagged version of the documentation.**
- [**LATEST**][docs-latest-url] — **in-development version of the documentation.**

For detailed instructions on how to set up and run GMH in Amazon Web Services or in JuliaBox see [Quantifying Uncertainty](http://quantifyinguncertainty.github.io)

Some elementary examples of how to use the code are provided in repository [GMHExamples.jl](https://github.com/QuantifyingUncertainty/GMHExamples.jl).

A biological model for use with the code is provided in repository [GMHPhotoReceptor.jl](https://github.com/QuantifyingUncertainty/GMHPhotoReceptor.jl)

###<a name="refs"/>References
Calderhead B. (2014), *A general construction for parallelizing Metropolis-Hastings algorithms*, PNAS, Vol: 111, Pages: 17408-17413 [10.1073/pnas.1408184111](http://www.pnas.org/content/111/49/17408.abstract)

[contrib-url]: https://quantifyinguncertainty.github.io/GeneralizedMetropolisHastings.jl/latest/man/contributing.html

[docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg
[docs-latest-url]: https://quantifyinguncertainty.github.io/GeneralizedMetropolisHastings.jl/latest

[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://quantifyinguncertainty.github.io/GeneralizedMetropolisHastings.jl/stable

[travis-img]: https://travis-ci.org/quantifyinguncertainty/GeneralizedMetropolisHastings.jl.svg?branch=master
[travis-url]: https://travis-ci.org/QuantifyingUncertainty/GeneralizedMetropolisHastings.jl

[appveyor-img]: https://ci.appveyor.com/api/projects/status/egdu3hrptf3mnfc6/branch/master?svg=true
[appveyor-url]: https://ci.appveyor.com/project/MichaelHatherly/GeneralizedMetropolisHastings-jl-bqgcw/branch/master

[codecov-img]: https://codecov.io/gh/quantifyinguncertainty/GeneralizedMetropolisHastings.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/quantifyinguncertainty/GeneralizedMetropolisHastings.jl

[issues-url]: https://github.com/quantifyinguncertainty/GeneralizedMetropolisHastings.jl/issues

[pkg-0.4-img]: http://pkg.julialang.org/badges/GeneralizedMetropolisHastings_0.4.svg
[pkg-0.4-url]: http://pkg.julialang.org/?pkg=GeneralizedMetropolisHastings
[pkg-0.5-img]: http://pkg.julialang.org/badges/GeneralizedMetropolisHastings_0.5.svg
[pkg-0.5-url]: http://pkg.julialang.org/?pkg=GeneralizedMetropolisHastings
[pkg-0.6-img]: http://pkg.julialang.org/badges/GeneralizedMetropolisHastings_0.6.svg
[pkg-0.6-url]: http://pkg.julialang.org/?pkg=GeneralizedMetropolisHastings


text: {% load thumbnail %}


text:
package freemarker.template;

import java.util.List;

import freemarker.core.Environment;
import freemarker.template.utility.DeepUnwrap;

/**
 * "extended method" template language data type: Objects that act like functions. Their main application is calling
 * Java methods via {@link freemarker.ext.beans.BeansWrapper}, but you can implement this interface to create
 * top-level functions too. They are "extended" compared to the deprecated {@link TemplateMethodModel}, which could only
 * accept string parameters.
 *
 * <p>In templates they are used like {@code myMethod(1, "foo")} or {@code myJavaObject.myJavaMethod(1, "foo")}.
 */
public interface TemplateMethodModelEx extends TemplateMethodModel {

    /**
     * Executes the method call.
     *
     * @param arguments a {@link List} of {@link TemplateModel}-s,
     *     containing the arguments passed to the method. If the implementation absolutely wants
     *     to operate on POJOs, it can use the static utility methods in the {@link DeepUnwrap}
     *     class to easily obtain them. However, unwrapping is not always possible (or not perfectly), and isn't always
     *     efficient, so it's recommended to use the original {@link TemplateModel} value as much as possible.
     *
     * @return the return value of the method, or {@code null}. If the returned value
     *     does not implement {@link TemplateModel}, it will be automatically
     *     wrapped using the {@link Environment#getObjectWrapper() environment's
     *     object wrapper}.
     */
    public Object exec(List arguments) throws TemplateModelException;

}


text:
module Spree
  module Api
    class TaxCategoriesController < Spree::Api::BaseController

      def index
        @tax_categories = Spree::TaxCategory.all.order(:name)
        respond_with @tax_categories
      end

      def show
        @tax_categories = Spree::TaxCategory.find(params[:id])
        respond_with @tax_categories
      end

    end
  end
end


text:
package org.sakaiproject.samigo.search;

import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import net.htmlparser.jericho.Source;

import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.entityprovider.EntityProviderManager;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.EntityContentProducerEvents;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchService;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentData;
import org.sakaiproject.tool.assessment.entity.impl.ItemEntityProviderImpl;
import org.sakaiproject.tool.assessment.facade.ItemFacade;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;

@Slf4j
public class ItemContentProducer implements EntityContentProducer, EntityContentProducerEvents {

    private SearchService searchService;
    private SearchIndexBuilder searchIndexBuilder;
    private EntityManager entityManager = null;
    AssessmentService assessmentService  = new AssessmentService();

    protected void init() throws Exception {
       if ("true".equals(ServerConfigurationService.getString("search.enable", "false"))) {
            getSearchIndexBuilder().registerEntityContentProducer(this);
        }

    }

    @Override
    public Set<String> getTriggerFunctions() {
        Set<String> h = new HashSet<String>();
        h.add("sam.assessment.saveitem");
        h.add("sam.assessment.item.delete");
        h.add("sam.questionpool.deleteitem");
        h.add("sam.assessment.unindexitem");
        h.add("site.upd");
        return h;
    }

    /**
     * Destroy
     */
    protected void destroy()
    {
        log.info("destroy() ItemContentProducer");
    }

    private Reference getReference(String reference) {
        return null;
    }

    private EntityReference getEntityReference(String reference) {
        try {
            return new EntityReference("/sam_item/"+reference);
        } catch ( Exception ex ) {
            log.debug("Managed exception getting the item entity reference: " + ex.getClass().getName() + " : " + ex.getMessage());
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public boolean canRead(String eventResource) {
        String reference= getReferenceFromEventResource(eventResource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);

        try {
            ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());
            qhp.entityExists(er.getId());
            return true;
        } catch (Exception ex) {
            log.debug("Managed exception getting the item canRead function" + ex.getClass().getName() + " : " + ex.getMessage());
            return false;
        }
    }

    /**
     * {@inheritDoc}
     */
    public Integer getAction(Event event) {

        String evt = event.getEvent();
        if (evt == null) return SearchBuilderItem.ACTION_UNKNOWN;
        if (evt.equals("sam.assessment.saveitem")) {
            return SearchBuilderItem.ACTION_ADD;
        }
        if (evt.equals("sam.assessment.item.delete")||evt.equals("sam.questionpool.deleteitem")||evt.equals("sam.assessment.unindexitem")) {
            return SearchBuilderItem.ACTION_DELETE;
        }
        if (evt.equals("site.upd")) {
            //Special code not included in the normal IndexActions
            return 100;
        }
        return SearchBuilderItem.ACTION_UNKNOWN;
    }

    /**
     * {@inheritDoc}
     */
    public List getAllContent() {
        List all = new ArrayList();
        //Not needed.
        return all;
    }

    public HashMap<String,Object> getAllFields(String resourceName){
        HashMap<String,Object> allInfo = new HashMap();

        String reference = getReferenceFromEventResource(resourceName);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());
        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            List<String> questionPoolIds = qhp.questionPoolIds(item);
            if (questionPoolIds.size()>0){
                allInfo.put("isFromQuestionPool","true");
                allInfo.put("questionPoolId",qhp.questionPoolIds(item));
            }else{
                allInfo.put("isFromQuestionPool","false");
            }
            allInfo.put("questionId", getId(resourceName));
            try {
                allInfo.put("site", qhp.siteIds(item).get(0));
            }catch (Exception ex) {
                allInfo.put("site",null);
            }
            allInfo.put("tags", qhp.tags(item));
            allInfo.put("questionPoolId",qhp.questionPoolIds(item));
            allInfo.put("assessmentId", qhp.assessmentId(item));
            allInfo.put("hash", item.getHash());
            allInfo.put("type", "question");
            allInfo.put("subtype","item");

            allInfo.put("typeId",item.getTypeId().toString());
            if (item.getTypeId() == 14) {
                allInfo.put("qText", item.getThemeText());
            }else{
                allInfo.put("qText", item.getText());
            }

        }catch (Exception ex) {
            log.debug("Managed exception getting the question hash " + ex.getClass().getName() + " : " + ex.getMessage());
        }finally{
            return allInfo;
        }

    }

    /**
     * {@inheritDoc}
     */
    public String getContainer(String reference) {
        return "";
    }

    /**
     * {@inheritDoc}
     */
    public String getContent(String eventResource) {
        String reference = getReferenceFromEventResource(eventResource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            ItemFacade item = (ItemFacade)qhp.getEntity(er);
            String content = qhp.content(item);
            //We will filter the HTML here just before send to the index
            Source parseContent = new Source(content);
            return parseContent.getTextExtractor().toString();
        } catch (Exception e) {
            throw new RuntimeException(" Failed to get item content ", e);
        }

    }

    /**
     * {@inheritDoc}
     */
    public Reader getContentReader(String reference) {
        return new StringReader(getContent(reference));
    }

    /**
     * {@inheritDoc}
     */
    public Map getCustomProperties(String eventResource) {
        HashMap<String, List> customProperties = new HashMap();

        try {
            return customProperties;
        }catch (Exception ex){
            log.debug("Managed exception getting the question custom Properties" + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }

    }

    public List<String> getQuestionPoolId(String resource) {
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            return qhp.questionPoolIds(item);
        }catch (Exception ex) {
            log.debug("Managed exception getting the question pool id" + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }
    }

    public List<String> getTags(String resource) {
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            return qhp.tags(item);
        }catch (Exception ex) {
            log.debug("Managed exception getting the question tags" + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }
    }

    public String getHash(String resource) {
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            return item.getHash();
        }catch (Exception ex) {
            log.debug("Managed exception getting the question hash " + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getCustomRDF(String ref) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public String getId(String reference) {
        try {
            return "/sam_item/"+getReferenceFromEventResource(reference);
        } catch ( Exception ex ) {
            return "";
        }
    }

    /**
     * {@inheritDoc}
     */
    public List getSiteContent(String context) {
        List<Long> questionIdList = new ArrayList<Long>();

        List<AssessmentData> assessmentsList = assessmentService.getAllActiveAssessmentsbyAgent(context);
        for (AssessmentData assessmentData:assessmentsList){
            List<Long> assessmentQuestionIdsList = assessmentService.getQuestionsIdList(assessmentData.getAssessmentId());
            questionIdList.addAll(assessmentQuestionIdsList);
        }
        return questionIdList;
    }

    /**
     * {@inheritDoc}
     */
    public Iterator getSiteContentIterator(final String context) {

        return getSiteContent(context).iterator();

    }

    private String getSiteId(Reference ref) {
        String reference= getReferenceFromEventResource(ref.getReference());
        return getSiteId(reference);

    }

    /**
     * {@inheritDoc}
     */
    public String getSiteId(String resource) {
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            return qhp.siteIds(item).get(0);
        }catch (Exception ex) {
            log.debug("Managed exception getting the question site id" + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }
    }

    public String getAssessmentId(String resource){
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());
        try {
            ItemFacade item = (ItemFacade) qhp.getEntity(er);
            return qhp.assessmentId(item);
        }catch (Exception ex) {
            log.debug("Managed exception getting the question origin" + ex.getClass().getName() + " : " + ex.getMessage());
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getSubType(String reference) {
        return "item";
    }

    /**
     * {@inheritDoc}
     */
    public String getTitle(String reference) {
        return "";
    }

    /**
     * {@inheritDoc}
     */
    public String getTool() {
        return "";
    }

    /**
     * {@inheritDoc}
     */
    public String getType(String reference) {
        return "question";
    }

    /**
     * {@inheritDoc}
     */
    public String getUrl(String reference) {
        return "";
    }

    /**
     * {@inheritDoc}
     */
    public boolean isContentFromReader(String reference) {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isForIndex(String resource) {
        String reference = getReferenceFromEventResource(resource);
        //Basically is a true always... but in case the reference is not valid let's maintain this.
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        try {
            return qhp.entityExists(reference);
        } catch (Exception ex) {
            log.debug("Managed exception in isForIndex" + ex.getClass().getName() + " : " + ex.getMessage());
            return false;
        }

    }

    /**
     * {@inheritDoc}
     */
    public boolean matches(String resource) {
        String reference = getReferenceFromEventResource(resource);
        EntityProviderManager entityProviderManager = ComponentManager.get(EntityProviderManager.class);
        EntityReference er= new EntityReference("/sam_item/"+reference);
        ItemEntityProviderImpl qhp= (ItemEntityProviderImpl)entityProviderManager.getProviderByPrefix(er.getPrefix());

        return qhp.entityExists(reference);

    }

    /**
     * {@inheritDoc}
     */
    public boolean matches(Event event) {
        return matches(getReferenceFromEventResource(event.getResource()));
    }

    private String getReferenceFromEventResource(String resource){
        String reference;
        if (resource.indexOf(" itemId=")==-1){
            if (resource.indexOf("/sam_item/")==-1){
                reference = resource;
            }else {
                reference = resource.substring(resource.indexOf("/sam_item/") + 10);
            }
        }else{
            reference = resource.substring(resource.indexOf(" itemId=") + 8);
        }
        return reference;
    }

    public SearchService getSearchService() {
        return searchService;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public SearchIndexBuilder getSearchIndexBuilder() {
        return searchIndexBuilder;
    }

    public void setSearchIndexBuilder(SearchIndexBuilder searchIndexBuilder) {
        this.searchIndexBuilder = searchIndexBuilder;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tkporter.fabrictwitterkit">
</manifest>