text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * All queries related to profiles
 */
class BxDolProfileQuery extends BxDolDb implements iBxDolSingleton
{
    protected function __construct()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);

        parent::__construct();
    }

    /**
     * Prevent cloning the instance
     */
    public function __clone()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
    }

    /**
     * Get singleton instance of the class
     */
    public static function getInstance()
    {
        if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
            $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolProfileQuery();

        return $GLOBALS['bxDolClasses'][__CLASS__];
    }

    /**
     * Get all account profiles.
     * @param  string  $iAccountId account id
     * @return profile array
     */
    public function getProfilesByAccount ($iAccountId)
    {
        if (!$iAccountId)
            return array();

        $oAccountQuery = BxDolAccountQuery::getInstance();
        $aAccountInfo = $oAccountQuery->getInfoById($iAccountId);

        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? ORDER BY `id` = ? DESC", $iAccountId, $aAccountInfo['profile_id']);
        return $this->getAllWithKey($sSql, 'id');
    }

    /**
     * Get profile by content id, type and account.
     * @param  string $iAccountId account id
     * @return array  if aprofile ids, key is profile id
     */
    public function getProfileByContentTypeAccount ($iContentId, $sType, $iAccountId)
    {
        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `account_id` = ? AND `type` = ? AND `content_id` = ?", $iAccountId, $sType, $iContentId);
        return $this->getRow($sSql);
    }

    /**
     * Get profile by content id and type.
     * @param  string $iAccountId account id
     * @return array  if aprofile ids, key is profile id
     */
    public function getProfileByContentAndType ($iContentId, $sType)
    {
        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `content_id` = ? AND `type` = ?", $iContentId, $sType);
        $sKey = 'BxDolProfileQuery::getProfileByContentAndType' . $iContentId . $sType;
        $mixedResult = $this->fromMemory($sKey, 'getRow', $sSql);
        if (!$mixedResult)
            $this->cleanMemory($sKey);
        return $mixedResult;
    }

    /**
     * Insert account and content id association. Also if currect profile id is not defined - it updates current profile id in account.
     * @param $iAccountId account id
     * @param $iContentId content id
     * @param $sStatus profile status
     * @param $sType profile content type
     * @return inserted profile's id
     */
    public function insertProfile ($iAccountId, $iContentId, $sStatus, $sType = 'system')
    {
        $sSql = $this->prepare("INSERT INTO `sys_profiles` SET `account_id` = ?, `type` = ?, `content_id` = ?, `status` = ?", $iAccountId, $sType, $iContentId, $sStatus);
        if (!$this->query($sSql))
            return false;
        $iProfileId = $this->lastId();
        $this->getCurrentProfileByAccount($iAccountId); // it updates current profile id automatically if it is not defined
        return $iProfileId;
    }

    /**
     * Update profile's status
     * @param $iProfileId profile id
     * @param $sStatus profile status
     * @return true on success or false otherwise
     */
    public function changeStatus ($iProfileId, $sStatus)
    {
        return $this->_updateField ($iProfileId, 'status', $sStatus);
    }

    /**
     * Get current account profile.
     * @param  string  $iAccountId account id
     * @return current account's profile id
     */
    public function getCurrentProfileByAccount ($iAccountId)
    {
        $sSql = $this->prepare("SELECT `profile_id` FROM `sys_accounts` WHERE `id` = ? LIMIT 1", $iAccountId);
        $sKey = 'BxDolProfileQuery::getCurrentProfileByAccount' . $iAccountId;
        $iProfileId = $this->fromMemory($sKey, 'getOne', $sSql);
        if (!$iProfileId) {
            $this->cleanMemory($sKey);
            $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `account_id` = ? LIMIT 1", $iAccountId);
            $iProfileId = $this->getOne($sSql);
            if (!$iProfileId)
                return false;

            if (!BxDolAccountQuery::getInstance()->updateCurrentProfile($iAccountId, $iProfileId))
                return false;
        }
        return $iProfileId;
    }

    /**
     * Get profile by specified field name and value.
     * It is for internal usage only.
     * Use other funtions to get profile info, like getInfoById, etc.
     * @param  string $sField database field name
     * @param  mixed  $sValue database field value
     * @return array  with porfile info
     */
    protected function _getDataByField ($sField, $sValue)
    {
        $sSql = $this->prepare("SELECT * FROM `sys_profiles` WHERE `$sField` = ? LIMIT 1", $sValue);
        return $this->getRow($sSql);
    }

    /**
     * get profile id by id
     */
    public function getIdById($iId)
    {
        $sSql = $this->prepare("SELECT `id` FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iId);
        $sKey = 'BxDolProfileQuery::getIdById' . $iId;
        $mixedResult = $this->fromMemory($sKey, 'getOne', $sSql);
        if (!$mixedResult)
            $this->cleanMemory($sKey);
        return $mixedResult;
    }

    /**
     * get account info by profile id
     */
    public function getAccountInfoByProfileId($iId)
    {
        $sSql = $this->prepare("SELECT `a`.* FROM `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON (`p`.`account_id` = `a`.`id`) WHERE `p`.`id` = ? LIMIT 1", $iId);
        return $this->getRow($sSql);
    }

    /**
     * get account email by profile id
     */
    public function getEmailById($iId)
    {
        $a = $this->getAccountInfoByProfileId($iId);
        if (!$a || empty($a['email']))
            return false;
        return $a['email'];
    }

    /**
     * Get profile info by id
     * @param  int   $iID profile id
     * @return array with profile info
     */
    public function getInfoById( $iID )
    {
        return $this->_getDataByField('id', (int)$iID);
    }

	/**
     * Is profile online by id
     * @param  int $iId profile id
     * @return profile online status
     */
    public function isOnline($iId)
    {
        $sSql = $this->prepare("SELECT
        		`tp`.`id`
        	FROM `sys_profiles` AS `tp`
        	INNER JOIN `sys_accounts` AS `ta` ON `tp`.`account_id`=`ta`.`id`
        	INNER JOIN `sys_sessions` AS `ts` ON `tp`.`account_id`=`ts`.`user_id`
        	WHERE
        		`tp`.`id` = ? AND
        		`ta`.`profile_id`=`tp`.`id` AND
        		`ts`.`date` > (UNIX_TIMESTAMP() - 60 * ?)
        	LIMIT 1", $iId, (int)getParam('sys_account_online_time'));
        return (int)$this->getOne($sSql) > 0;
    }

    /**
     * Get profile field by specified field name and value.
     * In most cases it is for internal usage only.
     * Use other funtions to get profile info, like getIdByEmail, etc.
     * @param  string    $sFieldRequested database field name to return
     * @param  string    $sFieldSearch    database field name to search for
     * @param  mixed     $sValue          database field value
     * @return specified profile field value
     */
    protected function _getFieldByField ($sFieldRequested, $sFieldSearch, $sValue)
    {
        $sSql = $this->prepare("SELECT `$sFieldRequested` FROM `sys_profiles` WHERE `$sFieldSearch` = ? LIMIT 1", $sValue);
        return $this->getOne($sSql);
    }

    /**
     * Update some field by profile id
     * In most cases it is for internal usage only.
     * Use other funtions to get profile info, like updateLogged, etc.
     * @param  string    $sFieldRequested database field name to return
     * @param  string    $sFieldSearch    database field name to search for
     * @param  mixed     $sValue          database field value
     * @return specified profile field value
     */
    protected function _updateField ($iId, $sFieldForUpdate, $sValue)
    {
        $sSql = $this->prepare("UPDATE `sys_profiles` SET `$sFieldForUpdate` = ? WHERE `id` = ? LIMIT 1", $sValue, $iId);
        return $this->query($sSql);
    }

    /**
     * Delete profile info by id
     * @param  int      $iID profile id
     * @return affected rows
     */
    public function delete($iID)
    {
        $sSql = $this->prepare("DELETE FROM `sys_profiles` WHERE `id` = ? LIMIT 1", $iID);
        return $this->query($sSql);
    }

    /**
     * Reset deleted profile ids and assign system profile ids.
     * Should be called after profiles module deletion.
     * It can be called automatically if
     * @code
     * 'process_deleted_profiles' => 1
     * @endcode
     * is specified in module config.php file in 'uninstall' section.
     */
    public function processDeletedProfiles ()
    {
        $bResult = true;

        // reset deleted profiles
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` LEFT OUTER JOIN `sys_profiles` AS `p` ON `a`.`profile_id`=`p`.`id` SET `a`.`profile_id`='0' WHERE `p`.`id` IS NULL") !== false;

        // try to assign another non-system profile to reset accounts
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`<>'system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;

        // assign system profile to reset accounts
        $bResult &= $this->query("UPDATE `sys_accounts` AS `a` INNER JOIN `sys_profiles` AS `p` ON `a`.`id`=`p`.`account_id` AND `p`.`type`='system' AND `a`.`profile_id`='0' SET `a`.`profile_id`=`p`.`id`") !== false;

        return $bResult;
    }
}

/** @} */


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/left_menu_bg"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="40dp">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="用户名"

            android:textSize="12pt" />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="设置"

        android:textSize="9pt" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:layout_marginBottom="12dp"
        android:layout_marginTop="12dp"
        android:background="#888888" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
/**
 * @license Hypertext Application Language Processor (HALP)
 * (c) 2014 Michael Kurze, http://github.com/x1b/halp
 * License: MIT
 */
define( [ 'uri-templates' ], function( uriTemplates, undefined ) {

   var RESERVED = { '_links': true, '_embedded': true };

   return halp;

   ///////////////////////////////////////////////////////////////////////////////////////////////////////////

   /**
    * Instantiate a HAL processor by passing dependencies
    *
    * Each HAL processor instantiated in this manner will have its own cache universe within which (embedded)
    * resources are shared when traversing links.
    *
    * @param {object} q
    *    A promise implementation compatible with AngularJS $q
    * @param {object} http
    *    An HTTP client implementation which offers a `get` method compatible with AngularJS $http
    * @param {object} [options]
    *    An optional object with further configuration properties
    * @param {object} [options.protect]
    *    A protection function used to transform any (parts of) resources that are passed out to clients.
    *    Example behaviors compatible with HALP include freezing, cloning or deep-cloning objects.
    *    By default, no additional protection is applied for maximum performance.
    *    This means that clients will witness mutual modifications to the same resource's properties.
    * @param {object} [options.log]
    *    A logger compatible with the console.log provided by modern browsers.
    *    If no implementation is given, console.log is used.
    *
    * @returns {{link: link, resource: resource}}
    *    a hal factory that allows to create links and resources
    */
   function halp( q, http, options ) {
      options = options || {};
      var protect = options.protect || identity;
      var log = options.log || window.console;

      var resourceCache = {};

      return {
         link: link,
         resource: resource
      };

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      /**
       * Create a traversable link from a link representation
       *
       * @param {string|object} link
       *    A link representation, being either
       *    - a string, which is interpreted as a uri
       *    - a hal-link with at least the `href` attribute set
       * @param {string} link.href
       *    when passing a hal-link, its mandatory href attribute
       * @param {boolean} [link.templated]
       *    indicates that this link has template parameters
       * @param {boolean} [link.name]
       *    a name which allows to identify a link within a relation
       *
       * @returns {{fetch: Function, instantiate: Function, href: string}}
       *    A superset of the hal-link structure with the additional methods instantiate and fetch.
       */
      function link( link ) {
         link = link.href ? link : { href: link };
         var href = link.href;

         /**
          * Fetch a representation of the resource associated with this link.
          *
          * @param {boolean} [options.revalidate]
          * @param {object} [options.parameters]
          */
         function fetch( options ) {
            options = options || {};
            var revalidate = options.revalidate;
            if( !revalidate && resourceCache[ href ] ) {
               return q.when( resourceCache[ href ] );
            }

            return http.get( href, {} ).then(
               function( response ) {
                  var hal = response.data;
                  var res = resource( hal );
                  cachePut( res, href );
                  return res;
               },
               function( response ) {
                  log.warn( 'GET failed for %s (status: %s)', href, response.status );
                  return response;
               }
            );
         }

         var template;
         if( link.templated ) {
            uriTemplates( link.href );
         }

         /**
          * Instantiate a templated link into a non-templated link by substituting the template parameters
          *
          * @param {object} parameters The template parameters to fill in
          *
          * @returns {link}
          */
         function instantiate( parameters ) {
            return template ? template.fillFromObject( parameters ) : link.href;
         }

         return {
            fetch: fetch,
            instantiate: instantiate,
            href: href
         }
      }

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      /**
       * Create a traversable hypermedia resource representation from
       * @param hal
       * @returns {{hal: hal, properties: properties, link: link, links: links, follow: follow, followEach: followEach, followAll: followAll}}
       */
      function resource( hal ) {

         // links by normalized relation:
         var _links = {};
         var _nameCache = null;
         Object.keys( hal._links || {}  ).forEach( function( relation ) {
            _links[ normRel( relation ) ] = hal._links[ relation ];
            // :TODO: create+fill name-cache
         } );

         var _curieByPrefix = null;
         if( _links.curies ) {
            _curieByPrefix = {};
            _links.curies.forEach( function( curie ) {
               _curieByPrefix[ curie.name ] = link( curie );
            } );
         }

         // embedded resources by normalized relation:
         var _embedded = {};
         Object.keys( hal._embedded || {} ).forEach( function( relation, related ) {
            var rel = normRel( relation );
            _embedded[ rel ] = related;
            array( _embedded[ rel] ).forEach( function( hal ) {
               cachePut( resource( hal ) );
            } );
         } );

         /** @return {String} the normalized name (uri) of the given relation */
         function normRel( relation ) {
            if( _curieByPrefix ) {
               return resolveCurie( relation );
            }
            return relation;
         }

         function resolveCurie( maybeCurie ) {
            var splitPos = maybeCurie.indexOf( ':' );
            var prefix = splitPos === -1 ? maybeCurie : maybeCurie.substring( 0, splitPos );
            var curieLink = _curieByPrefix[ prefix ];
            if( !curieLink ) {
               return maybeCurie;
            }

            var rel = maybeCurie.substring( splitPos + 1 );
            return curieLink.instantiate( { rel: rel } );
         }

         /** @return {Object} an absolute link to a related resource */
         function link( relation ) {
            return absoluteLink( _links[ normRel( relation ) ] );
         }

         /**
          * @param {String} relation
          * @return {Array|Object} a list of links (in the given relation), or all links overall (no relation)
          */
         function links( relation ) {
            if( relation === undefined ) {
               return _links;
            }
            relation = normRel( relation );
            return _links[ relation ].map( function( link ) {
               return absoluteLink( link );
            } );
         }

         /**
          * @param {String} relation
          * @param {String=} options.name
          *
          * @return {Object} a promise to the related resource
          */
         function follow( relation, options ) {
            var rel = normRel( relation );
            var link;
            if( options.name ) {
               link = _nameCache[ rel ][ options.name ];
               if( link ) {
                  return link( relation ).filter( function( _ ) { return _.name === options.name; } );
               }
               return q.reject();
            }
            return link( relation ).fetch();
         }

         /** @return {Array} a list of promises, each to a related resource */
         function followEach( relation ) {
            return links( relation ).map( function( link ) {
               return link.fetch();
            } );
         }

         /** @return {Object} a promise to a list of related resources */
         function followAll( relation ) {
            return q.all( followEach( relation ) );
         }

         return {
            hal: function() {
               return protect( hal );
            },

            properties: function() {
               var properties = {};
               Object.keys( hal ).forEach( function( key ) {
                  if( !( key in RESERVED ) ) {
                     properties[ key ] = protect( hal[ key ] );
                  }
               } );
               return properties;
            },

            link: link,
            links: links,

            follow: follow,
            followEach: followEach,
            followAll: followAll
         }
      }

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      function cachePut( resource, href ) {
         if( href ) {
            resourceCache[ href ] = resource;
         }
         var selfLink = resource.link( 'self' );
         if( selfLink && selfLink.href ) {
            resourceCache[ href ] = resource;
         }
      }

   }

   function identity( _ ) { return _; }

   function array( _ ) {  return Array.isArray( _ ) ? _ : [ _ ]; }

} );


text:
package io.fnx.backend.tools.hydration;

import java.util.List;

/**
 * Recipe which describes hydration of single entity
 */
public interface HydrationRecipe<ENTITY, HC extends HydrationContext> {

    /**
     * @param entity entity to hydrate
     * @param ctx hydration context to take into account when populating properties
     * @return Collection of properties to hydrate
     */
    List<HydrationRecipeStep<ENTITY, HC>> buildSteps(ENTITY entity, HC ctx);

}


text:
@interface BECroppableImageView : UIView

@property (nonatomic) UIImage *image;
@property (nonatomic) UIEdgeInsets contentInset;
@property (nonatomic) CGFloat maskAlpha;
@property (nonatomic) CGFloat zoomStep;
@property (nonatomic) CGFloat zoomMargin;
@property (nonatomic) CGFloat maximumZoomScale;
@property (nonatomic) BOOL symmetrical;
@property (nonatomic, readonly) CGRect selectedFrame;
@property (nonatomic, readonly) CGRect cropFrame;
@property (nonatomic, readonly) CGPoint imageOffset;
@property (nonatomic, readonly) CGFloat imageScale;
@property (nonatomic, readonly) CGFloat imageRotation;
@property (nonatomic, readonly) CGAffineTransform imageTransform;

- (UIImage *)getCroppedImage;

@end


text:
  do { \
    OTS_FAILURE_MSG_(file, TABLE_NAME ": " __VA_ARGS__); \
    OTS_FAILURE_MSG("Table discarded"); \
    delete file->vdmx; \
    file->vdmx = 0; \
  } while (0)

namespace ots {

bool ots_vdmx_parse(OpenTypeFile *file, const uint8_t *data, size_t length) {
  Buffer table(data, length);
  file->vdmx = new OpenTypeVDMX;
  OpenTypeVDMX * const vdmx = file->vdmx;

  if (!table.ReadU16(&vdmx->version) ||
      !table.ReadU16(&vdmx->num_recs) ||
      !table.ReadU16(&vdmx->num_ratios)) {
    return OTS_FAILURE_MSG("Failed to read table header");
  }

  if (vdmx->version > 1) {
    DROP_THIS_TABLE("bad version: %u", vdmx->version);
    return true;  // continue transcoding
  }

  vdmx->rat_ranges.reserve(vdmx->num_ratios);
  for (unsigned i = 0; i < vdmx->num_ratios; ++i) {
    OpenTypeVDMXRatioRecord rec;

    if (!table.ReadU8(&rec.charset) ||
        !table.ReadU8(&rec.x_ratio) ||
        !table.ReadU8(&rec.y_start_ratio) ||
        !table.ReadU8(&rec.y_end_ratio)) {
      return OTS_FAILURE_MSG("Failed to read ratio header %d", i);
    }

    if (rec.charset > 1) {
      DROP_THIS_TABLE("bad charset: %u", rec.charset);
      return true;
    }

    if (rec.y_start_ratio > rec.y_end_ratio) {
      DROP_THIS_TABLE("bad y ratio");
      return true;
    }

    // All values set to zero signal the default grouping to use;
    // if present, this must be the last Ratio group in the table.
    if ((i < vdmx->num_ratios - 1u) &&
        (rec.x_ratio == 0) &&
        (rec.y_start_ratio == 0) &&
        (rec.y_end_ratio == 0)) {
      // workaround for fonts which have 2 or more {0, 0, 0} terminators.
      DROP_THIS_TABLE("superfluous terminator found");
      return true;
    }

    vdmx->rat_ranges.push_back(rec);
  }

  vdmx->offsets.reserve(vdmx->num_ratios);
  const size_t current_offset = table.offset();
  // current_offset is less than (2 bytes * 3) + (4 bytes * USHRT_MAX) = 256k.
  for (unsigned i = 0; i < vdmx->num_ratios; ++i) {
    uint16_t offset;
    if (!table.ReadU16(&offset)) {
      return OTS_FAILURE_MSG("Failed to read ratio offset %d", i);
    }
    if (current_offset + offset >= length) {  // thus doesn't overflow.
      return OTS_FAILURE_MSG("Bad ratio offset %d for ration %d", offset, i);
    }

    vdmx->offsets.push_back(offset);
  }

  vdmx->groups.reserve(vdmx->num_recs);
  for (unsigned i = 0; i < vdmx->num_recs; ++i) {
    OpenTypeVDMXGroup group;
    if (!table.ReadU16(&group.recs) ||
        !table.ReadU8(&group.startsz) ||
        !table.ReadU8(&group.endsz)) {
      return OTS_FAILURE_MSG("Failed to read record header %d", i);
    }
    group.entries.reserve(group.recs);
    for (unsigned j = 0; j < group.recs; ++j) {
      OpenTypeVDMXVTable vt;
      if (!table.ReadU16(&vt.y_pel_height) ||
          !table.ReadS16(&vt.y_max) ||
          !table.ReadS16(&vt.y_min)) {
        return OTS_FAILURE_MSG("Failed to read reacord %d group %d", i, j);
      }
      if (vt.y_max < vt.y_min) {
        DROP_THIS_TABLE("bad y min/max");
        return true;
      }

      // This table must appear in sorted order (sorted by yPelHeight),
      // but need not be continuous.
      if ((j != 0) && (group.entries[j - 1].y_pel_height >= vt.y_pel_height)) {
        DROP_THIS_TABLE("the table is not sorted");
        return true;
      }

      group.entries.push_back(vt);
    }
    vdmx->groups.push_back(group);
  }

  return true;
}

bool ots_vdmx_should_serialise(OpenTypeFile *file) {
  if (!file->glyf) return false;  // this table is not for CFF fonts.
  return file->vdmx != NULL;
}

bool ots_vdmx_serialise(OTSStream *out, OpenTypeFile *file) {
  OpenTypeVDMX * const vdmx = file->vdmx;

  if (!out->WriteU16(vdmx->version) ||
      !out->WriteU16(vdmx->num_recs) ||
      !out->WriteU16(vdmx->num_ratios)) {
    return OTS_FAILURE_MSG("Failed to write table header");
  }

  for (unsigned i = 0; i < vdmx->rat_ranges.size(); ++i) {
    const OpenTypeVDMXRatioRecord& rec = vdmx->rat_ranges[i];
    if (!out->Write(&rec.charset, 1) ||
        !out->Write(&rec.x_ratio, 1) ||
        !out->Write(&rec.y_start_ratio, 1) ||
        !out->Write(&rec.y_end_ratio, 1)) {
      return OTS_FAILURE_MSG("Failed to write ratio %d", i);
    }
  }

  for (unsigned i = 0; i < vdmx->offsets.size(); ++i) {
    if (!out->WriteU16(vdmx->offsets[i])) {
      return OTS_FAILURE_MSG("Failed to write ratio offset %d", i);
    }
  }

  for (unsigned i = 0; i < vdmx->groups.size(); ++i) {
    const OpenTypeVDMXGroup& group = vdmx->groups[i];
    if (!out->WriteU16(group.recs) ||
        !out->Write(&group.startsz, 1) ||
        !out->Write(&group.endsz, 1)) {
      return OTS_FAILURE_MSG("Failed to write group %d", i);
    }
    for (unsigned j = 0; j < group.entries.size(); ++j) {
      const OpenTypeVDMXVTable& vt = group.entries[j];
      if (!out->WriteU16(vt.y_pel_height) ||
          !out->WriteS16(vt.y_max) ||
          !out->WriteS16(vt.y_min)) {
        return OTS_FAILURE_MSG("Failed to write group %d entry %d", i, j);
      }
    }
  }

  return true;
}

void ots_vdmx_free(OpenTypeFile *file) {
  delete file->vdmx;
}

}  // namespace ots

#undef TABLE_NAME
#undef DROP_THIS_TABLE


text:
A microframework for Python 3, based on werkzeug.

[![MIT License](https://img.shields.io/pypi/l/rouver.svg)](https://pypi.python.org/pypi/rouver/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/rouver)](https://pypi.python.org/pypi/rouver/)
[![GitHub](https://img.shields.io/github/release/srittau/rouver/all.svg)](https://github.com/srittau/rouver/releases/)
[![pypi](https://img.shields.io/pypi/v/rouver.svg)](https://pypi.python.org/pypi/rouver/)
[![Travis CI](https://travis-ci.org/srittau/rouver.svg?branch=master)](https://travis-ci.org/srittau/rouver)

## Routing

```python
>>> from rouver.router import Router
>>> from rouver.response import respond_with_html, respond_with_json
>>> def get_index(environ, start_response):
...     return respond_with_html(start_response, "<div>Foo</div>")
>>> def get_count(environ, start_response):
...     return respond_with_json(start_response, {"count": 42})
>>> router = Router()
>>> router.add_routes([
...     ("", "GET", get_index),
...     ("count", "GET", get_count),
... ])

```

Routes with placeholders:

```python
>>> def get_addition(environ, start_response):
...     num1, num2 = path
...     return response_with_json(start_response, {"result": num1 + num2})
>>> def numeric_arg(request, path, value):
...     return int(value)
>>> router.add_template_handler("numeric", numeric_arg)
>>> router.add_routes([
...     ("add/{numeric}/{numeric}", "GET", get_addition),
... ])
```

Routes with wildcards:

```python
>>> def get_wildcard(environ, start_response):
...     # environ["rouver.wildcard_path"] contains the remaining path
...     return respond(start_response)
>>> router.add_routes([
...     ("wild/*", "GET", get_wildcard),
... ])
```

Sub-routers:

```python
>>> def get_sub(environ, start_response):
...     return respond(start_response)
>>> sub_router = Router()
>>> sub_router.add_routes([
...     ("sub", "GET", get_sub),
... ])
>>> router.add_sub_router("parent", sub_router)
```

## Argument Handling

```python
>>> from rouver.args import Multiplicity, parse_args
>>> from rouver.response import respond_with_json
>>> def get_count_with_args(request, path, start_response):
...     args = parse_args(request.environ, [
...         ("count", int, Multiplicity.REQUIRED),
...     ])
...     return respond_with_json({"count": args["count"]})
```

## WSGI Testing

```python
>>> from rouver.test import create_request, test_wsgi_app
>>> request = create_request("GET", "/my/path")
>>> response = test_wsgi_app(app, request)
>>> response.assert_status(HTTPStatus.OK)
```


text:
package org.jtwig.translate.function.extract;

import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import org.jtwig.environment.Environment;
import org.jtwig.exceptions.CalculationException;
import org.jtwig.functions.FunctionRequest;
import org.jtwig.translate.environment.TranslateEnvironment;
import org.jtwig.translate.message.decorate.ReplacementMessageDecorator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.*;

public class TranslateParameterExtractorTest {
    private final LocaleExtractor localeExtractor = mock(LocaleExtractor.class);
    private final ReplacementsExtractor replacementsExtractor = mock(ReplacementsExtractor.class);
    private final LocaleOrReplacementsExtractor localeOrReplacementsExtractor = mock(LocaleOrReplacementsExtractor.class);
    private TranslateParameterExtractor underTest = new TranslateParameterExtractor(localeExtractor, replacementsExtractor, localeOrReplacementsExtractor);

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void extractChoiceForTwoArguments() throws Exception {
        Locale locale = Locale.CANADA;
        TranslateEnvironment translateEnvironment = mock(TranslateEnvironment.class);
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Supplier<Locale> supplier = mock(Supplier.class);
        when(supplier.get()).thenReturn(locale);
        when(request.getEnvironment().parameter("translate-extension-environment")).thenReturn(translateEnvironment);
        when(translateEnvironment.getLocaleSupplier()).thenReturn(supplier);

        TranslateParameterExtractor.TranslateChoiceParameters result =
                underTest.extractNoExtraArguments(request);

        assertThat(result.getLocale(), is(locale));
        assertThat(result.getReplacements(), is(empty()));
    }

    @Test
    public void extractForThreeArgumentsWhenNoArgumentPresent() throws Exception {
        Object value = new Object();
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);

        when(request.getEnvironment()).thenReturn(environment);
        when(localeOrReplacementsExtractor.extractor(request.getEnvironment(), value))
                .thenReturn(new LocaleOrReplacementsExtractor.Result(
                        Optional.<Locale>absent(),
                        Optional.<Collection<ReplacementMessageDecorator.Replacement>>absent()));

        expectedException.expect(CalculationException.class);
        expectedException.expectMessage(containsString(String.format("Expecting map or locale, but got '%s'", value)));

        underTest.extractForOneExtraArgument(request, value);
    }

    @Test
    public void extractForThreeArgumentsWhenLocalePresent() throws Exception {
        Object value = new Object();
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);
        Supplier<Locale> supplier = mock(Supplier.class);
        Locale locale = Locale.CANADA;
        TranslateEnvironment translateEnvironment = mock(TranslateEnvironment.class);

        when(request.getEnvironment()).thenReturn(environment);
        when(environment.parameter("currentLocaleSupplier")).thenReturn(supplier);
        when(request.get(2)).thenReturn(value);
        when(environment.parameter("translate-extension-environment")).thenReturn(translateEnvironment);
        when(translateEnvironment.getLocaleSupplier()).thenReturn(supplier);
        when(localeOrReplacementsExtractor.extractor(request.getEnvironment(), value))
                .thenReturn(new LocaleOrReplacementsExtractor.Result(
                        Optional.of(locale),
                        Optional.<Collection<ReplacementMessageDecorator.Replacement>>absent()));

        TranslateParameterExtractor.TranslateChoiceParameters result = underTest.extractForOneExtraArgument(request, value);

        assertThat(result.getLocale(), is(locale));
        assertThat(result.getReplacements(), is(empty()));
    }

    @Test
    public void extractForThreeArgumentsWhenReplacementsPresent() throws Exception {
        Collection<ReplacementMessageDecorator.Replacement> replacements = Collections.singletonList(mock(ReplacementMessageDecorator.Replacement.class));
        Object value = new Object();
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);
        Supplier<Locale> supplier = mock(Supplier.class);
        Locale locale = Locale.CANADA;
        TranslateEnvironment translateEnvironment = mock(TranslateEnvironment.class);

        when(supplier.get()).thenReturn(locale);
        when(request.getEnvironment()).thenReturn(environment);
        when(environment.parameter("translate-extension-environment")).thenReturn(translateEnvironment);
        when(translateEnvironment.getLocaleSupplier()).thenReturn(supplier);
        when(localeOrReplacementsExtractor.extractor(request.getEnvironment(), value))
                .thenReturn(new LocaleOrReplacementsExtractor.Result(
                        Optional.<Locale>absent(),
                        Optional.of(replacements)));

        TranslateParameterExtractor.TranslateChoiceParameters result = underTest.extractForOneExtraArgument(request, value);

        assertThat(result.getLocale(), is(locale));
        assertThat(result.getReplacements(), is(replacements));
    }

    @Test
    public void extractForFourArgumentsWhenReplacementsNotPresent() throws Exception {
        Object argument2 = new Object();
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);

        when(request.getEnvironment()).thenReturn(environment);
        when(replacementsExtractor.extract(environment, argument2)).thenReturn(Optional.<Collection<ReplacementMessageDecorator.Replacement>>absent());

        expectedException.expect(CalculationException.class);
        expectedException.expectMessage(containsString(String.format("Expecting map, but got '%s'", argument2)));

        underTest.extractForTwoExtraArguments(request, argument2, new Object());
    }

    @Test
    public void extractForFourArgumentsWhenLocaleNotPresent() throws Exception {
        Collection<ReplacementMessageDecorator.Replacement> replacements = Collections.singletonList(mock(ReplacementMessageDecorator.Replacement.class));
        Object argument2 = new Object();
        Object argument3 = new Object();
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);

        when(request.getEnvironment()).thenReturn(environment);
        when(replacementsExtractor.extract(environment, argument2)).thenReturn(Optional.of(replacements));
        when(localeExtractor.extract(environment, argument3)).thenReturn(Optional.<Locale>absent());

        expectedException.expect(CalculationException.class);
        expectedException.expectMessage(containsString(String.format("Expecting locale, but got '%s'", argument3)));

        underTest.extractForTwoExtraArguments(request, argument2, argument3);
    }

    @Test
    public void extractForFourArgumentsWhenBothPresent() throws Exception {
        Collection<ReplacementMessageDecorator.Replacement> replacements = Collections.singletonList(mock(ReplacementMessageDecorator.Replacement.class));
        Object argument2 = new Object();
        Object argument3 = new Object();
        Locale locale = Locale.CANADA;
        FunctionRequest request = mock(FunctionRequest.class, RETURNS_DEEP_STUBS);
        Environment environment = mock(Environment.class);

        when(request.getEnvironment()).thenReturn(environment);
        when(replacementsExtractor.extract(environment, argument2)).thenReturn(Optional.of(replacements));
        when(localeExtractor.extract(environment, argument3)).thenReturn(Optional.of(locale));

        TranslateParameterExtractor.TranslateChoiceParameters result = underTest.extractForTwoExtraArguments(request, argument2, argument3);

        assertThat(result.getLocale(), is(locale));
        assertThat(result.getReplacements(), is(replacements));
    }
}


text:
thread
======

Portable C++ multi-threading. C++11, C++14.

### License

Distributed under the [Boost Software License, Version 1.0](http://boost.org/LICENSE_1_0.txt).


text:
module Spree
  module Admin
    class GoogleTrustedStoreSettingsController < Spree::Admin::BaseController
      def show
        redirect_to action: :edit
      end
      def index
        redirect_to action: :edit
      end

      def edit
        @google_trusted_store_setting = GoogleTrustedStoreSetting.instance
      end
    end
  end
end


text:
 /***************************************************************************
 * Class: Fusion.Widget.LayerManager
 *
 * Displays a LayerManager of all the layers in the map as a collapsable tree.
 *
 * ShowRootFolder (boolean, optional)
 *
 * This controls whether the tree will have a single root node that
 * contains the name of the map as its label.  By default, the root
 * node does not appear.  Set to "true" or "1" to make the root node
 * appear.
 *
 * RootFolderIcon: (string, optional)
 *
 * The url to an image to use for the root folder.  This only has an
 * affect if ShowRootFolder is set to show the root folder.
 *
 * LayerThemeIcon: (string, optional)
 *
 * The url to an image toTopography use for layers that are currently themed.
 *
 * DisabledLayerIcon: (string, optional)
 *
 * The url to an image to use for layers that are out of scale.
 *
 * **********************************************************************/

Fusion.Widget.LayerManager = OpenLayers.Class(Fusion.Widget,  {
    currentNode: null,
    bIsDrawn: false,
    map: null,
    initializeWidget: function(widgetTag) {
        //console.log("initializeWidget");
        var json = widgetTag.extension;
        this.delIconSrc = json.DeleteIcon ? json.DeleteIcon[0] : 'images/icons/select-delete.png';

        Fusion.addWidgetStyleSheet(widgetTag.location + 'LayerManager/LayerManager.css');
        this.cursorNormal = ["url('images/grab.cur'),move", 'grab', '-moz-grab', 'move'];
        this.cursorDrag = ["url('images/grabbing.cur'),move", 'grabbing', '-moz-grabbing', 'move'];
        this.map = this.getMap();
        this.map.registerForEvent(Fusion.Event.MAP_LOADED, OpenLayers.Function.bind(this.mapLoaded, this));
        this.map.registerForEvent(Fusion.Event.MAP_RELOADED, OpenLayers.Function.bind(this.mapReLoaded, this));
        // update changes to the legend in this widget
        this.map.aMaps[0].registerForEvent(Fusion.Event.LAYER_PROPERTY_CHANGED, OpenLayers.Function.bind(this.layerChanged,this));
    },

    mapLoaded: function() {
        this.draw();
    },
    layerChanged: function() {
        this.updateSessionMapFile();
    },
    mapReLoaded: function(){
        this.draw();
   },
   /**
     * remove the dom objects representing the legend layers and groups
     */
    clear: function(node) {
        //console.log("clear");
        while (node.childNodes.length > 0) {
          this.clear(node.childNodes[0]);
            node.destroy(node.childNodes[0]);
        }
    },

    /**
     * Draws the layer manager
     *
     * @param r Object the reponse xhr object
     */
    draw: function(r) {
        //console.log("draw");
      if (this.mapList) {
        this.clear(this.mapList);
        this.mapList.destroy();
        this.mapList = null;
      }

      //create the master UL element to hold the list of layers
      this.mapList = document.createElement('ul');
      this.mapList.className = 'jxLman';
      this.domObj.appendChild(this.mapList);

      //this processes the OL layers
      var map = this.getMap();

      for (var i=0; i<map.aMaps.length; ++i) {
        var mapBlock = document.createElement('li');
        mapBlock.className = 'jxLmanMap';
        mapBlock.id = 'mapBlock_'+i;

        //add a handle so the map blocks can be re-arranged
        var handle = document.createElement('a');
        handle.innerHTML = map.aMaps[i]._sMapTitle;
        handle.className = 'jxLmanHandle';
        mapBlock.appendChild(handle);

        this.mapList.appendChild(mapBlock);
        this.processMapBlock(mapBlock, map.aMaps[i]);
      }

      if (map.aMaps.length >1) {
        var options = [];
        options.onUpdate = OpenLayers.Function.bind(this.updateMapBlock, this, map);
        options.handle = 'jxLmanHandle';
        options.scroll = this.domObj.id;
        Sortable.create(this.mapList.id, options);
      }
    },

    processMapBlock: function(blockDom, map) {
      //console.log("processMapBlock");
      var mapBlockList = document.createElement('ul');
      mapBlockList.className = 'jxLmanSet';
      mapBlockList.id = 'fusionLayerManager_'+map.getMapName();
      blockDom.appendChild(mapBlockList);
      map.layerPrefix = 'layer_';   //TODO make this unique for each block
      //this process all layers within an OL layer
      var processArray = map.aLayers;

      for (var i=0; i<processArray.length; ++i) {
        var blockItem = document.createElement('li');
        blockItem.className = 'jxLmanLayer';
        blockItem.id = map.layerPrefix+i;
        mapBlockList.appendChild(blockItem);
        this.createItemHtml(blockItem, processArray[i]);
        blockItem.layer = processArray[i];
      }

      var sortableOptions = {
                constrain: true,
                clone: false,
                revert: true,
                onComplete: OpenLayers.Function.bind(this.updateLayer, $(mapBlockList.id), map)
            };
    var mySortables = new Sortables(mapBlockList.id, sortableOptions);
    },

  createItemHtml: function(parent, layer) {
    var delIcon = document.createElement('img');
    delIcon.src = this.delIconSrc;
    OpenLayers.Event.observe(delIcon, 'click', OpenLayers.Function.bind(this.deleteLayer, this, layer));
    delIcon.style.visibility = 'hidden';
    parent.appendChild(delIcon);

    var visSelect = document.createElement('input');
    visSelect.type = 'checkbox';
    OpenLayers.Event.observe(visSelect, 'click', OpenLayers.Function.bind(this.visChanged, this, layer));
    parent.appendChild(visSelect);
    if (layer.visible) {
      visSelect.checked = true;
    } else {
      visSelect.checked = false;
    }

    var label = document.createElement('a');
    label.innerHTML = layer.legendLabel;
    OpenLayers.Event.observe(label, 'mouseover', OpenLayers.Function.bind(this.setGrabCursor, this));
    OpenLayers.Event.observe(label, 'mousedown', OpenLayers.Function.bind(this.setDragCursor, this));
    OpenLayers.Event.observe(label, 'mouseout', OpenLayers.Function.bind(this.setNormalCursor, this));
    parent.appendChild(label);

    OpenLayers.Event.observe(parent, 'mouseover', OpenLayers.Function.bind(this.setHandleVis, this, delIcon));
    OpenLayers.Event.observe(parent, 'mouseout', OpenLayers.Function.bind(this.setHandleHide, this, delIcon));
  },

  setHandleVis: function(delIcon) {
    delIcon.style.visibility = 'visible';
  },

  setHandleHide: function(delIcon) {
    delIcon.style.visibility = 'hidden';
  },

  setGrabCursor: function(ev) {
    this.setCursor(this.cursorDrag, ev.currentTarget.parentNode);
  },

  setDragCursor: function(ev) {
   this.setCursor(this.cursorDrag, ev.currentTarget.parentNode);
  },

  setNormalCursor: function(ev) {
    this.setCursor('auto', ev.currentTarget.parentNode);
  },

  setCursor : function(cursor, domObj) {
      this.cursor = cursor;
      if (cursor && cursor.length && typeof cursor == 'object') {
          for (var i = 0; i < cursor.length; i++) {
              domObj.style.cursor = cursor[i];
              if (domObj.style.cursor == cursor[i]) {
                  break;
              }
          }
      } else if (typeof cursor == 'string') {
          domObj.style.cursor = cursor;
      } else {
          domObj.style.cursor = 'auto';
      }
  },

  updateLayer: function(map, ul) {
   //console.log("updateLayer");
    //reorder the layers in the client as well as the session
    var aLayerIndex = [];
    var aIds = [];
    var nLayers = this.childNodes.length;
    for (var i=0; i<nLayers; ++i) {
      aIds[i] = this.childNodes[i].id.split('_');
      var index = parseInt(aIds[i].pop());
      aLayerIndex.push(index);
      this.childNodes[i].id = '';
    }

    //reset the ID's on the LI elements to be in order
    for (var i=0; i<this.childNodes.length; ++i) {
      var node = this.childNodes[i];
      aIds[i].push(i);
      node.id = aIds[i].join('_');
      node.childNodes[1].checked = node.layer.isVisible()
    }

    map.reorderLayers(aLayerIndex);
  },

  updateMapBlock: function(map, ul) {
    //reorder the OL layers
  },

  deleteLayer: function(layer, ev) {
   // console.log("deleteLayer");
    var targetLI = (new Event(ev)).target.parentNode;
    var ul = targetLI.parentNode;
    $(targetLI).dispose();
    this.updateLayer(layer.oMap, ul);
  },

  visChanged: function(layer2, ev) {
    var target = (new Event(ev)).target;
    var layer = target.parentNode.layer;
    if (target.checked) {
      layer.show();
    } else {
      layer.hide();
    }
  },
  updateSessionMapFile: function(){
   // console.log("updateSessionMapFile");
    // get map
    var map = this.getMap();
    var aMaps = map.getAllMaps();
    var currentMap = aMaps[0];
    var sessionId = aMaps[0].getSessionID();

    // get all layers
    var oLayers = currentMap.aLayers;
    var aLayerNames = [];
    var visibleLayers = [];
    for(var i=0;i<oLayers.length;i++){
        aLayerNames.push(oLayers[i].layerName);
        if(oLayers[i].visible == true){
            visibleLayers.push(oLayers[i].layerName);
        }
    }

    // prepare ajax req
    var params =  '&session='+sessionId+'&mapname='+ this.getMap().getMapName()+'&visLayers='+visibleLayers+'&layers='+aLayerNames;
    var options = {parameters: params};

    // fire the request no need to return
    var m = this.getMap().aMaps[0];
    var url = 'layers/' + m.arch + '/' + Fusion.getScriptLanguage() + "/updateSessionMapFile." + Fusion.getScriptLanguage()
    Fusion.ajaxRequest(  url, options);
  }

});


text:
/**
 * Admin Home Controller
 * Created by Matt on 6/18/17.
 */
(function () {
  'use strict';

  angular
      .module('KnowYourRep')
      .controller('adminHomeController', adminHomeController);

  function adminHomeController(adminService) {
      var vm = this;

      var rightTab = 'views/admin/templates/tabs/blank.tab.view.client.html';

      function init() {
          vm.users = [];
      }
      init();

      vm.getRightView = getRightView;
      vm.findAllUsers = findAllUsers;
      vm.deleteUser = deleteUser;
      vm.editUser = editUser;
      vm.updateUser = updateUser;
      vm.createUser = createUser;
      vm.createAdmin = createAdmin;
      vm.findAllReps = findAllReps;
      vm.removeRep = removeRep;
      vm.editRep = editRep;
      vm.updateRep = updateRep;

      function updateRep() {
          reset();
          if(vm.repEditForm.$invalid) {
              return;
          }
          adminService
              .updateRep(vm.rep)
              .then(function (success) {
                  vm.message = "Update Success!";
              }, function (err) {
                  vm.error = "Error: " + err;
              })
      }

      function editRep(rep) {
          reset();
          vm.rep = rep;
          rightTab = 'views/admin/templates/tabs/rep-edit.tab.view.client.html';
      }

      function removeRep(repId) {
          reset();
          adminService
              .deleteRep(repId)
              .then(function (success) {
                  findAllReps();
              }, function (err) {
                  vm.error = "Failed to delete rep: " + repId;
              });
      }

      function findAllReps() {
          reset();
          rightTab = 'views/admin/templates/tabs/reps.tab.view.client.html';
          adminService
              .findAllReps()
              .then(function (reps) {
                  vm.reps = reps;
              })
      }

      function createAdmin() {
          reset();
          vm.user = {
              admin: true
          };
          rightTab = 'views/admin/templates/tabs/user-new.tab.view.client.html';
      }

      function createUser(user) {
          reset();
          if (user === null || typeof user === 'undefined') {
              vm.user = {};
              rightTab = 'views/admin/templates/tabs/user-new.tab.view.client.html';
              return;
          }

          adminService
              .createUser(user)
              .then(function (success) {
                  vm.message = "Created the user";
                  rightTab = 'views/admin/templates/tabs/users.tab.view.client.html';
                  findAllUsers();
              }, function (err) {
                  vm.error = "Error: " + err;
              })
      }

      function updateUser() {
          reset();
          adminService
              .updateUser(vm.user)
              .then(function (success) {
                  vm.message = "Update Success!";
              }, function (err) {
                  vm.error = "Error: " + err;
              })
      }

      function editUser(user) {
          reset();
          vm.user = user;
          rightTab = 'views/admin/templates/tabs/user-edit.tab.view.client.html';
      }

      function deleteUser(userId) {
          reset();
          adminService
              .deleteUser(userId)
              .then(function (success) {
                  rightTab = 'views/admin/templates/tabs/users.tab.view.client.html';
                  findAllUsers();
              }, function (err) {
                  vm.error = "Failed to delete user: " + userId;
              });
      }

      function findAllUsers() {
          reset();
          rightTab = 'views/admin/templates/tabs/users.tab.view.client.html';
          adminService
              .findAllUsers()
              .then(function (users) {
                  vm.users = users;
              })
      }

      function getRightView() {
          return rightTab;
      }

      function reset() {
          vm.message = null;
          vm.error = null;
      }
  }
})();


text:
package org.chocosolver.util.objects.setDataStructures.swapList;

import gnu.trove.list.array.TIntArrayList;
import org.chocosolver.memory.IEnvironment;
import org.chocosolver.memory.IStateInt;
import org.chocosolver.util.objects.setDataStructures.ISet;
import org.chocosolver.util.objects.setDataStructures.ISetIterator;
import org.chocosolver.util.objects.setDataStructures.SetType;

/**
 * Set of integers based on BipartiteSet implementation for small sets (arraylist inside)
 * BEWARE : CANNOT BOTH ADD AND REMOVE ELEMENTS DURING SEARCH
 *
 * @author : Charles Prud'homme, Jean-Guillaume FAGES (fix remove)
 */
public class Set_Std_Swap2 implements ISet {

	//***********************************************************************************
	// VARIABLES
	//***********************************************************************************

    protected IStateInt size;
    protected TIntArrayList values;
    private ISetIterator iter = newIterator();

    //***********************************************************************************
	// CONSTRUCTOR
	//***********************************************************************************

	/**
	 * Creates an empty bipartite set
	 * @param e backtracking environment
	 */
	public Set_Std_Swap2(IEnvironment e){
		size = e.makeInt(0);
        values = new TIntArrayList(4);
	}

	//***********************************************************************************
	// METHODS
	//***********************************************************************************

    @Override
    public boolean add(int element) {
        if(!contains(element)){
            int pos = size.add(1);
            values.insert(pos - 1, element);
            return true;
        }
        return false;
    }

    @Override
    public boolean remove(int element) {
        int pos = values.indexOf(element);
        int s = size();
        if(pos > -1 && pos < s){
            iter.notifyRemoving(element);
            s--;
            int t = values.get(s);
            values.set(pos, t);
            values.set(s, element);
            size.add(-1);
            return true;
        }else return false;
    }

    @Override
    public boolean contains(int element) {
        int pos = values.indexOf(element);
        return pos > -1 && pos < size();
    }

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

    @Override
    public void clear() {
        size.set(0);
    }

    @Override
    public int min() {
        if(isEmpty()) throw new IllegalStateException("cannot find minimum of an empty set");
        int min = values.get(0);
        for(int i = 1; i< size(); i++){
            if(min > values.get(i)){
                min = values.get(i);
            }
        }
        return min;
    }

    @Override
    public int max() {
        if(isEmpty()) throw new IllegalStateException("cannot find maximum of an empty set");
        int max = values.get(0);
        for(int i = 1; i< size(); i++){
            if(max < values.get(i)){
                max = values.get(i);
            }
        }
        return max;
    }

    @Override
    public SetType getSetType() {
        return SetType.SMALLBIPARTITESET;
    }

    @Override
    public String toString() {
        StringBuilder st = new StringBuilder("{");
        ISetIterator iter = newIterator();
        while (iter.hasNext()) {
            st.append(iter.nextInt()).append(", ");
        }
        st.append("}");
        return st.toString().replace(", }","}");
    }

    @Override
    public ISetIterator iterator(){
        iter.reset();
        return iter;
    }

    @Override
    public ISetIterator newIterator(){
        return new ISetIterator() {
            private int idx;
            @Override
            public void reset() {
                idx = 0;
            }
            @Override
            public void notifyRemoving(int item) {
                if(idx>0 && item == values.get(idx-1)){
                    idx--;
                }
            }
            @Override
            public boolean hasNext() {
                return idx < size();
            }
            @Override
            public int nextInt() {
                idx ++;
                return values.get(idx-1);
            }
        };
    }
}


text:
#ifndef SEMIDIRECT_HPP
#define SEMIDIRECT_HPP

#include <sstream>
#include <utility>  /* pair */
#include "Groups/BasicGroup.hpp"
#include "Groups/Util.hpp"
#include "Groups/internals.hpp"  /* cartesian */

namespace Groups {
 template<class G, class H, class Func>
 class Semidirect : public basic_group< std::pair<typename G::elem_t,
						  typename H::elem_t> >,
		    public cmp_with< Semidirect<G,H,Func> > {
 public:
  typedef typename G::elem_t left_t;
  typedef typename H::elem_t right_t;
  typedef std::pair<left_t, right_t> elem_t;  // Why is this necessary?

  Semidirect(const G& g, const H& h, const Func& f)
   : _left(g), _right(h), _phi(f) { }

  virtual ~Semidirect() { }

  virtual elem_t oper(const elem_t& x, const elem_t& y) const {
   return elem_t(_left.oper(x.first, phi(x.second, y.first)),
		 _right.oper(x.second, y.second));
  }

  virtual elem_t identity() const {
   return elem_t(_left.identity(), _right.identity());
  }

  virtual std::vector<elem_t> elements() const {
   return cartesian(_left.elements(), _right.elements());
  }

  virtual elem_t invert(const elem_t& x) const {
   const U& binv = _right.invert(x.second);
   return elem_t(phi(binv, _left.invert(x.first)), binv);
  }

  virtual int order() const {return _left.order() * _right.order(); }

  virtual int order(const elem_t& x) const {
   // Should the results be cached somehow?
   int i = 1;
   elem_t val = x;
   while (val.first != _left.identity() && val.second != _right.identity()) {
    val = oper(val, x);
    i++;
   }
   if (val.first == _left.identity()) return i * _right.order(val.second);
   else return i * _left.order(val.first);
  }

  virtual std::string showElem(const elem_t& x) const {
   if (x.first == _left.identity() && x.second == _right.identity()) {
    return "1";
   } else {
    std::ostringstream out;
    out << '(' << _left.showElem(x.first) << ", " << _right.showElem(x.second)
	<< ')';
    return out.str();
   }
  }

/*
  virtual bool isAbelian() const {
   return _left.isAbelian() && _right.isAbelian() && [Func is the trivial homomorphism];
  }
*/

  virtual Semidirect<G,H,Func>* copy() const {return new Semidirect(*this); }

  virtual int cmp(const basic_group<elem_t>* other) const {
   int ct = cmpTypes(*this, *other);
   if (ct != 0) return ct;
   const Semidirect<G,H,Func>* c
    = static_cast<const Semidirect<G,H,Func>*>(other);
   return cmp(*c);
  }

  virtual int cmp(const Semidirect<G,H>& other) const {
   int cmpLeft = _left.cmp(other._left);
   if (cmpLeft != 0) return cmpLeft;
   int cmpRight = _right.cmp(other._right);
   if (cmpRight != 0) return cmpRight;
   return _phi < other._phi ? -1 : _phi > other._phi ? 1 : 0;
  }

  virtual bool contains(const elem_t& x) const {
   return _left.contains(x.first) && _right.contains(x.second);
  }

  virtual int indexElem(const elem_t& x) const {
   if (contains(x))
    return _left.indexElem(x.first)*_right.order() + _right.indexElem(x.second);
   else throw group_mismatch("Semidirect::indexElem");
  }

	G& left()        {return _left; }
  const G& left()  const {return _left; }
	H& right()       {return _right; }
  const H& right() const {return _right; }

	Func& phi()       {return _phi; }
  const Func& phi() const {return _phi; }

  left_t phi(const right_t& y, const left_t& x) {return _phi(y)(x); }

  elem_t pair(const left_t& x, const right_t& y) const {
   if (_left.contains(x) && _right.contains(y)) return elem_t(x,y);
   else throw group_mismatch("Semidirect::pair");
  }

 private:
  G _left;
  H _right;
  Func _phi;
 };
}

#endif


text:
<MMC>
	<Attributes>
		<Url></Url>
		<Image>MMC.jpg</Image>
		<File></File>
	</Attributes>
	<Events>
		<OnLeftClick></OnLeftClick>
		<OnRightClick></OnRightClick>
		<OnDblClick></OnDblClick>
		<OnMouseOver>PreviewImage</OnMouseOver>
	</Events>
</MMC>