text:
package dagger.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.CallSuper;
import dagger.internal.Beta;

/**
 * A {@link BroadcastReceiver} that injects its members in every call to {@link #onReceive(Context,
 * Intent)}.
 *
 *
This class should only be used for {@link BroadcastReceiver}s that are declared in an {@code
 * AndroidManifest.xml}. If, instead, the {@link BroadcastReceiver} is created in code, prefer
 * constructor injection.
 *
 *
Note: this class is not thread safe and should not be used with multiple {@link
 * android.os.Handler}s in calls to {@link Context#registerReceiver(BroadcastReceiver,
 * android.content.IntentFilter, String, android.os.Handler)}. Injection is performed on each
 * invocation to {@link #onReceive(Context, Intent)} which could result in inconsistent views of
 * injected dependencies across threads.
 *
 *
Subclasses should override {@link #onReceive(Context, Intent)} and call {@code
 * super.onReceive(context, intent)} immediately to ensure injection is performed immediately.
 */
@Beta
public abstract class DaggerBroadcastReceiver extends BroadcastReceiver {
  @CallSuper
  @Override
  public void onReceive(Context context, Intent intent) {
    AndroidInjection.inject(this, context);
  }
}


text:
/**
 * Created by Jörg Amelunxen on 05.11.2014.
 *
 * @class angular_module.controllersModule.ProposeCtrl
 *
 * This controller is needed to use the functions for proposing a new/specific topic.
 */
controllersModule.controller('ProposeCtrl', ['$scope','$http','commonTaskService', function($scope,$http,commonTaskService) {
    var that = this;

    this.debug = false;

    this.errorObject = {
        content:"Connection Error",
        sender:"System"
    };

    this.propose = {};

    /**
     * Sends a new proposement message to another user
     *
     * @param receiver      the email address resp. uID of the supervisor
     * @param sender        the email address resp. uID of the current user
     * @param proposeString language specific prefix for the title of the message
     */
    this.proposeTopic = function(receiver,sender,proposeString){
        var currentPropID = commonTaskService.generateUID(that.propose.name);

        var proposement = commonTaskService.createMessageObject(currentPropID, receiver, sender, proposeString + " " +
            that.propose.name, that.propose.content);

        $http.post('/admin/messages', proposement).
            success(function() {
            }).
            error(function() {
                console.log("Error ProposeCtrl: Could not propose a topic");
            });
    }
}]);

redpajama_set_name: RedPajamaGithub


text:
#pragma strict

var projectile : ProjectileBDD;
private var damageAmount : int;
private var rb : Rigidbody;

function Start () {
	rb = GetComponent.<Rigidbody>();
}

function Update () {
	if (gameObject.CompareTag("SoftMarble")){
		if (rb.velocity.x < 1 && rb.velocity.y < 1 && rb.velocity.z < 1){
			damageAmount = 0;
		}
		else {
			damageAmount = 10;
		}
	}
}

function UpdateDamageAmount (addAmount : int){
	damageAmount = projectile.damagesAmount + addAmount;
}

function GetDamage (){
	return damageAmount;
}

function OnCollisionEnter (collision : Collision){
	if (gameObject.CompareTag("Projectile")){
		yield WaitForSeconds(Time.deltaTime);
		if (projectile.projectileName == "Marble" && collision.collider.CompareTag("Ground")){
			gameObject.tag = "SoftMarble";
		}
		else if (projectile.projectileName == "Shuriken"){
			Destroy(gameObject, Time.deltaTime);
		}
		else if (projectile.projectileName == "Candy"){
			gameObject.tag = "Untagged";
		}
		else if (projectile.projectileName == "Shock"){
			gameObject.tag = "Untagged";
		}
	}
	else if (gameObject.CompareTag("Untagged")){
		Destroy(gameObject, Time.deltaTime);
	}
}


text:
package helper.oai;

import models.Globals;

/**
 * The OAISetBuilder creates OAISets from rdf statements
 *
 * @author Jan Schnasse schnasse@hbz-nrw.de
 *
 */
public class OaiSetBuilder {

	/**
	 * @param subject the subject of rdf triple
	 * @param predicate the predicate of rdf triple
	 * @param object the object of rdf triple
	 * @return a OAISet associated with the statement made by the triple
	 */
	public OaiSet getSet(String subject, String predicate, String object) {
		String name = null;
		String spec = null;
		String pid = null;

		if (predicate.compareTo("http://purl.org/dc/terms/subject") == 0) {
			if (object.startsWith("http://dewey.info/class/")) {
				String ddc = object
						.subSequence(object.length() - 4, object.length() - 1).toString();
				name = Globals.profile.getEtikett(object).getLabel();
				spec = "ddc:" + ddc;
				pid = "oai:" + ddc;
			} else {
				return null;
			}
		} else if (predicate
				.compareTo("http://hbz-nrw.de/regal#contentType") == 0) {
			String docType = object;
			name = docmap(docType);
			spec = "contentType:" + docType;
			pid = "oai:" + docType;

		}

		else {
			return null;
		}

		return new OaiSet(name, spec, pid);
	}

	private String docmap(String type) {
		if (type.compareTo("report") == 0) {
			return "Monograph";
		}
		if (type.compareTo("webpage") == 0) {
			return "Webpage";
		}
		if (type.compareTo("ejournal") == 0) {
			return "EJournal";
		}
		return "";
	}
}


text:
<resources>
    <string name="app_name">Bank IFSC codes</string>
    <string name="action_settings">Settings</string>
    <string name="locationLabelText">City</string>
    <string name="bankLabelText">Bank Name</string>
    <string name="searchLabelText">Search</string>
    <string name="title_activity_results">ResultsActivity</string>

    <string name="hello_world">Hello world!</string>
</resources>


text:
import { hasTagsOrInRange } from 'utils/selection'

const defaults = {
  tooltip: '下划线'
}

const sciprt = options => ({ el, widget, __S_, $selector, util }) => {
  const opts = Object.assign({}, defaults, options)
  const menu = new widget.Menu($selector, {
    icon: 'underline',
    tooltip: opts.tooltip,
    onMouseDown: e => {
      e.preventDefault()

      if (!util.isAvailable($selector, __S_)) return
      document.execCommand('underline')
      el.$document.trigger('selectionchange')
    }
  })

  util.addSelectionChangeEvent((isInArea, range) => {
    if (isInArea) {
      util.toEnable(() => menu.enable())
    } else {
      util.toDisable(() => menu.disable())
    }

    if (isInArea) {
      if (hasTagsOrInRange(range, ['PRE'])) {
        util.toDisable(() => menu.disable())
      }

      if (document.queryCommandState('underline')) {
        menu.turnOn()
      } else {
        menu.turnOff()
      }
    }
  })
}

const underline = {
  name: 'underline',
  run: sciprt,
  style: ''
}

export default underline


text:
#include "TextPlacement/OldLinePlacementPolicy.h"
#include "TextPlacement/TextPlacementPolicy.h"
#include "TextPlacement/TextPlacementData.h"
#include "TextPlacement/TextResult.h"
#include "Util/StringCache.h"
#include "ViewPortInterface.h"
#include "NativeTextInterface.h"
#include "OverlapDetector.h"
#include "MapProjection.h"
#include "TileFeature.h"
#include "TileMapTextSettings.h"
#include "InsideUtil.h"

#ifdef __SYMBIAN__
#include <e32math.h>
#endif

#define CORE_LOGGING_MODULE_NAME "OldPlacementPolicy"
// #define CORE_LOGGING_MODULE_LEVEL CL_ALL_FILE
#include "CoreDebugPrint.h"

/**
 *    Determines how much the angle between two segments that
 *    we are placing text on will affect the distance between
 *    the substrings. A higher value will give a shorter dist.
 *    Resonable values are 1-90. Good values are around 20.
 */
#define TPL_MAGIC_CONST      30

/**
 *    The maximum sumed angles that the cost function will
 *    alow for a text placed on_line.
 */
#define TPL_MAX_TOTAL_ANGLE  90

/**
 *    The maximum angle that two lines might have before we say
 *    that we cant place any text here.
 */
#define TPL_MAX_ANGLE        30

/**
 *    The highest cost that we willaccept from the cost function
 *    before we say that this will probably not look good.
 */
#define TPL_MAX_TOTAL_COST   100

static inline int
Pow2( int a ) {
   return a*a;
}

inline int Pow2DistBetweenPoints(const MC2Point& p1, const MC2Point& p2) {
   return
      Pow2( p1.getX() - p2.getX() ) +
      Pow2( p1.getY() - p2.getY() );
}

TextPlacementDelegator::OldLinePlacementPolicy::OldLinePlacementPolicy(
   NativeTextInterface* textInterface,
   ViewPortInterface* viewPort,
   TileMapTextSettings& textSettings,
   const MapProjection& mapProjection,
   StringCache& cache,
   OverlapDetector<PixelBox>& overlapDetector) :
   TextPlacementPolicy(textInterface,
                       viewPort,
                       textSettings,
                       mapProjection,
                       cache,
                       overlapDetector)
{

}

int
TextPlacementDelegator::OldLinePlacementPolicy::getTextWidth(
   STRING* nameOfFeature,
   int startIndex,
   int nbrOfChars )
{
   if( nbrOfChars == -1 ) {
      nbrOfChars =
         m_textInterface->getStringLength( *nameOfFeature ) -
         startIndex;

   }
   if( nbrOfChars <= 0 ) { return 0; }

   MC2Point p( 0, 0 );
   return m_textInterface->getStringAsRectangle(
      *nameOfFeature, p, startIndex, nbrOfChars, 0 ).getWidth();
}

const
int TextPlacementDelegator::OldLinePlacementPolicy::getLongestSegmentInFeature(
   const std::vector<MC2Point>& feature ) const
{
   double length = 0;
   int index = 0;
   const int featureSize = feature.size();
   if( featureSize >= 2 ) {
      for ( int i = 0; i < featureSize - 1; ++i ) {
         // Calc the (²) distance between the endpoints of
         // the current segment in the feature.
         int xDiff = feature[ i ].getX() - feature[ i + 1 ].getX();
         int yDiff = feature[ i ].getY() - feature[ i + 1 ].getY();
         double current_length = (double)(Pow2( xDiff ) + Pow2( yDiff ));
         // If the length of this segment is longer than any that we
         // have tested before, remember this one.
         if( current_length > length ) {
            length = current_length;
            index = i;
         }
      }
   } else {
      return -1;
   }
   return index;
}

int
TextPlacementDelegator::OldLinePlacementPolicy::placeOnLine(
   TextPlacementData& data,
   TextResultVec& output)
{
   std::vector<MC2Point> pointsInFeature;

   for( int i=0; i < (int)data.pointsInFeature.size(); i++ ) {
      pointsInFeature.push_back( data.pointsInFeature[ i ] );
   }

//   int isInside=0;
//   for( int i=0; i < (int)proxy_pointsInFeature.size(); i++ ) {
//      /*
//       * This clipping is not done in a correct way but it is probably
//       * as good as we need it to be. It will remove any segments
//       * that dosent have any points inside the screen.
//       */
//      int m_screenCoords_pointInside_proxy_pointsInFeature_i_1 = 0;
//      if( i > 1 &&
//            m_screenCoords.pointInside(proxy_pointsInFeature[i-1]) ) {
//         m_screenCoords_pointInside_proxy_pointsInFeature_i_1 = 1;
//      }
//      if( (m_screenCoords.pointInside(proxy_pointsInFeature[i]) ||
//           m_screenCoords.pointInside(proxy_pointsInFeature[i+1])) ||
//          (m_screenCoords.pointInside(proxy_pointsInFeature[i]) ||
//           m_screenCoords_pointInside_proxy_pointsInFeature_i_1)) {
//         pointsInFeature.push_back( proxy_pointsInFeature[ i ] );
//         isInside = 1;
//      } else if( isInside ) {
//         i = (int)proxy_pointsInFeature.size();
//      }
//   }

   std::vector<int> segmentWidths;
   int longestSegmentInFeature =
      getLongestSegmentInFeature( pointsInFeature );

   if( longestSegmentInFeature == -1 ) {
      return 0;
   }

   int lsifLength = Pow2DistBetweenPoints(
      pointsInFeature[ longestSegmentInFeature ],
      pointsInFeature[ longestSegmentInFeature + 1 ] );

   const STRING* font = m_stringCache.getOrCreateString(
      m_textSettings.getLineFont( data.polyLineWidth ).first );

   const int fontSize =
      m_textSettings.getLineFont( data.polyLineWidth ).second;

   m_textInterface->setFont( *font, fontSize );

   int stringWidth = getTextWidth(
      data.nameOfFeature, 0, -1 );

   int lengthOfString = m_textInterface->getStringLength( *data.nameOfFeature );
   std::vector<int> charsOnSegment( (int)pointsInFeature.size() - 1 );
   for( int j=0; j < (int)pointsInFeature.size() - 1; j++) {
      charsOnSegment[ j ] = 0;
   }

   stringWidth = Pow2( stringWidth );
   if( lsifLength > stringWidth ) {
      // Trying to place on the longest segment in the feature.
      charsOnSegment[ longestSegmentInFeature ] = lengthOfString;
   } else {
      for( int i = 0; i < (int)pointsInFeature.size() - 1; i++ ) {
         segmentWidths.push_back(
            Pow2DistBetweenPoints(
               pointsInFeature[ i ],
               pointsInFeature[ i + 1 ] ) );
      }

      int bestCostSoFar = INT_MAX;

      for( int segment = 0;
           segment < (int)segmentWidths.size();
           segment++ ) {
         std::vector<int> tempCharsOnSegment;
         tempCharsOnSegment.resize( (int)segmentWidths.size() );

         int nbrOfCharsPossitioned = fillRestOfCharsOnSegment(
            data.nameOfFeature,
            segmentWidths,
            tempCharsOnSegment,
            lengthOfString,
            segment, 0 );

         if( nbrOfCharsPossitioned == lengthOfString ) {
            int cost = polyCost(
               data.nameOfFeature,
               segmentWidths,
               tempCharsOnSegment,
               pointsInFeature );
            if( nbrOfCharsPossitioned != lengthOfString ) {
               cost = INT_MAX;
            }

            if( cost < bestCostSoFar ) {
               bestCostSoFar = cost;
               tempCharsOnSegment.swap( charsOnSegment );
            }
         } else {
            segment = (int)segmentWidths.size();
         }
      }
   }

   int firstSegment = -1;
   for( int k = 0; k < (int)charsOnSegment.size(); k++ ) {
      if( firstSegment == -1 && charsOnSegment[ k ] != 0 ) {
         firstSegment = k;
         k = (int)charsOnSegment.size();
      }
   }

   if ( firstSegment < 0 ) {
      return 0;
   }

   int reverseText = isTextReversed( pointsInFeature, firstSegment );

   return placeOnSegments( data,
                           font,
                           fontSize,
                           pointsInFeature,
                           data.coordsBegin,
                           charsOnSegment,
                           reverseText,
                           output);
}

int
TextPlacementDelegator::OldLinePlacementPolicy::placeOnSegments(
   TextPlacementData& data,
   const STRING* font,
   int fontSize,
   const std::vector<MC2Point>& pointsInFeature,
   TileMapCoords::const_iterator coordsBegin,
   std::vector<int>& charsOnSegment,
   int reverseText,
   TextResultVec& output)
{
   TextResult* tr = new TextResult();

   m_textInterface->setFont( *font, fontSize );
   std::vector<PixelBox> stringPixelBoxes;
   int textStartIdx = 0;
   // let the direction of the text be controled by the line
   // drawn by pointsInFeature[ 0 ] and
   // pointsInFeature[ (int)pointsInFeature.size()-1 ].
   int first=-1;
   int last=-1;
   for( int i = 0; i < (int)charsOnSegment.size(); i++ ) {
      if( first == -1 && charsOnSegment[ i ] != 0 ) {
         first = i;
      }
      if( charsOnSegment[ i ] != 0 ) {
         last = i;
      }
   }
   if( first == last) {
      first = -1;
      last = -1;
   }
   int lengthOfString = m_textInterface->getStringLength( *data.nameOfFeature );
   for( int segmentNbr = 0;
        segmentNbr < (int)charsOnSegment.size();
        segmentNbr++ ) {
      if( charsOnSegment[ segmentNbr ] != 0 ){
         MC2Point lineBegin = pointsInFeature[ segmentNbr ];
         MC2Point lineEnd = pointsInFeature[ segmentNbr + 1 ];

         MC2Coordinate lineBeginCoord = *(coordsBegin + segmentNbr);
         MC2Coordinate lineEndCoord = *(coordsBegin + segmentNbr + 1);

         int p1x = lineBegin.getX();
         int p1y = lineBegin.getY();
         int p2x = lineEnd.getX();
         int p2y = lineEnd.getY();

         int16 angle = calcAngleForTextOnLine( p1x, p1y, p2x, p2y );
         if( angle == 9999 ) {
            mc2dbg << "angle == 9999" << endl;
            delete( tr );
            return 0;
         }

         // Align al texts on a segment in the same way as the first one.
         if ( reverseText == 0 ) {
            angle += 180;
         }
         // Varun's angle increase ccw.
         angle = -angle;
         if ( angle < 0 ) {
            angle += 360;
         }

         // Collect and send the results to our textresults vector.
         tr->setString( data.nameOfFeature );
         tr->setFontName( font );

         uint32 textColor = m_textSettings.getTextColor();

         tr->setFontColor( (textColor >> 16 ) & 0xff,
                           (textColor >> 8 ) & 0xff,
                           (textColor >> 0 ) & 0xff );
         tr->setTypeOfString( TileMapNameSettings::on_line );
         tr->setFontSize( fontSize );
         std::vector<isab::Rectangle> stringRectangles;
         int posX = 0;
         int posY = 0;
         int textFirstIdx = 0;
         for( int i = 0; i < first; i++ ) {
            textFirstIdx += charsOnSegment[ i ];
         }
         int textLastIdx = 0;
         for( int j = 0; j < last; j++ ) {
            textLastIdx += charsOnSegment[ j ];
         }

         // Put text to the left.
         if( segmentNbr == first ) {
            mc2dbg4 << "left" << endl;
            // Compensate for the angle between line 1 and 2.
            double angleDiff = 0;
            if(  segmentNbr + 2 < (int)pointsInFeature.size() ) {
               int fp1x = pointsInFeature[ segmentNbr ].getX();
               int fp1y = pointsInFeature[ segmentNbr ].getY();
               int fp2x = pointsInFeature[ segmentNbr + 1 ].getX();
               int fp2y = pointsInFeature[ segmentNbr + 1 ].getY();
               int fp3x = pointsInFeature[ segmentNbr + 2 ].getX();
               int fp3y = pointsInFeature[ segmentNbr + 2 ].getY();

               angleDiff =
                  calcAngleForTextOnLine( fp1x, fp1y, fp2x, fp2y ) -
                  calcAngleForTextOnLine( fp2x, fp2y, fp3x, fp3y );
               angleDiff = abs(int( (int)angleDiff ) );
               if ( angleDiff > 180 ) {
                  angleDiff = 360 - angleDiff;
               }
            }
            double subTextWidth = getTextWidth( data.nameOfFeature,
                                                textFirstIdx, charsOnSegment[ segmentNbr ] );

            // 15 is a magic constant.
            double faktor = ( subTextWidth + ( angleDiff /
                                               TPL_MAGIC_CONST) ) / ( sqrt( (double)
                                                                          Pow2DistBetweenPoints( lineBegin, lineEnd ) ) * 2.0 );
            posX = (int)( ( lineBegin.getX() * faktor ) +
                          ( lineEnd.getX() * ( 1 - faktor ) ) + 0.0 );
            posY = (int)( ( lineBegin.getY() * faktor ) +
                          ( lineEnd.getY() * ( 1 - faktor ) ) + 0.0 );

            // Put text to the right.
         } else if( segmentNbr == last ) {
            mc2dbg4 << "right" << endl;
            double angleDiff = 0;
            int lp1x = pointsInFeature[ segmentNbr - 1 ].getX();
            int lp1y = pointsInFeature[ segmentNbr - 1 ].getY();
            int lp2x = pointsInFeature[ segmentNbr ].getX();
            int lp2y = pointsInFeature[ segmentNbr ].getY();
            int lp3x = pointsInFeature[ segmentNbr + 1 ].getX();
            int lp3y = pointsInFeature[ segmentNbr + 1 ].getY();

            angleDiff =
               calcAngleForTextOnLine( lp1x, lp1y, lp2x, lp2y ) -
               calcAngleForTextOnLine( lp2x, lp2y, lp3x, lp3y );
            angleDiff = abs(int( (int)angleDiff ) );
            if ( angleDiff > 180 ) {
               angleDiff = 360 - angleDiff;
            }

            double subTextWidth = getTextWidth( data.nameOfFeature,
                                                textLastIdx, charsOnSegment[ segmentNbr ] );

            // 15 is a magic constant.
            double faktor = (subTextWidth + ( angleDiff /
                                              TPL_MAGIC_CONST ) ) / ( sqrt( (double)
                                                                         Pow2DistBetweenPoints( lineBegin, lineEnd ) ) * 2.0 );

            posX = (int)( ( lineBegin.getX() * ( 1 - faktor ) ) +
                          ( lineEnd.getX() * faktor ) + 0.0 );
            posY = (int)( ( lineBegin.getY() *  ( 1 - faktor ) ) +
                          ( lineEnd.getY() * faktor ) + 0.0 );

            // Put text in center.
         } else {
            mc2dbg4 << "center" << endl;
            posX = (int)( ( ( lineBegin.getX() +
                              lineEnd.getX() ) / 2 ) + 0.0 );
            posY = (int)( ( ( lineBegin.getY() +
                              lineEnd.getY() ) / 2 ) + 0.0 );
         }
         MC2Point pos( posX, posY );
         if( reverseText == 0 ) {
            m_textInterface->getStringAsRectangles(
               stringRectangles,
               *data.nameOfFeature,
               pos,
               textStartIdx,
               charsOnSegment[ segmentNbr ],
               angle );
         } else {
            m_textInterface->getStringAsRectangles(
               stringRectangles,
               *data.nameOfFeature,
               pos,
               lengthOfString - textStartIdx -
               charsOnSegment[ segmentNbr ],
               charsOnSegment[ segmentNbr ],
               angle );
         }
         for( int k = 0; k < (int)stringRectangles.size(); k++ ) {
            stringPixelBoxes.push_back( stringRectangles[ k ] );
         }

         MC2Point posOfString( posX, posY );
         MC2Coordinate worldCoord;
         toWorld( worldCoord, posOfString );

         if( reverseText == 0 ) {
            TextPlacementNotice tpn( posOfString,
                                     worldCoord,
                                     textStartIdx,
                                     textStartIdx + charsOnSegment[ segmentNbr ],
                                     angle,
                                     lineEndCoord,
                                     lineBeginCoord);
            tr->addTPN( tpn );
         } else {
            TextPlacementNotice tpn( posOfString,
                                     worldCoord,
                                     lengthOfString - textStartIdx -
                                     charsOnSegment[ segmentNbr ],
                                     lengthOfString - textStartIdx,
                                     angle,
                                     lineBeginCoord,
                                     lineEndCoord);
            tr->addTPN( tpn );
         }
         textStartIdx += charsOnSegment[ segmentNbr ];
      }
      mc2dbg4 << endl;
   }
   int nbrOfstringRectangles_inside_m_screenCoords = 0;
   for( int k = 0; k < (int)stringPixelBoxes.size(); k++ ) {
      if( !( stringPixelBoxes[k].inside(m_screenCoords) ) ) {
         nbrOfstringRectangles_inside_m_screenCoords++;
      }
   }

   int halfNbrOfRectangles = (int)stringPixelBoxes.size() / 2;

   // This should be fetched from the MapPlotter for this actual
   // text. Right to left text means "wrong" drawing order, i.e.
   // arabic, hebrew or similar. We only support placing text in
   // the wrong drawing order with one text segment (since ABC DEF
   // -> CBA FED instead of FEDCBA)
   bool leftToRightText =
      m_textInterface->textDirectionLeftToRight( *data.nameOfFeature );

   if( tr->getTPN().size() > 0 &&
       nbrOfstringRectangles_inside_m_screenCoords <
       halfNbrOfRectangles &&
       m_overlapDetector.addIfNotOverlapping( stringPixelBoxes ) &&
       // OK, if wrong text drawing order and only one string
       (!leftToRightText && tr->getTPN().size() == 1 ||
        // Also OK if normal text drawing order and many strings
        leftToRightText ))
   {
      coreprintln("Failed to place %s", data.mc2String.c_str());
      output.push_back( tr );
   } else {
      coreprintln("Successfully placed %s", data.mc2String.c_str());
      delete tr;
      return 0;
   }

   return 1;
}

int
TextPlacementDelegator::OldLinePlacementPolicy::fillRestOfCharsOnSegment(
   STRING* nameOfFeature,
   const std::vector<int>& segmentWidths,
   std::vector<int>& tempCharsOnSegment,
   int stringLength,
   int startSegment,
   int startChar )
{
   for( int i = startSegment; i < (int)segmentWidths.size(); i++ ) {
      if( startChar >= stringLength ) {
         return startChar;
      }
      tempCharsOnSegment[ i ] =
         nbrOfCharsThatFitsInSeg(
            nameOfFeature, stringLength,
            segmentWidths[ i ], startChar );
      startChar += tempCharsOnSegment[ i ];
      if( tempCharsOnSegment[ i ] == 0 ) {
         return -1;
      }
   }
   return startChar;
}

int
TextPlacementDelegator::OldLinePlacementPolicy::nbrOfCharsThatFitsInSeg(
   STRING* nameOfFeature,
   int stringLength,
   int segmentWidth,
   int startChar )
{
   if( startChar >= stringLength ) {
      return 0;
   }
   if( segmentWidth <= 0 ) {
      return 0;
   }
   int nbrOfCharsUsedSoFar = 0;
   int charsWidth = getTextWidth( nameOfFeature,
                                  startChar, nbrOfCharsUsedSoFar );

   int firstCharWidth = getTextWidth( nameOfFeature,
                                      startChar, 1 );
   int lastCharWidth = getTextWidth( nameOfFeature,
                                     startChar + nbrOfCharsUsedSoFar, 1 );

   if( startChar + nbrOfCharsUsedSoFar >= stringLength ) {
      return stringLength - startChar;
   }

   while( segmentWidth > Pow2( charsWidth +
                               ( firstCharWidth + lastCharWidth ) / 2 ) ) {

      nbrOfCharsUsedSoFar++;
      if( startChar + nbrOfCharsUsedSoFar >= stringLength ) {
         return stringLength - startChar;
      }
      charsWidth = getTextWidth( nameOfFeature,
                                 startChar, nbrOfCharsUsedSoFar );
      lastCharWidth = getTextWidth( nameOfFeature,
                                    startChar + nbrOfCharsUsedSoFar, 1 );
   }
   return nbrOfCharsUsedSoFar;
}

int
TextPlacementDelegator::OldLinePlacementPolicy::polyCost(
   STRING* nameOfFeature,
   const std::vector<int>& segmentWidths,
   const std::vector<int>& charsOnSegment,
   const std::vector<MC2Point>& pointsInFeature )
{
   int startIdx = 0;
   int cost = 0;
   int totalAngle = 0;
   int atLeastOneSegmentHaveCharsThatNeedsPlacment = 0;
   // For all segments.
   for( int i = 0; i < (int)segmentWidths.size()-1; i++ ) {
      if( charsOnSegment[ i ] != 0 ) {
         atLeastOneSegmentHaveCharsThatNeedsPlacment = 1;
      }

      if( i > 0 && i < (int)segmentWidths.size() - 1 ) {
         if( ( charsOnSegment[ i - 1 ] != 0 ) &&
             ( charsOnSegment[ i ] == 0 ) &&
             ( charsOnSegment[ i + 1 ] != 0 ) ) {
            mc2dbg << "We have atleast one segment that are empty within "
                   << "the segments that we are placing text on." << endl;
            return INT_MAX;
         }
         int subStringOnSegWidth = getTextWidth(
            nameOfFeature,
            startIdx,
            charsOnSegment[ i ] );
         startIdx += charsOnSegment[ i ];
         if( ( charsOnSegment[ i ] != 0 ) &&
             ( charsOnSegment[ i - 1 ] != 0 ) &&
             ( charsOnSegment[ i + 1 ] != 0 ) ) {
            cost += abs(int( Pow2( subStringOnSegWidth ) -
                             segmentWidths[ i ] ) );
         }
      }
      if( i < (int)segmentWidths.size() - 1 ) {
         if( ( charsOnSegment[ i ] != 0 ) &&
             ( charsOnSegment[ i + 1 ] != 0 ) ) {
            int p1x = pointsInFeature[ i ].getX();
            int p1y = pointsInFeature[ i ].getY();
            int p2x = pointsInFeature[ i + 1 ].getX();
            int p2y = pointsInFeature[ i + 1 ].getY();
            int a12Cost = calcAngleForTextOnLine( p1x, p1y, p2x, p2y );
            int p3x = pointsInFeature[ i + 2 ].getX();
            int p3y = pointsInFeature[ i + 2 ].getY();
            int a23Cost = calcAngleForTextOnLine( p2x, p2y, p3x, p3y );

            int a13Cost = abs(int( a12Cost - a23Cost ) );
            if ( a13Cost > 180 ) { a13Cost = 360 - a13Cost; }
            totalAngle += a13Cost;
            if ( a13Cost > TPL_MAX_ANGLE || totalAngle > TPL_MAX_TOTAL_ANGLE ) {
               return INT_MAX;
            }
            cost += a13Cost;
         }
      }
      if( cost > TPL_MAX_TOTAL_COST ) {
         return INT_MAX;
      }
   }
   if( atLeastOneSegmentHaveCharsThatNeedsPlacment ) {
      return cost;
   } else {
      return INT_MAX;
   }
}

int
TextPlacementDelegator::OldLinePlacementPolicy::isTextReversed(
   const std::vector<MC2Point>& pointsInFeature,
   int firstSegment )
{
   const MC2Point &lineBegin = pointsInFeature[ firstSegment ];
   const MC2Point &lineEnd = pointsInFeature[ firstSegment + 1 ];
   int p1x = lineBegin.getX();
   int p1y = lineBegin.getY();
   int p2x = lineEnd.getX();
   int p2y = lineEnd.getY();

   int16 angle = calcAngleForTextOnLine( p1x, p1y, p2x, p2y );
   if( angle == 9999 ) {
      mc2dbg << "angle == 9999" << endl;
   }
   if( ( angle > -90 ) && ( angle < 90 ) ) {
      return 1;
   }
   return 0;
}

int16
TextPlacementDelegator::OldLinePlacementPolicy::calcAngleForTextOnLine(
   int p1x,
   int p1y,
   int p2x,
   int p2y )
{
   double xDiff = p1x - p2x;
   double yDiff = p1y - p2y;

   if ( xDiff == 0 && yDiff == 0 ) {
      // x and y diff is 0 means no angle.
      return 9999;
   }

   // Calculate at what angle the line p1-p2 is.
#ifdef __SYMBIAN__
   TReal atanRes;
   Math::ATan( atanRes, yDiff, xDiff );
#else
   double atanRes = atan2( yDiff, xDiff );
#endif
   int16 angle = (int16)( ( atanRes / M_PI ) * 180 );
   return angle;
}


text:
package org.chafed

/**
 * A request body.
 */
trait Body {
  /**
   * The content type (or `None`) if not specified.
   */
  def contentType: Option[String] = None

  /**
   * The raw content of the body.
   */
  lazy val content: Array[Byte] = Array()

  /**
   * Extract additional headers we can derive given the content.
   */
  private[chafed] def implicitHeaders: List[Header] = contentType match {
    case Some(c) =>
      List(header.ContentType(c), header.ContentLength(content.size))
    case None => Nil
  }
}

/**
 * An empty request body.
 */
case object EmptyBody extends Body

/**
 * A URL-encoded request body.
 */
case class FormURLEncoded(query: Map[String, Option[String]]) extends Body with QueryBuilder {
  override lazy val content = optMap2Str(query).getBytes

  override def contentType = Some("application/x-www-form-urlencoded")
}


text:
A simple dating age calculator inspired by https://xkcd.com/314/
![Screenshot]
(https://raw.githubusercontent.com/jayseejc/XKCD-Dating-Age-Calculator/master/Screenshots/screenshot.png)


text:
@class LFPayTipView;

@protocol LFPayTipViewDelegate<NSObject>

-(void)LFPayTipView:(UIView *)payTipView closeBtnDidClick:(UIButton *)closeBtn;

@end
@interface LFPayTipView : UIView
@property(nonatomic,weak) id<LFPayTipViewDelegate> del;
+(instancetype)payTipView;
@end


text:
package org.dozer.functional_tests;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.dozer.CustomFieldMapper;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.dozer.functional_tests.support.SampleDefaultBeanFactory;
import org.dozer.functional_tests.support.TestCustomFieldMapper;
import org.dozer.util.CollectionUtils;
import org.dozer.vo.AnotherTestObject;
import org.dozer.vo.AnotherTestObjectPrime;
import org.dozer.vo.FieldValue;
import org.dozer.vo.Fruit;
import org.dozer.vo.InsideTestObject;
import org.dozer.vo.MethodFieldTestObject;
import org.dozer.vo.MethodFieldTestObject2;
import org.dozer.vo.NoReadMethod;
import org.dozer.vo.NoReadMethodPrime;
import org.dozer.vo.NoVoidSetters;
import org.dozer.vo.NoWriteMethod;
import org.dozer.vo.NoWriteMethodPrime;
import org.dozer.vo.PrimitiveArrayObj;
import org.dozer.vo.PrimitiveArrayObjPrime;
import org.dozer.vo.SimpleObj;
import org.dozer.vo.SimpleObjPrime;
import org.dozer.vo.TestObject;
import org.dozer.vo.TestObjectPrime;
import org.dozer.vo.TestObjectPrime2;
import org.dozer.vo.allowedexceptions.ThrowException;
import org.dozer.vo.allowedexceptions.ThrowExceptionPrime;
import org.dozer.vo.context.ContextMapping;
import org.dozer.vo.context.ContextMappingNested;
import org.dozer.vo.context.ContextMappingNestedPrime;
import org.dozer.vo.context.ContextMappingPrime;
import org.dozer.vo.iface.ApplicationUser;
import org.dozer.vo.iface.UpdateMember;
import org.dozer.vo.index.Mccoy;
import org.dozer.vo.index.MccoyPrime;
import org.dozer.vo.isaccessible.Foo;
import org.dozer.vo.isaccessible.FooPrime;
import org.dozer.vo.isaccessible.PrivateConstructorBean;
import org.dozer.vo.isaccessible.PrivateConstructorBeanPrime;
import org.dozer.vo.orphan.Child;
import org.dozer.vo.orphan.ChildPrime;
import org.dozer.vo.orphan.Parent;
import org.dozer.vo.orphan.ParentPrime;
import org.dozer.vo.perf.MyClassA;
import org.dozer.vo.perf.MyClassB;
import org.dozer.vo.set.NamesArray;
import org.dozer.vo.set.NamesCollection;
import org.dozer.vo.set.NamesSet;
import org.dozer.vo.set.NamesSortedSet;
import org.dozer.vo.set.SomeDTO;
import org.dozer.vo.set.SomeOtherDTO;
import org.dozer.vo.set.SomeVO;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * @author garsombke.franz
 */
public class GranularDozerBeanMapperTest extends AbstractFunctionalTest {

  @Test
  public void testFieldAccessible() throws Exception {
    Mapper mapper = getMapper("fieldAttributeMapping.xml");
    TestObject to = newInstance(TestObject.class);
    to.setFieldAccessible("fieldAccessible");
    to.setFieldAccessiblePrimInt(2);
    InsideTestObject ito = newInstance(InsideTestObject.class);
    ito.setLabel("label");
    to.setFieldAccessibleComplexType(ito);
    String[] stringArray = new String[] { "one", "two" };
    to.setFieldAccessibleArrayToList(stringArray);
    TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
    assertEquals("fieldAccessible", top.fieldAccessible);
    assertEquals("label", top.fieldAccessibleComplexType.getLabelPrime());
    assertEquals(2, top.fieldAccessiblePrimInt);
    assertEquals("one", top.fieldAccessibleArrayToList.get(0));
    assertEquals("two", top.fieldAccessibleArrayToList.get(1));

    // Map Back
    TestObject toDest = mapper.map(top, TestObject.class);
    assertEquals("fieldAccessible", toDest.getFieldAccessible());
    assertEquals("label", toDest.getFieldAccessibleComplexType().getLabel());
    assertEquals(2, toDest.getFieldAccessiblePrimInt());
    assertEquals("one", toDest.getFieldAccessibleArrayToList()[0]);
    assertEquals("two", toDest.getFieldAccessibleArrayToList()[1]);
  }

  @Test
  public void testOverloadGetSetMethods() throws Exception {
    Mapper mapper = getMapper("fieldAttributeMapping.xml");
    TestObject to = newInstance(TestObject.class);
    Date date = new Date();
    to.setOverloadGetField(new Date());
    TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
    assertEquals(date, top.getOverloadSetField());

    // Map Back
    TestObject toDest = (TestObject) mapper.map(top, TestObject.class);
    assertEquals(date, toDest.getOverloadGetField());
  }

  @Test
  public void testFieldCreateMethod() throws Exception {
    Mapper mapper = getMapper("fieldAttributeMapping.xml");
    TestObject to = newInstance(TestObject.class);
    InsideTestObject ito = newInstance(InsideTestObject.class);
    // we did not set any values. this will be set in the 'createMethod'
    to.setCreateMethodType(ito);
    TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
    assertEquals("myField", top.getCreateMethodType().getMyField());

    // Map Back
    TestObject toDest = mapper.map(top, TestObject.class);
    assertEquals("testCreateMethod", toDest.getCreateMethodType().getTestCreateMethod());
  }

  @Test
  public void testIntegerToString() throws Exception {
    Mapper mapper = getMapper("fieldAttributeMapping.xml");
    TestObject to = newInstance(TestObject.class);
    Integer[] array = new Integer[] { new Integer(1), new Integer(2) };
    to.setArrayForLists(array);
    TestObjectPrime top = mapper.map(to, TestObjectPrime.class);
    assertEquals("1", top.getListForArray().get(0));
  }

  @Test
  public void testMapNull_MappingLevel() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // check that null does not override an existing value when map-null="false"
    AnotherTestObject src = newInstance(AnotherTestObject.class);
    src.setField3(null);
    src.setField4(null);
    AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
    dest.setTo(newInstance(TestObject.class));
    dest.setField3("555");
    dest.getTo().setOne("4641");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertEquals("invalid dest field value", "555", dest.getField3());
    assertEquals("invalid dest field value2", "4641", dest.getTo().getOne());
  }

  @Test
  public void testMapNull_MappingLevel2() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // Reverse mapping
    AnotherTestObjectPrime src = newInstance(AnotherTestObjectPrime.class);
    src.setTo(newInstance(TestObject.class));
    src.setField3(null);
    src.getTo().setOne(null);
    AnotherTestObject dest = newInstance(AnotherTestObject.class);
    dest.setField3("555");
    dest.setField4("4641");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertEquals("invalid dest field value", "555", dest.getField3());
    assertEquals("invalid dest field value2", "4641", dest.getField4());
  }

  @Test
  public void testMapEmptyString_MappingLevel() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // check that "" does not override an existing value when
    // map-empty-string="false"
    AnotherTestObject src = newInstance(AnotherTestObject.class);
    src.setField3("");
    src.setField4("");
    AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
    dest.setTo(newInstance(TestObject.class));
    dest.setField3("555");
    dest.getTo().setOne("4641");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertEquals("invalid dest field value", "555", dest.getField3());
    assertEquals("invalid dest field value2", "4641", dest.getTo().getOne());
  }

  @Test
  public void testMapEmptyString_MappingLevel2() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // reverse mapping
    AnotherTestObjectPrime src = newInstance(AnotherTestObjectPrime.class);
    src.setTo(newInstance(TestObject.class));
    src.setField3("");
    src.getTo().setOne("");
    AnotherTestObject dest = newInstance(AnotherTestObject.class);
    dest.setField3("555");
    dest.setField4("4641");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertEquals("invalid dest field value", "555", dest.getField3());
    assertEquals("invalid dest field value2", "4641", dest.getField4());
  }

  @Test
  public void testMapNull_ClassLevel() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // check that null does not override an existing value when map-null="false"
    TestObject src = newInstance(TestObject.class);
    src.setOne(null);
    TestObjectPrime2 dest = newInstance(TestObjectPrime2.class);
    dest.setOne("555");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertNotNull("dest should not be null", dest.getOne());
    assertEquals("invalid dest field value", "555", dest.getOne());

    // reverse mapping
    TestObjectPrime2 src2 = newInstance(TestObjectPrime2.class);
    src2.setOne(null);
    TestObject dest2 = newInstance(TestObject.class);
    dest2.setOne("555");

    // dest field should NOT remain unchanged
    mapper.map(src2, dest2);
    assertNull("dest should be null", dest2.getOne());
  }

  @Test
  public void testMapEmptyString_ClassLevel() throws Exception {
    Mapper mapper = getMapper("nullFieldMapping.xml");
    // check that "" does not override an existing value when
    // map-empty-string="false"
    TestObject src = newInstance(TestObject.class);
    src.setOne("");
    TestObjectPrime2 dest = newInstance(TestObjectPrime2.class);
    dest.setOne("555");

    // dest field should remain unchanged
    mapper.map(src, dest);
    assertNotNull("dest should not be null", dest.getOne());
    assertEquals("invalid dest field value", "555", dest.getOne());

    // reverse mapping
    TestObjectPrime2 src2 = newInstance(TestObjectPrime2.class);
    src2.setOne("");
    TestObject dest2 = newInstance(TestObject.class);
    dest2.setOne("555");

    // dest field should NOT remain unchanged
    mapper.map(src2, dest2);
    assertNotNull("dest should not be null", dest2.getOne());
    assertEquals("dest should be an empty string", "", dest2.getOne());

  }

  @Test
  public void testContextMappingWithNestedContext() throws Exception {
    Mapper mapper = getMapper("contextMapping.xml");

    ContextMappingNested cmn = newInstance(ContextMappingNested.class);
    cmn.setLoanNo("loanNoNested");
    List<ContextMappingNested> list = newInstance(ArrayList.class);
    list.add(cmn);
    ContextMapping cm = newInstance(ContextMapping.class);
    cm.setLoanNo("loanNo");
    cm.setContextList(list);

    ContextMappingPrime cmpA = mapper.map(cm, ContextMappingPrime.class, "caseA");
    assertNull(cmpA.getLoanNo());
    assertNull(((ContextMappingNestedPrime) cmpA.getContextList().get(0)).getLoanNo());

    ContextMappingPrime cmpB = mapper.map(cm, ContextMappingPrime.class, "caseB");
    assertEquals("loanNo", cmpB.getLoanNo());
    assertEquals("loanNoNested", ((ContextMappingNested) cmpB.getContextList().get(0)).getLoanNo());

    ContextMappingNestedPrime cmn2 = newInstance(ContextMappingNestedPrime.class);
    cmn2.setLoanNo("loanNoNested");
    List<ContextMappingNestedPrime> list2 = newInstance(ArrayList.class);
    list2.add(cmn2);
    ContextMappingPrime prime = newInstance(ContextMappingPrime.class);
    prime.setLoanNo("loanNo");
    prime.setContextList(list2);

    ContextMapping cmDest = mapper.map(prime, ContextMapping.class, "caseA");
    assertNull(cmDest.getLoanNo());
    assertNull(((ContextMappingNested) cmDest.getContextList().get(0)).getLoanNo());

    ContextMapping cmpBDest = mapper.map(prime, ContextMapping.class, "caseB");
    assertEquals("loanNo", cmpBDest.getLoanNo());
    assertEquals("loanNoNested", ((ContextMappingNestedPrime) cmpBDest.getContextList().get(0)).getLoanNo());
  }

  @Test
  public void testArrayToSortedSet() {
    NamesArray from = newInstance(NamesArray.class);
    String[] names = { "John", "Bill", "Tony", "Fred", "Bruce" };
    from.setNames(names);
    NamesSortedSet to = mapper.map(from, NamesSortedSet.class);

    assertNotNull(to);
    assertEquals(names.length, to.getNames().size());
  }

  @Test
  public void testSortedSetToArray() {
    NamesSortedSet from = newInstance(NamesSortedSet.class);
    NamesArray to = null;
    SortedSet<String> names = newInstance(TreeSet.class);

    names.add("Jen");
    names.add("Sue");
    names.add("Sally");
    names.add("Jill");
    from.setNames(names);

    to = mapper.map(from, NamesArray.class);

    assertNotNull(to);
    assertEquals(names.size(), to.getNames().length);
  }

  @Test
  public void testSetToSortedSet() {
    NamesSet from = newInstance(NamesSet.class);
    NamesSortedSet to = null;
    Set<String> names = newInstance(HashSet.class);

    names.add("Red");
    names.add("Blue");
    names.add("Green");
    from.setNames(names);

    to = mapper.map(from, NamesSortedSet.class);

    assertNotNull(to);
    assertEquals(names.size(), to.getNames().size());
  }

  /**
   * When the source type is a Set and the destination is a Collection we expect that the
   * mapper narrows to the Set type instead of using a List by default.
   *
   * issue https://github.com/DozerMapper/dozer/issues/287
   */
  @Test
  public void testSetToCollection() {
    NamesSet from = newInstance(NamesSet.class);
    NamesCollection to;
    Set<String> names = newInstance(HashSet.class);
    names.add("Red");
    names.add("Blue");
    names.add("Green");
    names.add("Green");
    from.setNames(names);

    to = mapper.map(from, NamesCollection.class);

    assertNotNull(to);
    assertTrue(to.getNames() instanceof Set);
    assertThat(to.getNames().size(), is(3));
    assertEquals(names.size(), to.getNames().size());
  }

  @Test
  public void testSortedSetToSet() {
    NamesSortedSet from = newInstance(NamesSortedSet.class);
    NamesSet to = null;
    SortedSet<String> names = newInstance(TreeSet.class);

    names.add("Bone");
    names.add("White");
    names.add("Beige");
    names.add("Ivory");
    names.add("Cream");
    names.add("Off white");
    from.setNames(names);

    to = mapper.map(from, NamesSet.class);

    assertNotNull(to);
    assertEquals(names.size(), to.getNames().size());
  }

  @Test
  public void testSetPrivateField() {
    mapper = getMapper("isaccessiblemapping.xml");
    Foo src = newInstance(Foo.class);
    List<String> list = (ArrayList<String>) newInstance(ArrayList.class);
    list.add("test1");
    list.add("test2");
    src.setCategories(list);

    FooPrime dest = mapper.map(src, FooPrime.class);
    assertNotNull(dest);
  }

  @Test
  public void testStringToIndexedSet_UsingHint() {
    mapper = getMapper("indexMapping.xml");
    Mccoy src = newInstance(Mccoy.class);
    src.setStringProperty(String.valueOf(System.currentTimeMillis()));
    src.setField2("someValue");

    MccoyPrime dest = mapper.map(src, MccoyPrime.class, "usingDestHint");
    Set<?> destSet = dest.getFieldValueObjects();
    assertNotNull("dest set should not be null", destSet);
    assertEquals("dest set should contain 1 entry", 1, destSet.size());
    Object entry = destSet.iterator().next();
    assertTrue("dest set entry should be instance of FieldValue", entry instanceof FieldValue);
    assertEquals("invalid value for dest object", src.getStringProperty(), ((FieldValue) entry).getValue("theKey"));
  }

  public void testAllowedExceptionsDoNotThrowException() throws Exception {
    Mapper mapper = getMapper("allowedExceptionsMapping.xml");
    TestObject to2 = newInstance(TestObject.class);
    to2.setThrowNonAllowedExceptionOnMap("do not throw me");
    try {
      mapper.map(to2, TestObjectPrime.class);
    } catch (RuntimeException e) {
      fail("This should not have been thrown");
    }
  }

  public void testAllowedExceptions_ImplicitDoNotThrow() throws Exception {
    ThrowException to2 = newInstance(ThrowException.class);
    to2.setThrowNotAllowedException("do not throw me");
    try {
      mapper.map(to2, ThrowExceptionPrime.class);
    } catch (RuntimeException e) {
      fail("This should not have been thrown");
    }
  }

  @Test
  public void testPrimitiveArrayToList() throws Exception {
    mapper = getMapper("primitiveArrayToListMapping.xml");

    int[] i = new int[] { 1, 2, 3 };
    PrimitiveArrayObj src = newInstance(PrimitiveArrayObj.class);
    src.setField1(i);

    PrimitiveArrayObjPrime dest = mapper.map(src, PrimitiveArrayObjPrime.class);

    assertNotNull("dest list field should not be null", dest.getField1());
    assertEquals("invalid dest field size", i.length, dest.getField1().size());

    List<?> srcObjectList = CollectionUtils.convertPrimitiveArrayToList(i);
    assertEquals("invalid dest field value", srcObjectList, dest.getField1());
  }

  @Test
  public void testPrimitiveArrayToList_UsingHint() throws Exception {
    mapper = getMapper("primitiveArrayToListMapping.xml");

    int[] srcArray = new int[] { 1, 2, 3 };
    PrimitiveArrayObj src = newInstance(PrimitiveArrayObj.class);
    src.setField1(srcArray);

    PrimitiveArrayObjPrime dest = mapper.map(src, PrimitiveArrayObjPrime.class, "primitiveToArrayUsingHint");

    assertNotNull("dest list field should not be null", dest.getField1());
    assertEquals("invalid dest field size", srcArray.length, dest.getField1().size());

    for (int i = 0; i < srcArray.length; i++) {
      String srcValue = String.valueOf(srcArray[i]);
      String resultValue = (String) dest.getField1().get(i);
      assertEquals("invalid result entry value", srcValue, resultValue);
    }
  }

  @Test
  public void testInterface() throws Exception {
    mapper = getMapper("interfaceMapping.xml");
    ApplicationUser user = newInstance(ApplicationUser.class);
    user.setSubscriberNumber("123");

    // Mapping works
    UpdateMember destObject = mapper.map(user, UpdateMember.class);

    assertEquals("invalid value for subsriber #", user.getSubscriberNumber(), destObject.getSubscriberKey().getSubscriberNumber());

    // Clear value
    destObject = new UpdateMember();

    // Mapping doesn't work
    mapper.map(user, destObject);

    assertNotNull("dest field should not be null", destObject.getSubscriberKey());
    assertEquals("invalid value for subsriber #", user.getSubscriberNumber(), destObject.getSubscriberKey().getSubscriberNumber());
  }

  @Test
  public void testCustomFieldMapper() throws Exception {
    CustomFieldMapper customFieldMapper = new TestCustomFieldMapper();
    ((DozerBeanMapper) mapper).setCustomFieldMapper(customFieldMapper);

    String currentTime = String.valueOf(System.currentTimeMillis());
    SimpleObj src = newInstance(SimpleObj.class);
    src.setField1(currentTime);
    src.setField6("field6Value" + currentTime);

    SimpleObjPrime dest = mapper.map(src, SimpleObjPrime.class);

    assertNotNull("dest field1 should not be null", dest.getField1());
    assertNotNull("dest field6 should not be null", dest.getField6());
    assertEquals("dest field1 should have been set by custom field mapper", TestCustomFieldMapper.fieldValue, dest.getField1());
    assertEquals("dest field6 should NOT have been set by custom field mapper", src.getField6(), dest.getField6());
  }

  @Test
  public void testPrivateConstructor() throws Exception {
    PrivateConstructorBean src = PrivateConstructorBean.newInstance();
    src.setField1("someValue");

    PrivateConstructorBeanPrime dest = mapper.map(src, PrivateConstructorBeanPrime.class);

    assertNotNull("dest bean should not be null", dest);
    assertEquals("field1 not mapped correctly", src.getField1(), dest.getField1());
  }

  /*
   * Bug #1549738
   */
  @Test
  public void testSetMapping_UppercaseFieldNameInXML() throws Exception {
    // For some reason the resulting SomeVO contains a Set with 4 objects. 2 SomeOtherDTO's and 2 SomeOtherVO's. I
    // believe it
    // should only contain 2 SomeOtherVO's. It has something to do with specifying the field name starting with cap in
    // the mapping file. If
    // you change the field mapping to start with lower case it seems to map correctly.
    Mapper mapper = getMapper("setMappingWithUpperCaseFieldName.xml");

    SomeDTO someDto = newInstance(SomeDTO.class);
    someDto.setField1(new Integer("1"));

    SomeOtherDTO someOtherDto = newInstance(SomeOtherDTO.class);
    someOtherDto.setOtherField2(someDto);
    someOtherDto.setOtherField3("value1");

    SomeDTO someDto2 = newInstance(SomeDTO.class);
    someDto2.setField1(new Integer("2"));

    SomeOtherDTO someOtherDto2 = newInstance(SomeOtherDTO.class);
    someOtherDto2.setOtherField2(someDto2);
    someOtherDto2.setOtherField3("value2");

    SomeDTO src = newInstance(SomeDTO.class);
    src.setField2(new SomeOtherDTO[] { someOtherDto2, someOtherDto });

    SomeVO dest = mapper.map(src, SomeVO.class);

    assertEquals("incorrect resulting set size", src.getField2().length, dest.getField2().size());
    // TODO: add more asserts
  }

  @Test
  public void testGlobalBeanFactoryAppliedToDefaultMappings() throws Exception {
    mapper = getMapper("global-configuration.xml");
    TestObjectPrime dest = mapper.map(newInstance(TestObject.class), TestObjectPrime.class);

    assertNotNull("created by factory name should not be null", dest.getCreatedByFactoryName());
    assertEquals(SampleDefaultBeanFactory.class.getName(), dest.getCreatedByFactoryName());
  }

  @Test
  public void testStringToDateMapping() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SS");
    String dateStr = "01/29/1975 10:45:13:25";
    TestObject sourceObj = newInstance(TestObject.class);
    sourceObj.setDateStr(dateStr);
    TestObjectPrime result = mapper.map(sourceObj, TestObjectPrime.class);
    assertEquals(df.parse(dateStr), result.getDateFromStr());
    assertEquals(dateStr, df.format(result.getDateFromStr()));

    TestObject result2 = mapper.map(result, TestObject.class);
    assertEquals(df.format(result.getDateFromStr()), result2.getDateStr());
    assertEquals(result.getDateFromStr(), df.parse(result2.getDateStr()));
  }

  @Test
  public void testMethodMapping() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    MethodFieldTestObject sourceObj = newInstance(MethodFieldTestObject.class);
    sourceObj.setIntegerStr("1500");
    sourceObj.setPriceItem("3500");
    sourceObj.setFieldOne("fieldOne");
    MethodFieldTestObject2 result = mapper.map(sourceObj, MethodFieldTestObject2.class);
    assertEquals("invalid result object size", 1, result.getIntegerList().size());
    assertEquals("invalid result object value", 3500, result.getTotalPrice());
    assertEquals("invalid result object value", "fieldOne", result.getFieldOne());
    // map back
    MethodFieldTestObject result2 = mapper.map(result, MethodFieldTestObject.class);
    // if no exceptions we thrown we are good. stopOnErrors = true. both values will be null
    // since this is a one-way mapping we shouldn't have a value
    assertNull(result2.getFieldOne());
  }

  @Test
  public void testNoReadMethod() throws Exception {
    // If the field doesnt have a getter/setter, dont add it is a default field to be mapped.
    mapper = getMapper("dozerBeanMapping.xml");
    NoReadMethod src = newInstance(NoReadMethod.class);
    src.setNoReadMethod("somevalue");

    NoReadMethodPrime dest = mapper.map(src, NoReadMethodPrime.class);
    assertNull("field should be null because no read method exists for field", dest.getXXXXX());
  }

  @Test
  public void testNoReadMethodSameClassTypes() throws Exception {
    // If the field doesnt have a getter/setter, dont add it is a default field to be mapped.
    mapper = getMapper("dozerBeanMapping.xml");
    NoReadMethod src = newInstance(NoReadMethod.class);
    src.setNoReadMethod("somevalue");

    NoReadMethod dest = mapper.map(src, NoReadMethod.class);
    assertNull("field should be null because no read method exists for field", dest.getXXXXX());
  }

  @Test
  public void testNoReadMethod_GetterOnlyWithParams() throws Exception {
    // Dont use getter methods that have a param when discovering default fields to be mapped.
    mapper = getMapper("dozerBeanMapping.xml");
    NoReadMethod src = newInstance(NoReadMethod.class);
    src.setOtherNoReadMethod("someValue");

    NoReadMethod dest = mapper.map(src, NoReadMethod.class);
    assertNull("field should be null because no read method exists for field", dest.getOtherNoReadMethod(-1));
  }

  @Test
  public void testNoWriteMethod() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    NoWriteMethod src = newInstance(NoWriteMethod.class);
    src.setXXXXXX("someValue");

    NoWriteMethodPrime dest = mapper.map(src, NoWriteMethodPrime.class);
    assertNull("field should be null because no write method exists for field", dest.getNoWriteMethod());
  }

  @Test
  public void testNoWriteMethodSameClassTypes() throws Exception {
    // When mapping between identical types, if the field doesnt have a getter/setter, dont
    // add it is a default field to be mapped.
    mapper = getMapper("dozerBeanMapping.xml");
    NoWriteMethod src = newInstance(NoWriteMethod.class);
    src.setXXXXXX("someValue");

    mapper.map(newInstance(NoReadMethod.class), NoReadMethod.class);

    NoWriteMethod dest = mapper.map(src, NoWriteMethod.class);
    assertNull("field should be null because no write method exists for field", dest.getNoWriteMethod());
  }

  @Test
  public void testNoVoidSetters() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    NoVoidSetters src = newInstance(NoVoidSetters.class);
    src.setDescription("someValue");
    src.setI(1);

    NoVoidSetters dest = mapper.map(src, NoVoidSetters.class);
    assertEquals("invalid dest field value", src.getDescription(), dest.getDescription());
    assertEquals("invalid dest field value", src.getI(), dest.getI());
  }

  @Test
  public void testNullField() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    AnotherTestObject src = newInstance(AnotherTestObject.class);
    src.setField2(null);
    AnotherTestObjectPrime dest = newInstance(AnotherTestObjectPrime.class);
    dest.setField2(Integer.valueOf("555"));
    // check that null overrides an existing value
    mapper.map(src, dest);
    assertNull("dest field should be null", dest.getField2());
  }

  @Test
  public void testNullField2() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    // Test that String --> String with an empty String input value results
    // in the destination field being an empty String and not null.
    String input = "";
    TestObject src = newInstance(TestObject.class);
    src.setOne(input);

    TestObjectPrime dest = mapper.map(src, TestObjectPrime.class);
    assertNotNull("dest field should not be null", dest.getOnePrime());
    assertEquals("invalid dest field value", input, dest.getOnePrime());
  }

  @Test
  public void testNullToPrimitive() throws Exception {
    mapper = getMapper("dozerBeanMapping.xml");
    AnotherTestObject src = newInstance(AnotherTestObject.class);
    AnotherTestObjectPrime prime = newInstance(AnotherTestObjectPrime.class);
    TestObject to = newInstance(TestObject.class);
    to.setThePrimitive(AnotherTestObjectPrime.DEFAULT_FIELD1);
    prime.setTo(to);
    mapper.map(src, prime);
    // check primitive on deep field
    // primitive should still be default
    assertEquals("invalid field value", AnotherTestObjectPrime.DEFAULT_FIELD1, prime.getField1());
    assertEquals("invalid field value", AnotherTestObjectPrime.DEFAULT_FIELD1, prime.getTo().getThePrimitive());
  }

  @Test
  public void testGlobalRelationshipType() throws Exception {
    mapper = getMapper("relationship-type-global-configuration.xml");
    TestObject src = new TestObject();
    src.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a" })));

    TestObjectPrime dest = new TestObjectPrime();
    dest.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a", "b" })));

    mapper.map(src, dest);

    assertEquals("wrong # of elements in dest list for non-cumulative mapping", 2, dest.getHintList().size());
  }

  @Test
  public void testClassMapRelationshipType() throws Exception {
    mapper = getMapper("relationshipTypeMapping.xml");
    TestObject src = new TestObject();
    src.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a" })));

    TestObjectPrime dest = new TestObjectPrime();
    dest.setHintList(new ArrayList<String>(Arrays.asList(new String[] { "a", "b" })));

    mapper.map(src, dest);

    assertEquals("wrong # of elements in dest list for non-cumulative mapping", 2, dest.getHintList().size());
  }

  @Test
  public void testRemoveOrphans() {
    mapper = getMapper("removeOrphansMapping.xml");

    MyClassA myClassA = new MyClassA();
    MyClassB myClassB = new MyClassB();

    Fruit apple = new Fruit();
    apple.setName("Apple");
    Fruit banana = new Fruit();
    banana.setName("Banana");
    Fruit grape = new Fruit();
    grape.setName("Grape");
    Fruit orange = new Fruit();
    orange.setName("Orange");
    Fruit kiwiFruit = new Fruit();
    kiwiFruit.setName("Kiwi Fruit");

    List<Fruit> srcFruits = new ArrayList<Fruit>();
    srcFruits.add(apple);
    srcFruits.add(banana);
    srcFruits.add(kiwiFruit);

    List<Fruit> destFruits = new ArrayList<Fruit>();
    destFruits.add(grape); // not in src
    destFruits.add(banana); // shared with src fruits
    destFruits.add(orange); // not in src

    myClassA.setAStringList(srcFruits);
    myClassB.setAStringList(destFruits);

    mapper.map(myClassA, myClassB, "testRemoveOrphansOnList");

    assertEquals(3, myClassB.getAStringList().size());
    assertTrue(myClassB.getAStringList().contains(apple));
    assertTrue(myClassB.getAStringList().contains(banana));
    assertTrue(myClassB.getAStringList().contains(kiwiFruit));
    assertFalse(myClassB.getAStringList().contains(grape));
    assertFalse(myClassB.getAStringList().contains(orange));
  }

  @Test
  public void testOrphanRemovalSet() {
    mapper = getMapper("removeOrphansMapping.xml");
    Parent parent = new Parent(new Long(1), "parent");
    Child child1 = new Child(new Long(1), "child1");
    Set<Child> childrenSet = new HashSet<Child>();
    childrenSet.add(child1);
    parent.setChildrenSet(childrenSet);

    ParentPrime parentPrime = mapper.map(parent, ParentPrime.class);
    // Make sure the first one was mapped ok.
    assertEquals(parent.getChildrenSet().size(), parentPrime.getChildrenSet().size());

    ChildPrime child2 = new ChildPrime(new Long(2L), "child2");
    parentPrime.getChildrenSet().add(child2);
    mapper.map(parentPrime, parent);
    // Make sure adding one works ok.
    assertEquals(parentPrime.getChildrenSet().size(), parent.getChildrenSet().size());

    parentPrime.getChildrenSet().clear();
    mapper.map(parentPrime, parent);
    // Make sure REMOVING them (the orphan children) works ok.
    assertEquals(parentPrime.getChildrenSet().size(), parent.getChildrenSet().size());
  }

  @Test
  public void testOrphanRemovalList() {
    mapper = getMapper("removeOrphansMapping.xml");
    Parent parent = new Parent(new Long(1), "parent");
    Child child1 = new Child(new Long(1), "child1");
    List<Child> childrenList = new ArrayList<Child>();
    childrenList.add(child1);
    parent.setChildrenList(childrenList);

    ParentPrime parentPrime = mapper.map(parent, ParentPrime.class);
    // Make sure the first one was mapped ok.
    assertEquals(parent.getChildrenList().size(), parentPrime.getChildrenList().size());

    ChildPrime child2 = new ChildPrime(new Long(2L), "child2");
    parentPrime.getChildrenList().add(child2);
    mapper.map(parentPrime, parent);
    // Make sure adding one works ok.
    assertEquals(parentPrime.getChildrenList().size(), parent.getChildrenList().size());

    parentPrime.getChildrenList().clear();
    mapper.map(parentPrime, parent);
    // Make sure REMOVING them (the orphan children) works ok.
    assertEquals(parentPrime.getChildrenList().size(), parent.getChildrenList().size());
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    >

    <TextView
        android:id="@+id/warningTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:visibility="visible"
        android:text="@string/warning_main"
        android:textColor="@color/white"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/friends_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/recyclerview_margin"
        android:visibility="gone"
        />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/deskfloatingactionbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_plus"
        app:fabSize="normal"
        android:layout_gravity="bottom|right"
        android:layout_margin="@dimen/floatingactionbutton_margin"
        app:layout_anchor="@id/friends_recyclerview"
        app:layout_anchorGravity="bottom|right|end"
        app:backgroundTint="@color/yellow"
        />

</android.support.design.widget.CoordinatorLayout>


text:
package com.contained.game.data;

import java.util.Map;

import com.google.common.collect.ImmutableMap;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;

public class Data {
	/*
	 *  Occupational item groups
	 *  (Useful data for classifying people's actions into certain "jobs")
	 *
	 *  The "rank" value in the OccupationRanks below are the weights
	 *  of each of these items -- this number is how much ownership of the
	 *  item counts towards evidence of the player belonging to the
	 *  respective occupational group.
	*/
	public static final int MINING = 0;
	public static final int COOKING = 1;
	public static final int FARMING = 2;
	public static final int FISHING = 3;
	public static final int LUMBER = 4;
	public static final int FIGHTER = 5;
	public static final int POTION = 6;
	public static final int BUILDING = 7;
	public static final int MACHINE = 8;
	public static final int TRANSPORT = 9;

	public static class OccupationRank {
		public int occupationID;
		public int rank;

		public OccupationRank(int occupationID, int rank) {
			this.occupationID = occupationID;
			this.rank = rank;
		}
	}

	public static final Map<DataItemStack, OccupationRank> occupationMap =
			ImmutableMap.<DataItemStack, OccupationRank>builder()

	//Mining
	.put(new DataItemStack(Items.coal), 		   new OccupationRank(MINING, 1))
	.put(new DataItemStack(Items.redstone), 	   new OccupationRank(MINING, 1))
	.put(new DataItemStack(Items.diamond), 		   new OccupationRank(MINING, 8))
	.put(new DataItemStack(Blocks.iron_ore), 	   new OccupationRank(MINING, 1))
	.put(new DataItemStack(Blocks.gold_ore), 	   new OccupationRank(MINING, 3))
	.put(new DataItemStack(Items.emerald), 		   new OccupationRank(MINING, 4))
	.put(new DataItemStack(Items.dye, 1, 4), 	   new OccupationRank(MINING, 1)) //lapis lazuli
	.put(new DataItemStack(Items.wooden_pickaxe),  new OccupationRank(MINING, 16))
	.put(new DataItemStack(Items.stone_pickaxe),   new OccupationRank(MINING, 16))
	.put(new DataItemStack(Items.iron_pickaxe),	   new OccupationRank(MINING, 24))
	.put(new DataItemStack(Items.golden_pickaxe),  new OccupationRank(MINING, 16))
	.put(new DataItemStack(Items.diamond_pickaxe), new OccupationRank(MINING, 32))

	//Cooking
	.put(new DataItemStack(Items.apple), 		   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.baked_potato),    new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.beef), 		   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.chicken), 		   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.bread), 		   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.cake), 		   new OccupationRank(COOKING, 8))
	.put(new DataItemStack(Items.cookie), 		   new OccupationRank(COOKING, 1))
	.put(new DataItemStack(Items.cooked_beef), 	   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.cooked_chicken),  new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.cooked_porkchop), new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.cooked_fished),   new OccupationRank(COOKING, 3))
	.put(new DataItemStack(Items.melon), 		   new OccupationRank(COOKING, 1))
	.put(new DataItemStack(Items.mushroom_stew),   new OccupationRank(COOKING, 3))
	.put(new DataItemStack(Items.golden_apple),    new OccupationRank(COOKING, 6))
	.put(new DataItemStack(Items.porkchop), 	   new OccupationRank(COOKING, 2))
	.put(new DataItemStack(Items.pumpkin_pie), 	   new OccupationRank(COOKING, 3))

	//Farming
	.put(new DataItemStack(Items.wheat), 		   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Blocks.pumpkin), 	   new OccupationRank(FARMING, 2))
	.put(new DataItemStack(Items.reeds), 		   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Items.carrot), 		   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Items.potato), 		   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Items.poisonous_potato),new OccupationRank(FARMING, 2))
	.put(new DataItemStack(Items.wheat_seeds), 	   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Items.melon_seeds), 	   new OccupationRank(FARMING, 2))
	.put(new DataItemStack(Items.pumpkin_seeds),   new OccupationRank(FARMING, 2))
	.put(new DataItemStack(Items.dye, 1, 15), 	   new OccupationRank(FARMING, 1)) //bone meal
	.put(new DataItemStack(Blocks.brown_mushroom), new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Blocks.red_mushroom),   new OccupationRank(FARMING, 1))
	.put(new DataItemStack(Items.wooden_hoe), 	   new OccupationRank(FARMING, 16))
	.put(new DataItemStack(Items.stone_hoe), 	   new OccupationRank(FARMING, 16))
	.put(new DataItemStack(Items.iron_hoe), 	   new OccupationRank(FARMING, 24))
	.put(new DataItemStack(Items.golden_hoe), 	   new OccupationRank(FARMING, 16))
	.put(new DataItemStack(Items.diamond_hoe), 	   new OccupationRank(FARMING, 32))

	//Fishing
	.put(new DataItemStack(Items.fishing_rod), 	   new OccupationRank(FISHING, 32))
	.put(new DataItemStack(Items.fish, 1, 0), 	   new OccupationRank(FISHING, 4))  //raw fish
	.put(new DataItemStack(Items.fish, 1, 1), 	   new OccupationRank(FISHING, 8))  //salmon
	.put(new DataItemStack(Items.fish, 1, 2), 	   new OccupationRank(FISHING, 16)) //clownfish
	.put(new DataItemStack(Items.fish, 1, 3), 	   new OccupationRank(FISHING, 16)) //pufferfish

	//Lumberjacking
	.put(new DataItemStack(Blocks.sapling), 	   new OccupationRank(LUMBER, 4))
	.put(new DataItemStack(Blocks.leaves), 		   new OccupationRank(LUMBER, 1))
	.put(new DataItemStack(Blocks.leaves2), 	   new OccupationRank(LUMBER, 1))
	.put(new DataItemStack(Blocks.log), 		   new OccupationRank(LUMBER, 2))
	.put(new DataItemStack(Blocks.log2),		   new OccupationRank(LUMBER, 2))
	.put(new DataItemStack(Items.wooden_axe), 	   new OccupationRank(LUMBER, 16))
	.put(new DataItemStack(Items.stone_axe), 	   new OccupationRank(LUMBER, 16))
	.put(new DataItemStack(Items.iron_axe), 	   new OccupationRank(LUMBER, 24))
	.put(new DataItemStack(Items.golden_axe), 	   new OccupationRank(LUMBER, 16))
	.put(new DataItemStack(Items.diamond_axe), 	   new OccupationRank(LUMBER, 32))

	//Fighting
	.put(new DataItemStack(Items.arrow), 		   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.rotten_flesh),    new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.bone), 		   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.string), 		   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.spider_eye), 	   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.gunpowder), 	   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.blaze_rod), 	   new OccupationRank(FIGHTER, 2))
	.put(new DataItemStack(Items.ghast_tear), 	   new OccupationRank(FIGHTER, 6))
	.put(new DataItemStack(Items.ender_pearl), 	   new OccupationRank(FIGHTER, 6))
	.put(new DataItemStack(Items.slime_ball), 	   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.magma_cream),	   new OccupationRank(FIGHTER, 1))
	.put(new DataItemStack(Items.wooden_sword),    new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.stone_sword),	   new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.iron_sword),	   new OccupationRank(FIGHTER, 24))
	.put(new DataItemStack(Items.golden_sword),    new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.diamond_sword),   new OccupationRank(FIGHTER, 32))
	.put(new DataItemStack(Items.bow), 		   	   new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.leather_helmet),  new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.leather_boots),   new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.leather_leggings),      new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.leather_chestplate),    new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.golden_helmet),   new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.golden_boots),    new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.golden_leggings),       new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.golden_chestplate),     new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.chainmail_helmet),  new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.chainmail_boots),   new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.chainmail_leggings),    new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.chainmail_chestplate),  new OccupationRank(FIGHTER, 8))
	.put(new DataItemStack(Items.iron_helmet),     new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.iron_boots),      new OccupationRank(FIGHTER, 16))
	.put(new DataItemStack(Items.iron_leggings),   new OccupationRank(FIGHTER, 24))
	.put(new DataItemStack(Items.iron_chestplate), new OccupationRank(FIGHTER, 24))
	.put(new DataItemStack(Items.diamond_helmet),  new OccupationRank(FIGHTER, 32))
	.put(new DataItemStack(Items.diamond_boots),   new OccupationRank(FIGHTER, 32))
	.put(new DataItemStack(Items.diamond_leggings),      new OccupationRank(FIGHTER, 48))
	.put(new DataItemStack(Items.diamond_chestplate),    new OccupationRank(FIGHTER, 48))

	//Brewing
	.put(new DataItemStack(Items.brewing_stand),   new OccupationRank(POTION, 32))
	.put(new DataItemStack(Items.glass_bottle),    new OccupationRank(POTION, 3))
	.put(new DataItemStack(Items.potionitem),      new OccupationRank(POTION, 5))
	.put(new DataItemStack(Items.nether_wart), 	   new OccupationRank(POTION, 3))
	.put(new DataItemStack(Items.blaze_powder),    new OccupationRank(POTION, 1))
	.put(new DataItemStack(Items.fermented_spider_eye),  new OccupationRank(POTION, 4))
	.put(new DataItemStack(Items.sugar), 		   new OccupationRank(POTION, 1))
	.put(new DataItemStack(Items.glowstone_dust),  new OccupationRank(POTION, 1))
	.put(new DataItemStack(Items.golden_carrot),   new OccupationRank(POTION, 1))
	.put(new DataItemStack(Items.speckled_melon),  new OccupationRank(POTION, 4))

	//Building
	.put(new DataItemStack(Blocks.fence), 		   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.ladder), 		   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.birch_stairs),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.brick_block),    new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.brick_stairs),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.carpet), 		   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.cobblestone_wall),     new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.fence_gate), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.glass_pane), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.iron_bars), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Items.iron_door), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Items.wooden_door),     new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.jungle_stairs),  new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.mossy_cobblestone),    new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.nether_brick_fence),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.nether_brick_stairs),  new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.oak_stairs), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.stone_slab), 	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.acacia_stairs),  new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.wooden_slab),    new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Items.sign),	    	   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.spruce_stairs),  new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.sandstone_stairs), 	 new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.quartz_stairs),  new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.quartz_block, 1, 1),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.quartz_block, 1, 2),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.quartz_block, 1, 3),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.quartz_block, 1, 4),   new OccupationRank(BUILDING, 1))
	.put(new DataItemStack(Blocks.trapdoor), 	   new OccupationRank(BUILDING, 1))

	//Engineering
	.put(new DataItemStack(Blocks.redstone_lamp),  new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.redstone_torch), new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.lever), 		   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.wooden_button),  new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.wooden_pressure_plate),new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.stone_button),   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.stone_pressure_plate), new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.anvil), 		   new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.enchanting_table), 	 new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.crafting_table), new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.furnace), 	   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.dispenser), 	   new OccupationRank(MACHINE, 8))
	.put(new DataItemStack(Items.cauldron), 	   new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.hopper), 		   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.beacon), 		   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.noteblock), 	   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.dropper), 	   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.ender_chest),    new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.chest), 	       new OccupationRank(MACHINE, 2))
	.put(new DataItemStack(Blocks.trapped_chest),  new OccupationRank(MACHINE, 3))
	.put(new DataItemStack(Blocks.tnt), 		   new OccupationRank(MACHINE, 1))
	.put(new DataItemStack(Blocks.tripwire_hook),  new OccupationRank(MACHINE, 3))
	.put(new DataItemStack(Items.comparator), 	   new OccupationRank(MACHINE, 3))
	.put(new DataItemStack(Items.repeater), 	   new OccupationRank(MACHINE, 3))
	.put(new DataItemStack(Blocks.piston), 		   new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.sticky_piston),  new OccupationRank(MACHINE, 4))
	.put(new DataItemStack(Blocks.command_block),  new OccupationRank(MACHINE, 16))
	.put(new DataItemStack(Blocks.daylight_detector),    new OccupationRank(MACHINE, 4))

	//Transportation
	.put(new DataItemStack(Blocks.rail), 		   new OccupationRank(TRANSPORT, 1))
	.put(new DataItemStack(Blocks.detector_rail),  new OccupationRank(TRANSPORT, 3))
	.put(new DataItemStack(Blocks.golden_rail),    new OccupationRank(TRANSPORT, 3))
	.put(new DataItemStack(Items.minecart), 	   new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.chest_minecart),  new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.furnace_minecart),new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.tnt_minecart),    new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.hopper_minecart), new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.command_block_minecart), new OccupationRank(TRANSPORT, 16))
	.put(new DataItemStack(Items.boat), 		   new OccupationRank(TRANSPORT, 16))
	.build();

	public static final String[] occupationNames = {
		"Mining", "Cooking", "Farming", "Fishing", "Lumberjacking"
		, "Fighting", "Brewing", "Building", "Engineering", "Transporting"
	};

	//Set all values in the array to zero.
	public static void zero(int[] vals) {
		for(int i=0; i<vals.length; i++)
			vals[i] = 0;
	}

	public static void zero(double[] vals) {
		for(int i=0; i<vals.length; i++)
			vals[i] = 0;
	}

	public static void zero(float[] vals) {
		for(int i=0; i<vals.length; i++)
			vals[i] = 0;
	}

	//Translate first element of array to zero, and shift all other
	//elements in array by the same amount as the first element.
	public static int[] convertBaseline(int[] array) {
		int[] retArray = new int[array.length];
		for(int i=0; i<array.length; i++)
			retArray[i] = array[i]-array[0];
		return retArray;
	}

	public static double[] convertBaseline(double[] array) {
		double[] retArray = new double[array.length];
		for(int i=0; i<array.length; i++)
			retArray[i] = array[i]-array[0];
		return retArray;
	}

	public static Double[] convertBaseline(Double[] array) {
		Double[] retArray = new Double[array.length];
		for(int i=0; i<array.length; i++)
			retArray[i] = array[i]-array[0];
		return retArray;
	}

	public static float[] convertBaseline(float[] array) {
		float[] retArray = new float[array.length];
		for(int i=0; i<array.length; i++)
			retArray[i] = array[i]-array[0];
		return retArray;
	}

	//Starting index for a sliding window over an array.
	public static int swStart(int length, int windowSize) {
		return Math.max(0, length-windowSize);
	}

	//Terminating index for a sliding window over an array.
	public static int swEnd(int length, int windowSize) {
		return Math.min(length,  swStart(length, windowSize)+windowSize);
	}

	//Modified version of getTagCompound that will return an
	//empty tag compound instead of null if the item has no tag.
	public static NBTTagCompound getTagCompound(ItemStack stack) {
		NBTTagCompound itemData = stack.getTagCompound();
		if (itemData == null)
			itemData = new NBTTagCompound();
		return itemData;
	}
}


text:
require 'squeel/adapters/active_record/compat'

module ActiveRecord
  module Associations
    class AssociationScope
      def eval_scope(klass, scope, owner)
        if scope.is_a?(Relation)
          scope
        else
          klass.unscoped.instance_exec(owner, &scope).visited
        end
      end
    end
  end
end


text:
<!doctype html>

    <title>Student Loan Repayment Calculator</title>

    <form action="">
      I'm on plan
      <select id="plan">
        <option value="p1">1</option>
        <option value="p2">2</option>
      </select>
       with an interest rate of <input type="text" id="p1interest" value="1.5">%.

      My expected yearly income is <input type="text" id="income" >GBP, and my current loan balance is <input type="text" id="loan">GBP.

      I graduate(d) in <input type="text" id="gradyear">.
    </form>
    <button id="update">Update</button>

      <canvas id="canvas"></canvas>


text:
bool osStream::seekCurrentPosition(gtSize_t offset)
{
    return seekCurrentPosition(OS_STREAM_CURRENT_POSITION, offset);
}

// ---------------------------------------------------------------------------
// Name:        osStream::currentPosition
// Description: Returns the stream current position, relative to the
//              stream begin position.
// Return Val:  long - The stream current position (relative to the stream beginning).
//                     or 0 in case of failure.
// Author:      AMD Developer Tools Team
// Date:        3/6/2004
// ---------------------------------------------------------------------------
gtSize_t osStream::currentPosition() const
{
    gtSize_t offset = 0;

    // Get the stream current position (relative to the stream beginning):
    bool rc = currentPosition(OS_STREAM_BEGIN, offset);

    // In case of failure - we return 0:
    if (!rc)
    {
        offset = 0;
    }

    return offset;
}


text:
package de.hilling.junit.cdi.service;

import de.hilling.junit.cdi.BackendServiceException;
import de.hilling.junit.cdi.annotations.ActivatableTestImplementation;
import de.hilling.junit.cdi.beans.Person;
import de.hilling.junit.cdi.lifecycle.TestEvent;
import de.hilling.junit.cdi.scope.TestState;
import org.junit.jupiter.api.extension.ExtensionContext;

import jakarta.enterprise.event.Observes;
import java.lang.reflect.InvocationTargetException;

@ActivatableTestImplementation
public class BackendServiceTestImplementation extends BackendService {

    private int invocations;

    private RuntimeException exceptionToThrow;

    @Override
    public String storePerson(Person person) {
        if (exceptionToThrow != null) {
            throw exceptionToThrow;
        } else {
            invocations++;
        }
        return null;
    }

    protected void testStarted(@Observes @TestEvent(TestState.STARTING) ExtensionContext context) {
        context.getTestMethod().ifPresent(m -> {
            final BackendServiceException serviceException = m.getAnnotation(BackendServiceException.class);
            if (serviceException != null) {
                try {
                    exceptionToThrow = serviceException.value()
                                                       .getDeclaredConstructor()
                                                       .newInstance();
                } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException e) {
                    throw new RuntimeException("creating test exception failed", e);
                }
            }
        });
    }

    public int getInvocations() {
        return invocations;
    }
}


text:
package org.mifos.application.admin.system.persistence;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.springframework.beans.factory.annotation.Autowired;

public class AppliedUpgradesDaoHibernateIntegrationTest extends MifosIntegrationTestCase {

    @Autowired
    private AppliedUpgradesDao appliedUpgradesDao;

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testGetAppliedUpgrades() throws SQLException {
        List<Integer> upgrades = appliedUpgradesDao.getAppliedUpgrades();

        StaticHibernateUtil.initialize();
        Connection connection = StaticHibernateUtil.getSessionTL().connection();
        ResultSet rs = connection.createStatement().executeQuery("select count(upgrade_id) from applied_upgrades");
        rs.first();
        int expected = rs.getInt(1);

        Assert.assertEquals(expected, upgrades.size());
    }

}


text:
from msrest.serialization import Model

class BaselineMetadataValue(Model):
    """Represents a baseline metadata value.

    :param name: the name of the metadata.
    :type name: ~azure.mgmt.monitor.models.LocalizableString
    :param value: the value of the metadata.
    :type value: str
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'LocalizableString'},
        'value': {'key': 'value', 'type': 'str'},
    }

    def __init__(self, *, name=None, value: str=None, **kwargs) -> None:
        super(BaselineMetadataValue, self).__init__(**kwargs)
        self.name = name
        self.value = value


text:
<?php

declare(strict_types=1);

namespace KejawenLab\Application\SemartHris\Component\Reason\Model;

use KejawenLab\Application\SemartHris\Component\Reason\ReasonType;

/**
 * @author Muhamad Surya Iksanudin <surya.iksanudin@gmail.com>
 */
interface ReasonInterface
{
    /**
     * @return string
     */
    public function getId(): string;

    /**
     * @return string
     */
    public function getCode(): string;

    /**
     * @return string
     */
    public function getName(): string;

    /**
     * @return string
     *
     * @see ReasonType
     */
    public function getType(): string;
}


text:
var POST_HEIGHT = 80;
var Positions = new Meteor.Collection(null);

Template.postItem.helpers({
  ownPost: () => {
    return this.userId == Meteor.userId();
  },
  domain: () => {
    var a = document.createElement('a');
    a.href = this.url;
    return a.hostname;
  },
  upvotedClass: () => {
    var userId = Meteor.userId();
    if (userId && !_.include(this.upvoters, userId)) {
      return 'btn-primary upvotable';
    } else {
      return 'disabled';
    }
  },
  attributes: () => {
    var post = _.extend({}, Positions.findOne({postId: this._id}), this);
    var newPosition = post._rank * POST_HEIGHT;
    var attributes = {};

    if (_.isUndefined(post.position)) {
      attributes.class = 'post invisible';
    } else {
      var delta = post.position - newPosition;
      attributes.style = "top: " + delta + "px";
      if (delta === 0)
        attributes.class = "post animate"
    }

    Meteor.setTimeout(() => {
      Positions.upsert({postId: post._id}, {$set: {position: newPosition}})
    });

    return attributes;
  }
});

Template.postItem.events({
  'click .upvotable': (e) => {
    e.preventDefault();
    Meteor.call('upvote', this._id);
  }
});


text:
require "spec_helper"

describe ::Protobuf::Nats do
  it "has a version number" do
    expect(Protobuf::Nats::VERSION).not_to be nil
  end

  class ExampleServiceKlassBro; end

  it "can generate a correct subscription key" do
    expect(described_class.subscription_key(ExampleServiceKlassBro, :yolo_dude)).to eq("rpc.example_service_klass_bro.yolo_dude")
  end

  describe "#on_error" do
    # Reset error callbacks.
    before { described_class.instance_variable_set(:@error_callbacks, nil) }
    after { described_class.instance_variable_set(:@error_callbacks, nil) }

    it "has a logger error handler" do
      expect(described_class.error_callbacks.size).to eq(1)
      expect(described_class).to receive(:log_error).with("test")
      described_class.notify_error_callbacks("test")
    end

    it "can have multiple error callbacks" do
      was_invoked = false
      described_class.on_error do |_error|
        was_invoked = true
      end
      expect(described_class.error_callbacks.size).to eq(2)
      described_class.notify_error_callbacks(::ArgumentError.new("test"))
      expect(was_invoked).to eq(true)
    end

    it "raises an argument error when a callback does not have arity of 1" do
      expect { described_class.on_error {} }.to raise_error(::ArgumentError)
    end
  end

  describe "#log_error" do
    let(:logger) { ::Logger.new(nil) }

    before do
      allow(::Protobuf::Logging).to receive(:logger).and_return(logger)
    end

    it "does not log an error with a backtrace" do
      expect(logger).to receive(:error).with("yolo")
      expect(logger).to_not receive(:error).with("")
      ::Protobuf::Nats.log_error(::ArgumentError.new("yolo"))
    end

    it "logs errors with backtrace" do
      error = ::ArgumentError.new("yolo")
      allow(error).to receive(:backtrace).and_return(["line 1", "line 2"])
      expect(logger).to receive(:error).with("yolo")
      expect(logger).to_not receive(:error).with("line 1\nline2")
      ::Protobuf::Nats.log_error(error)
    end
  end

  describe "#notify_error_callbacks" do
    it "logs an error raised by a callback" do
      the_error = ::RuntimeError.new("Save me from my callback sadness!")
      error_callback = lambda { |_error| fail the_error }
      allow(described_class).to receive(:error_callbacks).and_return([error_callback])

      expect(described_class).to receive(:log_error).with(the_error)
      described_class.notify_error_callbacks("yolo")
    end
  end
end


text:
#include "config.h"

#include "viewer-render.h"
#include "viewer-x.h"

#include <pango/pangoxft.h>

static void
default_substitute (FcPattern *pattern,
		    gpointer   data G_GNUC_UNUSED)
{
  FcPatternDel (pattern, FC_DPI);
  FcPatternAddInteger (pattern, FC_DPI, opt_dpi);

  if (opt_hinting != HINT_DEFAULT)
    {
      FcPatternDel (pattern, FC_HINTING);
      FcPatternAddBool (pattern, FC_HINTING, opt_hinting != HINT_NONE);

      FcPatternDel (pattern, FC_AUTOHINT);
      FcPatternAddBool (pattern, FC_AUTOHINT, opt_hinting == HINT_AUTO);
    }
}

static gpointer
pangoxft_view_create (const PangoViewer *klass)
{
  XViewer *instance;

  instance = x_view_create (klass);

  XftInit (NULL);

  pango_xft_set_default_substitute (instance->display, instance->screen,
				    default_substitute, NULL, NULL);

  return instance;
}

static void
pangoxft_view_destroy (gpointer instance)
{
  XViewer *x = (XViewer *)instance;

  pango_xft_shutdown_display (x->display, x->screen);

  x_view_destroy (instance);
}

static PangoContext *
pangoxft_view_get_context (gpointer instance)
{
  XViewer *x = (XViewer *) instance;

  return pango_font_map_create_context (pango_xft_get_font_map (x->display, x->screen));
}

typedef struct
{
  XftDraw *draw;
  XftColor color;
} MyXftContext;

static void
render_callback (PangoLayout *layout,
		 int          x,
		 int          y,
		 gpointer     context,
		 gpointer     state G_GNUC_UNUSED)
{
  MyXftContext *xft_context = (MyXftContext *) context;

  pango_xft_render_layout (xft_context->draw,
			   &xft_context->color,
			   layout,
			   x * PANGO_SCALE, y * PANGO_SCALE);
}

static void
pangoxft_view_render (gpointer      instance,
		      gpointer      surface,
		      PangoContext *context,
		      int          *width,
		      int          *height,
		      gpointer      state)
{
  XViewer *x = (XViewer *) instance;
  Pixmap pixmap = (Pixmap) surface;
  MyXftContext xft_context;
  XftDraw *draw;
  XftColor color;

  draw = XftDrawCreate (x->display, pixmap,
			DefaultVisual (x->display, x->screen),
			DefaultColormap (x->display, x->screen));

  /* XftDrawRect only fills solid.
   * Flatten with white.
   */
  color.color.red = ((opt_bg_color.red * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.green = ((opt_bg_color.green * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.blue = ((opt_bg_color.blue * opt_bg_alpha) >> 16) + (65535 - opt_bg_alpha);
  color.color.alpha = 65535;

  XftDrawRect (draw, &color, 0, 0, *width, *height);

  color.color.red = opt_fg_color.red;
  color.color.blue = opt_fg_color.green;
  color.color.green = opt_fg_color.blue;
  color.color.alpha = opt_fg_alpha;

  xft_context.draw = draw;
  xft_context.color = color;

  do_output (context, render_callback, NULL, &xft_context, state, width, height);

  XftDrawDestroy (draw);
}

const PangoViewer pangoxft_viewer = {
  "PangoXft",
  "xft",
  NULL,
  pangoxft_view_create,
  pangoxft_view_destroy,
  pangoxft_view_get_context,
  x_view_create_surface,
  x_view_destroy_surface,
  pangoxft_view_render,
  NULL,
  x_view_create_window,
  x_view_destroy_window,
  x_view_display
};


text:
This is a locally run application that serves as a web interface for ACM data and controlling the database. An RFID scanner
is attached through a serial connection to the application. This app can run on Windows, OS X and Linux.

# Requirements
Flask (http://flask.pocoo.org)
* SocketIO extension (https://flask-socketio.readthedocs.io/en/latest/)

AngularJS
* SocketIO (https://socket.io)

Python 3 (https://www.python.org/downloads/)
* PySerial (https://pythonhosted.org/pyserial/)
* GSpread (https://gspread.readthedocs.io/en/latest/)

# Installation
1. Install Python 3 and Flask
2. Install PySerial, GSpread, and Flask-SocketIO modules
3. Follow OAuth2 procedure in GSpread documentation UNLESS still using original spreadsheet.
   You will still need to install oauth2client `pip install --upgrade oauth2client` and PyOpenSSL `pip install PyOpenSSL`
   Email Brian for authorization file. See OAuth2 procedure for details on how authorization is obtained.
   In the database.py file, adjust the relative path to the JSON keyfile if needed.
   `credentials = ServiceAccountCredentials.from_json_keyfile_name('../../acm-dashboard.json', scope)`
4. App is started by running `python3 server.py`

# Notes
* Photos are uploaded to amazon s3. Photo naming scheme is {id}.jpg


text:
define(function() {
  var nativeConsole = {};
  try {
    // for IE 8/9
    if (!window.console) {
      window.console = {
        log:   function() {},
        debug: function() {},
        info:  function() {},
        warn:  function() {},
        error: function() {}
      };
    }
    nativeConsole = console;
  // Firefox throws an exception if you access the console object and it doesn't exist. Wow!
  } catch (e) { }
  return nativeConsole;
});