text:
package org.mifos.accounts.productdefinition.persistence;

import java.util.List;

import junit.framework.Assert;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mifos.accounts.productdefinition.business.ProductCategoryBO;
import org.mifos.accounts.productdefinition.business.ProductTypeEntity;
import org.mifos.accounts.productdefinition.util.helpers.ProductType;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.security.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("unchecked")
public class ProductCategoryPersistenceIntegrationTest extends MifosIntegrationTestCase {

    @Autowired
    private LegacyProductCategoryDao legacyProductCategoryDao;

    private UserContext userContext = null;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
        userContext = null;
    }

    @Test
    public void testGetMaxPrdCategoryId() throws Exception {
       Assert.assertEquals(Short.valueOf("2"), legacyProductCategoryDao.getMaxPrdCategoryId());
    }

    @Test
    public void testGetProductCategory() throws Exception {
       Assert.assertEquals(Integer.valueOf("0"), legacyProductCategoryDao.getProductCategory("product"));
    }

    @Test
    public void testGetProductTypes() throws Exception {
        List<ProductTypeEntity> productTypeList = legacyProductCategoryDao.getProductTypes();
       Assert.assertEquals(2, productTypeList.size());
        for (ProductTypeEntity productTypeEntity : productTypeList) {
            if (productTypeEntity.getType() == ProductType.LOAN) {
               Assert.assertEquals("Loan", productTypeEntity.getName());
            } else {
                //Assert.assertEquals("Margin Money",productTypeEntity.getName());
               Assert.assertEquals("Savings", productTypeEntity.getName());
            }
        }
    }

    @Test
    public void testGetProductTypesByType() throws Exception {
        ProductTypeEntity productTypeEntity = legacyProductCategoryDao.getProductTypes(ProductType.LOAN.getValue());
        Assert.assertNotNull(productTypeEntity);
        if (productTypeEntity.getType() == ProductType.LOAN) {
           Assert.assertEquals("Loan", productTypeEntity.getName());
        } else {
           Assert.assertEquals("", productTypeEntity.getName());
        }
    }

    @Test
    public void testGetPrdCategory() throws Exception {
       Assert.assertEquals(Integer.valueOf("0"), legacyProductCategoryDao.getProductCategory("product category",
                getProductCategory().get(0).getProductCategoryID()));
        ProductCategoryBO productCategoryBO = createProductCategory();
       Assert.assertEquals(Integer.valueOf("0"), legacyProductCategoryDao.getProductCategory("product category",
                getProductCategory().get(2).getProductCategoryID()));
       Assert.assertEquals(Integer.valueOf("1"), legacyProductCategoryDao.getProductCategory("product category",
                getProductCategory().get(1).getProductCategoryID()));
        deleteProductCategory(productCategoryBO);
    }

    @Test
    public void testFindByGlobalNum() throws Exception {
        ProductCategoryBO productCategoryBO = createProductCategory();
        Assert.assertNotNull(legacyProductCategoryDao.findByGlobalNum(productCategoryBO.getGlobalPrdCategoryNum()));
        deleteProductCategory(productCategoryBO);
    }

    @Test
    public void testGetProductCategoryStatusList() throws Exception {
       Assert.assertEquals(2, legacyProductCategoryDao.getProductCategoryStatusList().size());
    }

    @Test
    public void testGetAllCategories() throws Exception {
       Assert.assertEquals(2, legacyProductCategoryDao.getAllCategories().size());
        ProductCategoryBO productCategoryBO = createProductCategory();
       Assert.assertEquals(3, legacyProductCategoryDao.getAllCategories().size());
        deleteProductCategory(productCategoryBO);
    }

    private List<ProductCategoryBO> getProductCategory() {
        return StaticHibernateUtil.getSessionTL().createQuery(
                "from " + ProductCategoryBO.class.getName() + " pcb order by pcb.productCategoryID").list();
    }

    private void deleteProductCategory(ProductCategoryBO productCategoryBO) {
        Session session = StaticHibernateUtil.getSessionTL();
        Transaction transaction = StaticHibernateUtil.startTransaction();
        session.delete(productCategoryBO);
        session.flush();
    }

    private ProductCategoryBO createProductCategory() throws Exception {
        userContext = TestUtils.makeUser();
        ProductCategoryBO productCategoryBO = new ProductCategoryBO(userContext, legacyProductCategoryDao
                .getProductTypes().get(0), "product category", "created a category");
        productCategoryBO.save();
        StaticHibernateUtil.flushSession();
        return getProductCategory().get(2);
    }

}


text:
module Callbacks
  class WithStateArgMultiple

    include AASM

    aasm(:left) do
      state :open, :inital => true
      state :closed
      state :out_to_lunch

      event :close, :before => :before_method, :after => :after_method do
        transitions :to => :closed, :from => [:open], :after => :transition_method
        transitions :to => :out_to_lunch, :from => [:open], :after => :transition_method2
      end
    end

    def before_method(arg); end

    def after_method(arg); end

    def transition_method(arg); end

    def transition_method2(arg); end

  end
end

redpajama_set_name: RedPajamaGithub


text:
```
sudo apt-get update
sudo apt-get remove --auto-remove --purge libx11-.*
sudo apt-get install deborphan
deborphan -sz
sudo apt-get remove --purge $(deborphan)
sudo apt-get autoremove
```

Maybe I should make this a script? Would be simple enough.


text:
using System;
//Write a program that enters a number n and after that enters more n numbers and calculates and prints their sum. Note: You may need to use a for-loop.
class SumOfNNumbers
{
    static void Main()
    {
        Console.Title = "Problem 9. Sum of n Numbers";
        Console.Write("Enter a number n= ");
        double n = double.Parse(Console.ReadLine());
        double sum=0;
        for (int i = 1; i <= n; i++)
        {
            Console.Write("Enter a number #{0}: ",i);
            sum = sum + double.Parse(Console.ReadLine());
        }
        Console.WriteLine("Sum: {0}",sum);
    }
}


text:
class Fruit < ActiveRecord::Base
	validates  :tipo, :descripcion, :precio, :presence => true
end


text:
@interface WMGaugeViewStyleFlatThin ()

@property (nonatomic) CAShapeLayer *needleLayer;

@end

@implementation WMGaugeViewStyleFlatThin

- (void)drawNeedleOnLayer:(CALayer*)layer inRect:(CGRect)rect
{
    _needleLayer = [CAShapeLayer layer];
    UIBezierPath *needlePath = [UIBezierPath bezierPath];
    [needlePath moveToPoint:CGPointMake(FULLSCALE(kCenterX - kNeedleWidth, kCenterY))];
    [needlePath addLineToPoint:CGPointMake(FULLSCALE(kCenterX + kNeedleWidth, kCenterY))];
    [needlePath addLineToPoint:CGPointMake(FULLSCALE(kCenterX, kCenterY - kNeedleHeight))];
    [needlePath closePath];

    _needleLayer.path = needlePath.CGPath;
    _needleLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _needleLayer.fillColor = kNeedleColor;
    _needleLayer.strokeColor = kNeedleColor;
    _needleLayer.lineWidth = 1.2;

    // Needle shadow
    _needleLayer.shadowColor = [[UIColor blackColor] CGColor];
    _needleLayer.shadowOffset = CGSizeMake(-2.0, -2.0);
    _needleLayer.shadowOpacity = 0.2;
    _needleLayer.shadowRadius = 1.2;

    [layer addSublayer:_needleLayer];

    // Screw drawing
    CAShapeLayer *screwLayer = [CAShapeLayer layer];
    screwLayer.bounds = CGRectMake(FULLSCALE(kCenterX - kNeedleScrewRadius, kCenterY - kNeedleScrewRadius), FULLSCALE(kNeedleScrewRadius * 2.0, kNeedleScrewRadius * 2.0));
    screwLayer.position = CGPointMake(FULLSCALE(kCenterX, kCenterY));
    screwLayer.path = [UIBezierPath bezierPathWithOvalInRect:screwLayer.bounds].CGPath;
    screwLayer.fillColor = kNeedleScrewColor;

    // Screw shadow
    screwLayer.shadowColor = [[UIColor blackColor] CGColor];
    screwLayer.shadowOffset = CGSizeMake(0.0, 0.0);
    screwLayer.shadowOpacity = 0.2;
    screwLayer.shadowRadius = 2.0;

    [layer addSublayer:screwLayer];
}

- (void)drawFaceWithContext:(CGContextRef)context inRect:(CGRect)rect
{
#define EXTERNAL_RING_RADIUS    0.24
#define INTERNAL_RING_RADIUS    0.1

    // External circle
    CGContextAddEllipseInRect(context, CGRectMake(kCenterX - EXTERNAL_RING_RADIUS, kCenterY - EXTERNAL_RING_RADIUS, EXTERNAL_RING_RADIUS * 2.0, EXTERNAL_RING_RADIUS * 2.0));
    CGContextSetFillColorWithColor(context, CGRGB(255, 104, 97));
    CGContextFillPath(context);

    // Inner circle
    CGContextAddEllipseInRect(context, CGRectMake(kCenterX - INTERNAL_RING_RADIUS, kCenterY - INTERNAL_RING_RADIUS, INTERNAL_RING_RADIUS * 2.0, INTERNAL_RING_RADIUS * 2.0));
    CGContextSetFillColorWithColor(context, CGRGB(242, 99, 92));
    CGContextFillPath(context);
}

- (BOOL)needleLayer:(CALayer*)layer willMoveAnimated:(BOOL)animated duration:(NSTimeInterval)duration animation:(CAKeyframeAnimation*)animation
{
    layer.transform = [[animation.values objectAtIndex:0] CATransform3DValue];
    CGAffineTransform affineTransform1 = [layer affineTransform];
    layer.transform = [[animation.values objectAtIndex:1] CATransform3DValue];
    CGAffineTransform affineTransform2 = [layer affineTransform];
    layer.transform = [[animation.values lastObject] CATransform3DValue];
    CGAffineTransform affineTransform3 = [layer affineTransform];

    _needleLayer.shadowOffset = CGSizeApplyAffineTransform(CGSizeMake(-2.0, -2.0), affineTransform3);

    [layer addAnimation:animation forKey:kCATransition];

    CAKeyframeAnimation * animationShadowOffset = [CAKeyframeAnimation animationWithKeyPath:@"shadowOffset"];
    animationShadowOffset.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animationShadowOffset.removedOnCompletion = YES;
    animationShadowOffset.duration = animated ? duration : 0.0;
    animationShadowOffset.values = @[[NSValue valueWithCGSize:CGSizeApplyAffineTransform(CGSizeMake(-2.0, -2.0), affineTransform1)],
                                     [NSValue valueWithCGSize:CGSizeApplyAffineTransform(CGSizeMake(-2.0, -2.0), affineTransform2)],
                                     [NSValue valueWithCGSize:CGSizeApplyAffineTransform(CGSizeMake(-2.0, -2.0), affineTransform3)]];
    [_needleLayer addAnimation:animationShadowOffset forKey:kCATransition];

    return YES;
}

@end


text:
SYNONYM

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

#### Published in
Persoonia 9(4): 466 (1978)

#### Original name
Hydnum calcareum Cooke & Massee, 1892

### Remarks
null


text:
import Rebase from 're-base'
import Firebase from 'firebase'

const firebaseConfig = {
  apiKey: 'AIzaSyC0Zmyuet43K-pHBJhgIXfvHAKuoroZHP8',
  authDomain: 'thatconference-e515b.firebaseapp.com',
  databaseURL: 'https://thatconference-e515b.firebaseio.com'
}

const firebaseApp = Firebase.initializeApp(firebaseConfig)
const base = Rebase.createClass(firebaseApp.database())
export default base


text:
var AWS = require('aws-sdk');

var environment = process.env.ENVIRONMENT;
var region = process.env.AWS_REGION;

var accessKey = process.env.AWS_ACCESS_KEY_ID;
var secretKey = process.env.AWS_SECRET_ACCESS_KEY;

AWS.config.update({
  accessKeyId: accessKey,
  secretAccessKey: secretKey,
  region: region
});

var rds = new AWS.RDS();

rds.describeDBInstances({}, function(err, data) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  var exists = data && data.DBInstances.filter(function(item) {
    return item.DBInstanceIdentifier === 'chusrodriguez-' + environment + '-db'
  }).length > 0 ? 'true' : 'false';

  process.stdout.write(exists);

});


text:
layout: page
title: Alda Rocha
excerpt: "Fuck it Dude. Let's go bowling. [ UX Designer e WebDeveloper - @ShotCoffeeArt #GDGDrops #365cafes #5pordia Contato: mj.coffeeholick@gmail.com"
modified: 2015-01-05T22:35:00.000000-04:00
---

{{ page.excerpt }}

[@mjcofeeholick no Twitter](https://twitter.com/mjcoffeeholick)


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Zane.LogHub.Client
{
    public class MemoryStorage : IStorage
    {
        ConcurrentQueue<LogEntity> Logs = new ConcurrentQueue<LogEntity>();
        public override void Delete(IEnumerable<LogEntity> logs)
        {
            return;
        }

        public override void Delete(LogEntity log)
        {
            return;
        }

        public override LogEntity[] DequeueBatch(int maxCount = 100)
        {
            List<LogEntity> result = new List<LogEntity>();
            while (result.Count<maxCount&&Logs.Count>0)
            {
                LogEntity log = null;
                if (Logs.TryDequeue(out log)&&log!=null)
                {
                    result.Add(log);
                }
            }
            return result.ToArray();
        }

        public override LogEntity DequeueSingle()
        {
            LogEntity log = null;
            Logs.TryDequeue(out log);
            return log;
        }

        public override void Enqueue(LogEntity log)
        {
            Logs.Enqueue(log);
        }
    }
}


text:
require 'context-io/error'

module ContextIO
  # Raised when Context.IO returns a 5xx HTTP status code.
  #
  # @api public
  class Error::ServerError < ContextIO::Error
  end
end


text:
package engine.math.physics;

import org.lwjgl.util.vector.Vector2f;

import engine.math.Maths;
import engine.objects.Sprite;
import engine.objects.shapes.CollisionShape;

/**
 * This class handles collision calculations
 * @author Sharhar
 *
 */
public class Collider {

	/**
	 * This is a general function to check if any to shapes are colliding
	 * @param s1 shape 1
	 * @param s2 shape 2
	 * @return whether the shapes are colliding
	 */

	public static boolean spriteSpriteCol(Sprite sp1, Sprite sp2) {
		for(int i = 0; i < sp1.shapes.col.length;i++) {
			for(int j = 0;j < sp2.shapes.col.length;j++) {
				if(shapeShapeCol(sp1.shapes.col[i], sp2.shapes.col[j])) {
					return true;
				}
			}
		}

		return false;
	}

	public static boolean shapeShapeCol(CollisionShape s1, CollisionShape s2) {
		s1.updateCollisionStuff();
		s2.updateCollisionStuff();

		return boundingBoxCol(s1, s2);
		/*
		if(s1.shapeType.equals("Rect") && s2.shapeType.equals("Rect") && s1.r == 0 && s2.r == 0) {
			return rectRectCol(s1, s2);
		} else if(s1.shapeType.equals("Cir") && s2.shapeType.equals("Cir")) {
			return cirCirCol(s1, s2);
		} else if(s1.shapeType.equals("Cir") && s2.shapeType.equals("Rec") && s2.r == 0) {
			return rectCirCol(s2, s1);
		} else if(s1.shapeType.equals("Rec") && s2.shapeType.equals("Cir") && s1.r == 0) {
			return rectCirCol(s1, s2);
		}

		return polygonCol(s1, s2);
		*/
	}

	/**
	 * This function checks to see if a rectangle shape and a circle shape are colliding
	 * @param r rectangle shape
	 * @param c circle shape
	 * @return whether they are colliding
	 */
	public static boolean rectCirCol(CollisionShape r, CollisionShape c) {
		Vector2f close = Maths.getPointClosestToInRect(r, c.pos);

		float d = Maths.distance(close, c.pos);

		return d <= c.r;
	}

	/**
	 * This function checks if two circle shapes are colliding
	 * @param s1 shape 1
	 * @param s2 shape 2
	 * @return whether they are colliding
	 */
	public static boolean cirCirCol(CollisionShape s1, CollisionShape s2) {
		float d = Maths.distance(s1.pos, s2.pos);
		float r = s1.r + s2.r;

		return d <= r;
	}

	/**
	 * This function checks if two rectangle shapes are colliding
	 * @param sh1 shape 1
	 * @param sh2 shape 2
	 * @return whether they are colliding
	 */
	public static boolean boundingBoxCol(CollisionShape sh1, CollisionShape sh2) {
		Vector2f p1 = new Vector2f(sh1.pos.x - sh1.boundingBox.x/2, sh1.pos.y - sh1.boundingBox.y/2);
		Vector2f p2 = new Vector2f(sh2.pos.x - sh2.boundingBox.x/2, sh2.pos.y - sh2.boundingBox.y/2);
		Vector2f s1 = sh1.boundingBox;
		Vector2f s2 = sh2.boundingBox;

		if(p1.x + s1.x< p2.x || p2.x + s2.x < p1.x) {
			return false;
		}

		if(p1.y + s1.y < p2.y || p2.y + s2.y < p1.y) {
			return false;
		}

		return true;
	}

	public static boolean rectRectCol(CollisionShape sh1, CollisionShape sh2) {
		Vector2f p1 = sh1.pos;
		Vector2f p2 = sh2.pos;
		Vector2f s1 = sh1.other[0];
		Vector2f s2 = sh2.other[0];

		if(p1.x + s1.x< p2.x || p2.x + s2.x < p1.x) {
			return false;
		}

		if(p1.y + s1.y < p2.y || p2.y + s2.y < p1.y) {
			return false;
		}

		return true;
	}

	/**
	 * This function checks if two polygons are colliding
	 * @param s1 shape 1
	 * @param s2 shape 2
	 * @return whether they are colliding
	 */
	public static boolean polygonCol(CollisionShape s1, CollisionShape s2) {
		CollisionShape[] shapes = new CollisionShape[2];
		shapes[0] = s1;
		shapes[1] = s2;

		for (CollisionShape s : shapes) {
			for (int i1 = 0; i1 < s.colVert.length; i1++) {
				int i2 = (i1 + 1) % s.colVert.length;
				Vector2f p1 = s.colVert[i1];
				Vector2f p2 = s.colVert[i2];

				Vector2f normal = new Vector2f(p2.y - p1.y, p1.x - p2.x);

				float minA = Float.MAX_VALUE;
				float maxA = Float.MIN_VALUE;

				for (Vector2f v : s1.colVert) {
					float projected = normal.x * v.x + normal.y * v.y;
					if (projected < minA)
						minA = projected;
					if (projected > maxA)
						maxA = projected;
				}

				float minB = Float.MAX_VALUE;
				float maxB = Float.MIN_VALUE;

				for (Vector2f v : s2.colVert) {
					float projected = normal.x * v.x + normal.y * v.y;
					if (projected < minB)
						minB = projected;
					if (projected > maxB)
						maxB = projected;
				}

				if (maxA < minB || maxB < minA) {
					return false;
				}
			}
		}

		return true;
	}
}


text:
package org.openengsb.domain.example.model;

import org.openengsb.core.api.Constants;
import org.openengsb.core.api.model.annotation.Model;
import org.openengsb.core.api.model.annotation.OpenEngSBForeignKey;
import org.openengsb.core.api.model.annotation.OpenEngSBModelId;
import org.openengsb.labs.delegation.service.Provide;

@Provide(context = { Constants.DELEGATION_CONTEXT_MODELS })
@Model
public class EOModel {
    @OpenEngSBModelId
    private String edbId;
    @OpenEngSBForeignKey(modelType = SourceModelA.class, modelVersion = "3.0.0.SNAPSHOT")
    private String refModelA;
    @OpenEngSBForeignKey(modelType = SourceModelB.class, modelVersion = "3.0.0.SNAPSHOT")
    private String refModelB;
    private String nameA;
    private String nameB;
    private String shared;

    public EOModel() {
    }

    public EOModel(String edbId, String refModelA, String refModelB, String shared) {
        this.edbId = edbId;
        this.refModelA = refModelA;
        this.refModelB = refModelB;
        this.shared = shared;
    }

    public String getEdbId() {
        return edbId;
    }

    public void setEdbId(String edbId) {
        this.edbId = edbId;
    }

    public String getRefModelA() {
        return refModelA;
    }

    public void setRefModelA(String refModelA) {
        this.refModelA = refModelA;
    }

    public String getRefModelB() {
        return refModelB;
    }

    public void setRefModelB(String refModelB) {
        this.refModelB = refModelB;
    }

    public String getNameA() {
        return nameA;
    }

    public void setNameA(String nameA) {
        this.nameA = nameA;
    }

    public String getNameB() {
        return nameB;
    }

    public void setNameB(String nameB) {
        this.nameB = nameB;
    }

    public String getShared() {
        return shared;
    }

    public void setShared(String shared) {
        this.shared = shared;
    }
}


text:
package org.cqframework.cql.cql2elm.model;

import org.antlr.v4.runtime.misc.NotNull;
import org.cqframework.cql.elm.tracking.*;
import org.hl7.elm_modelinfo.r1.ConversionInfo;
import org.hl7.elm_modelinfo.r1.ModelInfo;

import java.util.*;

public class Model {
    public Model(@NotNull ModelInfo modelInfo, Model systemModel) throws ClassNotFoundException {
        info = modelInfo;
        index = new HashMap<>();
        nameIndex = new HashMap<>();
        classIndex = new HashMap<>();
        conversions = new ArrayList<>();

        ModelImporter importer = new ModelImporter(info, systemModel != null ? systemModel.nameIndex.values() : null);
        index = importer.getTypes();
        for (Conversion c : importer.getConversions()) {
            conversions.add(c);
        }

        for (DataType t : index.values()) {
            if (t instanceof ClassType) {
                classIndex.put(((ClassType)t).getLabel(), (ClassType)t);
            }

            if (t instanceof NamedType) {
                nameIndex.put(((NamedType)t).getSimpleName(), t);
            }
        }
    }

    private ModelInfo info;
    public ModelInfo getModelInfo() { return info; }

    private Map<String, DataType> index;
    private Map<String, ClassType> classIndex;
    private Map<String, DataType> nameIndex;
    private List<Conversion> conversions;

    public Iterable<Conversion> getConversions() {
        return conversions;
    }

    public DataType resolveTypeName(@NotNull String typeName) {
        DataType result = index.get(typeName);
        if (result == null) {
            result = nameIndex.get(typeName);
        }

        return result;
    }

    public ClassType resolveLabel(@NotNull String label) {
        return classIndex.get(label);
    }

    private DataType internalResolveTypeName(@NotNull String typeName, Model systemModel) {
        DataType result = resolveTypeName(typeName);
        if (result == null) {
            result = systemModel.resolveTypeName(typeName);
            if (result == null) {
                throw new IllegalArgumentException(String.format("Could not resolve type name %s in model %s.",
                        typeName, info.getName()));
            }
        }

        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.Runtime;

namespace Amazon.StorageGateway.Model
{
    /// <summary>
    /// Returns information about the  ListGatewaysResult response and response metadata.
    /// </summary>
    public class ListGatewaysResponse : AmazonWebServiceResponse
    {
        private ListGatewaysResult listGatewaysResult;

        /// <summary>
        /// Gets and sets the ListGatewaysResult property.
        /// A JSON object containing the following fields: ListGatewaysOutput$Gateways ListGatewaysOutput$Marker
        /// </summary>
        public ListGatewaysResult ListGatewaysResult
        {
            get
            {
                if(this.listGatewaysResult == null)
                {
                    this.listGatewaysResult = new ListGatewaysResult();
                }

                return this.listGatewaysResult;
            }
            set { this.listGatewaysResult = value; }
        }
    }
}


text:
namespace RapidVulkan
{
  //! This object is movable so it can be thought of as behaving in the same was as a unique_ptr and is compatible with std containers
  class RenderPass
  {
    VkDevice m_device{VK_NULL_HANDLE};
    VkRenderPass m_renderPass{VK_NULL_HANDLE};

  public:
    RenderPass(const RenderPass&) = delete;
    RenderPass& operator=(const RenderPass&) = delete;

    //! @brief Move assignment operator
    RenderPass& operator=(RenderPass&& other) noexcept
    {
      if (this != &other)
      {
        // Free existing resources then transfer the content of other to this one and fill other with default values
        if (IsValid())
        {
          Reset();
        }

        // Claim ownership here
        m_device = other.m_device;
        m_renderPass = other.m_renderPass;

        // Remove the data from other
        other.m_device = VK_NULL_HANDLE;
        other.m_renderPass = VK_NULL_HANDLE;
      }
      return *this;
    }

    //! @brief Move constructor
    //! Transfer ownership from other to this
    RenderPass(RenderPass&& other) noexcept
      : m_device(other.m_device)
      , m_renderPass(other.m_renderPass)
    {
      // Remove the data from other
      other.m_device = VK_NULL_HANDLE;
      other.m_renderPass = VK_NULL_HANDLE;
    }

    //! @brief Create a 'invalid' instance (use Reset to populate it)
    RenderPass()

        = default;

    //! @brief Assume control of the RenderPass (this object becomes responsible for releasing it)
    explicit RenderPass(const ClaimMode claimMode, const VkDevice device, const VkRenderPass renderPass)
      : RenderPass()
    {
      Reset(claimMode, device, renderPass);
    }

    //! @brief Create the requested resource
    //! @note  Function: vkCreateRenderPass
    RenderPass(const VkDevice device, const VkRenderPassCreateInfo& createInfo)
      : RenderPass()
    {
      Reset(device, createInfo);
    }

#ifndef RAPIDVULKAN_DISABLE_UNROLLED_STRUCT_METHODS
    //! @brief Create the requested resource
    //! @note  Function: vkCreateRenderPass
    RenderPass(const VkDevice device, const VkRenderPassCreateFlags flags, const uint32_t attachmentCount, VkAttachmentDescription*const pAttachments, const uint32_t subpassCount, VkSubpassDescription*const pSubpasses, const uint32_t dependencyCount, VkSubpassDependency*const pDependencies)
      : RenderPass()
    {
      Reset(device, flags, attachmentCount, pAttachments, subpassCount, pSubpasses, dependencyCount, pDependencies);
    }
#endif

    ~RenderPass()
    {
      Reset();
    }

    //! @brief returns the managed handle and releases the ownership.
    RAPIDVULKAN_FUNC_WARN_UNUSED_RESULT VkRenderPass Release()
    {
      const auto resource = m_renderPass;
      m_device = VK_NULL_HANDLE;
      m_renderPass = VK_NULL_HANDLE;
      return resource;
    }

    //! @brief Destroys any owned resources and resets the object to its default state.
    void Reset() noexcept
    {
      if (! IsValid())
      {
        return;
      }

      assert(m_device != VK_NULL_HANDLE);
      assert(m_renderPass != VK_NULL_HANDLE);

      vkDestroyRenderPass(m_device, m_renderPass, nullptr);
      m_device = VK_NULL_HANDLE;
      m_renderPass = VK_NULL_HANDLE;
    }

    //! @brief Destroys any owned resources and assume control of the RenderPass (this object becomes responsible for releasing it)
    void Reset(const ClaimMode claimMode, const VkDevice device, const VkRenderPass renderPass)
    {
      if (IsValid())
      {
        Reset();
      }

      m_device = device;
      m_renderPass = renderPass;
    }

    //! @brief Destroys any owned resources and then creates the requested one
    //! @note  Function: vkCreateRenderPass
    void Reset(const VkDevice device, const VkRenderPassCreateInfo& createInfo)
    {
#ifndef RAPIDVULKAN_DISABLE_PARAM_VALIDATION
      if (device == VK_NULL_HANDLE)
      {
        throw std::invalid_argument("device can not be VK_NULL_HANDLE");
      }
#else
      assert(device != VK_NULL_HANDLE);
#endif

      // Free any currently allocated resource
      if (IsValid())
      {
        Reset();
      }

      // Since we want to ensure that the resource is left untouched on error we use a local variable as a intermediary
      VkRenderPass renderPass;
      CheckError(vkCreateRenderPass(device, &createInfo, nullptr, &renderPass), "vkCreateRenderPass", __FILE__, __LINE__);

      // Everything is ready, so assign the members
      m_device = device;
      m_renderPass = renderPass;
    }

#ifndef RAPIDVULKAN_DISABLE_UNROLLED_STRUCT_METHODS
    //! @brief Destroys any owned resources and then creates the requested one
    //! @note  Function: vkCreateRenderPass
    void Reset(const VkDevice device, const VkRenderPassCreateFlags flags, const uint32_t attachmentCount, VkAttachmentDescription*const pAttachments, const uint32_t subpassCount, VkSubpassDescription*const pSubpasses, const uint32_t dependencyCount, VkSubpassDependency*const pDependencies)
    {
      VkRenderPassCreateInfo createInfo{};
      createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
      createInfo.pNext = nullptr;
      createInfo.flags = flags;
      createInfo.attachmentCount = attachmentCount;
      createInfo.pAttachments = pAttachments;
      createInfo.subpassCount = subpassCount;
      createInfo.pSubpasses = pSubpasses;
      createInfo.dependencyCount = dependencyCount;
      createInfo.pDependencies = pDependencies;

      Reset(device, createInfo);
    }
#endif

    //! @brief Get the associated 'Device'
    VkDevice GetDevice() const
    {
      return m_device;
    }

    //! @brief Get the associated resource handle
    VkRenderPass Get() const
    {
      return m_renderPass;
    }

    //! @brief Get a pointer to the associated resource handle
    const VkRenderPass* GetPointer() const
    {
      return &m_renderPass;
    }

    //! @brief Check if this object contains a valid resource
    inline bool IsValid() const
    {
      return m_renderPass != VK_NULL_HANDLE;
    }

    //! @note  Function: vkGetRenderAreaGranularity
    void GetRenderAreaGranularity(VkExtent2D * pGranularity)
    {
      vkGetRenderAreaGranularity(m_device, m_renderPass, pGranularity);
    }

#if VK_HEADER_VERSION >= 189
    //! @note  Function: vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI
    void GetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI(VkExtent2D * pMaxWorkgroupSize)
    {
      CheckError(vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI(m_device, m_renderPass, pMaxWorkgroupSize), "vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI", __FILE__, __LINE__);
    }
#endif
  };
}

#endif


text:
package foo

type StringerVar string

func (myx StringerVar) String() string {
	return string(myx)
}

type Stringer interface {
	String() string
}

type SomeInterface interface {
	FunctionA(StringerVar)
	FunctionB(Stringer) string
}

type SomeVar struct{}

func (i SomeVar) FunctionA(a StringerVar) {
	i.FunctionB(a)
}

func (i SomeVar) FunctionB(a Stringer) string {
	return a.String()
}


text:
[DscLocalConfigurationManager()]
Configuration MetaConfig
{
    Settings
    {
        ConfigurationModeFrequencyMins  = 45
        RebootNodeIfNeeded              = $true
        ConfigurationMode               = 'ApplyAndAutoCorrect'
        ActionAfterReboot               = 'ContinueConfiguration'
        RefreshMode                     = 'Push'
    }
}

MetaConfig -OutputPath c:\Configs\Mof\Nano -nodes localhost -Verbose

Set-DscLocalConfigurationManager -Path c:\Configs\Mof\Nano -Verbose


text:
DROP TABLE IF EXISTS `community_closed_log`;

CREATE TABLE `community_closed_log` (
  `id_community_closed_log` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `day` date DEFAULT NULL,
  `type` enum('all_restaurants','close_3rd_party_delivery_restaurants','auto_closed','closed_with_driver') DEFAULT NULL,
  `hours_closed` float DEFAULT NULL,
  `id_community` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id_community_closed_log`),
  UNIQUE KEY `community_closed_log_day_community` (`day`,`id_community`,`type`),
  KEY `id_community` (`id_community`),
  CONSTRAINT `community_closed_log_ibfk_1` FOREIGN KEY (`id_community`) REFERENCES `community` (`id_community`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
layout: icon
title: Fast food
categories: commercial
icon-24: fast-food-24.png
icon-18: fast-food-18.png
icon-12: fast-food-12.png
tags:
  - food
  - fast
  - commercial
  - burger
  - drive-through
---


text:
<?xml version="1.0" encoding="utf-8"?>

<info><title>HTML E-Mail</title></info>

    <para>
        To send an e-mail in <acronym>HTML</acronym> format, set the body using the method
        <methodname>setBodyHTML()</methodname> instead of <methodname>setBodyText()</methodname>.
        The <acronym>MIME</acronym> content type will automatically be set to
        <property>text/html</property> then. If you use both <acronym>HTML</acronym> and Text
        bodies, a multipart/alternative <acronym>MIME</acronym> message will automatically be
        generated:
    </para>

    <example xml:id="zend.mail.html-mails.example-1"><info><title>Sending HTML E-Mail</title></info>

        <programlisting language="php"><![CDATA[
$mail = new Zend_Mail();
$mail->setBodyText('My Nice Test Text');
$mail->setBodyHtml('My Nice Test Text');
$mail->setFrom('somebody@example.com', 'Some Sender');
$mail->addTo('somebody_else@example.com', 'Some Recipient');
$mail->setSubject('TestSubject');
$mail->send();
]]></programlisting>
    </example>


text:
#ifndef MUGGLE_C_BENCHMARK_HANDLE_H_
#define MUGGLE_C_BENCHMARK_HANDLE_H_

#include "muggle_benchmark_macro.h"
#include "muggle_benchmark/muggle_benchmark_config.h"

EXTERN_C_BEGIN

/**
 * @brief benchmark record
 */
typedef struct muggle_benchmark_record
{
	uint64_t idx;    //!< record index
	uint64_t action; //!< record action
	union {
		struct timespec ts;  //!< elapsed time with timespec
		uint64_t cpu_cycles; //!< elapsed time with cpu cycle
	};
} muggle_benchmark_record_t;

/**
 * @brief callback function for record
 *
 * @param record  benchmark record
 */
typedef void (*fn_muggle_benchmark_record)(muggle_benchmark_record_t *record);

/**
 * @brief benchmark handle
 */
typedef struct muggle_benchmark_handle
{
	uint64_t                   record_count;     //!< total number of record
	int                        action_count;     //!< total action count
	char                       **action_name;    //!< action name map
	muggle_benchmark_record_t  **action_records; //!< action to records array map
} muggle_benchmark_handle_t;

/**
 * @brief initialize benchmark handle
 *
 * @param handle        benchmark handle
 * @param record_count  total number of record
 * @param action_count  total action count
 *
 * @return
 *   0 - success
 *   otherwise - failed
 */
MUGGLE_BENCHMARK_EXPORT
int muggle_benchmark_handle_init(
	muggle_benchmark_handle_t *handle,
	uint64_t record_count,
	int action_count);

/**
 * @brief destroy benchmark handle)
 *
 * @param handle  benchmark handle
 */
MUGGLE_BENCHMARK_EXPORT
void muggle_benchmark_handle_destroy(muggle_benchmark_handle_t *handle);

/**
 * @brief set action name and allocate records space
 *
 * @param handle  benchmark handle
 * @param action      action id
 * @param action_name action name
 *
 * @return
 *   0 - seccess
 *   otherwise - failed
 */
MUGGLE_BENCHMARK_EXPORT
int muggle_benchmark_handle_set_action(muggle_benchmark_handle_t *handle, int action, const char *action_name);

/**
 * @brief get record count
 *
 * @param handle  benchmark handle
 * @return record count
 */
MUGGLE_BENCHMARK_EXPORT
uint64_t muggle_benchmark_handle_get_record_count(muggle_benchmark_handle_t *handle);

/**
 * @brief get action name
 *
 * @param handle  benchmark handle
 * @param action  action id
 *
 * @return action name
 */
MUGGLE_BENCHMARK_EXPORT
const char* muggle_benchmark_handle_get_action_name(muggle_benchmark_handle_t *handle, int action);

/**
 * @brief get records by action id
 *
 * @param handle  benchmark handle
 * @param action  action id
 *
 * @return records
 */
MUGGLE_BENCHMARK_EXPORT
muggle_benchmark_record_t* muggle_benchmark_handle_get_records(muggle_benchmark_handle_t *handle, int action);

/**
 * @brief generate records report
 *
 * @param handle       benchmark handle
 * @param fp           output file handle
 * @param elapsed_unit elapsed time unit
 */
MUGGLE_BENCHMARK_EXPORT
void muggle_benchmark_handle_gen_records_report(
	muggle_benchmark_handle_t *handle,
	FILE *fp,
	int elapsed_unit);

/**
 * @brief generate latency benchmark report head
 *
 * @param fp      output file handle
 * @param config  benchmark config
 */
MUGGLE_BENCHMARK_EXPORT
void muggle_benchmark_gen_latency_report_head(FILE *fp, struct muggle_benchmark_config *config);

/**
 * @brief generate latency benchmark report body
 *
 * @param fp            output file handle
 * @param handle        benchmark handle
 * @param config        benchmark config
 * @param action1       action id1
 * @param action2       action id2
 * @param sort_result   whether need to sort result
 */
MUGGLE_BENCHMARK_EXPORT
void muggle_benchmark_gen_latency_report_body(
	FILE *fp,
	muggle_benchmark_handle_t *handle,
	struct muggle_benchmark_config *config,
	int action1,
	int action2,
	bool sort_result);

/**
 * @brief get record function
 *
 * @param elapsed_unit elapsed unit
 *
 * @return record function
 */
MUGGLE_BENCHMARK_EXPORT
fn_muggle_benchmark_record muggle_benchmark_get_fn_record(int elapsed_unit);

EXTERN_C_END

#endif // !MUGGLE_C_BENCHMARK_HANDLE_H_


text:
package com.linkedin.kafka.cruisecontrol.metricsreporter.metric;

import com.linkedin.kafka.cruisecontrol.metricsreporter.CruiseControlMetricsReporter;
import java.nio.ByteBuffer;

/**
 * An interface for all the raw metrics reported by {@link CruiseControlMetricsReporter}.
 */
public abstract class CruiseControlMetric {
  static final byte METRIC_VERSION = 0;
  private final RawMetricType _rawMetricType;
  private final long _time;
  private final int _brokerId;
  private final double _value;

  public CruiseControlMetric(RawMetricType rawMetricType, long time, int brokerId, double value) {
    _rawMetricType = rawMetricType;
    _time = time;
    _brokerId = brokerId;
    _value = value;
  }

  /**
   * Get the metric class id for this metric. The metric class id will be stored in the serialized metrics
   * so that the deserializer will know which class should be used to deserialize the data.
   */
  public abstract MetricClassId metricClassId();

  /**
   * Get the {@link RawMetricType} of this metric.
   */
  public RawMetricType rawMetricType() {
    return _rawMetricType;
  }

  /**
   * Get the timestamp for this metric.
   */
  public long time() {
    return _time;
  }

  /**
   * Get the broker id who reported this metric.
   */
  public int brokerId() {
    return _brokerId;
  }

  /**
   * Get the metric value.
   */
  public double value() {
    return _value;
  }

  /**
   * Serialize the metric to a byte buffer with the header size reserved.
   * @param headerSize the header size to reserve.
   * @return A ByteBuffer with header size reserved at the beginning.
   */
  abstract ByteBuffer toBuffer(int headerSize);

  /**
   * An enum that list all the implementations of the interface. This id will be store in the serialized
   * metrics to help the metric sampler to decide using which class to deserialize the metric bytes.
   */
  public enum MetricClassId {
    BROKER_METRIC((byte) 0), TOPIC_METRIC((byte) 1), PARTITION_METRIC((byte) 2);

    private final byte _id;

    MetricClassId(byte id) {
      _id = id;
    }

    byte id() {
      return _id;
    }

    static MetricClassId forId(byte id) {
      if (id < values().length) {
        return values()[id];
      } else {
        throw new IllegalArgumentException("MetricClassId " + id + " does not exist.");
      }
    }
  }
}


text:
  Grostenquin est
       un village
       localisé dans le département de Moselle en Lorraine. Elle totalisait 543 habitants en 2008.

À proximité de Grostenquin sont localisées les communes de
Bérig-Vintrange à 3 km, 229 habitants,
Léning à 5 km, 268 habitants,
Vallerange localisée à 5 km, 204 habitants,
Freybouse à 3 km, 377 habitants,
Erstroff située à 2 km, 187 habitants,
Neufvillage à 5 km, 40 habitants,
 entre autres. De plus, Grostenquin est située à seulement 25 km de Forbach.

À Grostenquin, le prix moyen à l'achat d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 390 € du m². À la location la valeur moyenne se situe à 6,8 € du m² par mois.

Le nombre de logements, à Grostenquin, était réparti en 2011 en 53 appartements et 235 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de venir habiter à Grostenquin, vous pourrez facilement trouver une maison à acheter.

La commune compte quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport et une boucle de randonnée.


text:
<?php namespace App;

use Illuminate\Auth\UserTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Contracts\Auth\User as UserContract;
use Illuminate\Contracts\Auth\Remindable as RemindableContract;

class User extends Model implements UserContract, RemindableContract {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];

}


text:
import { TestBed, inject } from '@angular/core/testing';

import { FireService } from './fire.service';

describe('FireService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [FireService]
    });
  });

  it('should ...', inject([FireService], (service: FireService) => {
    expect(service).toBeTruthy();
  }));
});


text:
using System;
using System.Runtime.Serialization;
using System.Collections.Generic;

namespace Epi.Cloud.Common.Criteria
{
    /// <summary>
    /// Holds criteria for SurveyInfo queries.
    /// </summary>
    [DataContract(Namespace = "http://www.yourcompany.com/types/")]
    public class SurveyInfoCriteria : Criteria
    {
        public SurveyInfoCriteria()
        {
            this.SurveyIdList = new List<string>();
            this.ClosingDate = DateTime.MinValue;
            this.SurveyType = -1;
        }

        /// <summary>
        /// Organization Key for Manager Service
        /// </summary>
        [DataMember]
        public Guid OrganizationKey { get; set; }

        /// <summary>
        /// Contains the User Id of logged in User.
        /// </summary>
        [DataMember]
        public int UserId { get; set; }

        /// <summary>
        /// Which page to retrieve
        /// </summary>
        [DataMember]
        public int PageNumber { get; set; }

        /// <summary>
        /// Number of Records per page
        /// </summary>
        [DataMember]
        public int PageSize { get; set; }

        /// <summary>
        /// Number of Records per page
        /// </summary>
        [DataMember]
        public bool ReturnSizeInfoOnly { get; set; }

        /// <summary>
        /// Unique SurveyInfo identifier.
        /// </summary>
        [DataMember]
        public List<string> SurveyIdList { get; set; }

        /// <summary>
        /// Last Day survey can be completed
        /// </summary>
        [DataMember]
        public DateTime ClosingDate { get; set; }

        /// <summary>
        /// Survey Type
        /// </summary>
        [DataMember]
        public int SurveyType { get; set; }

        /// <summary>
        /// User Publish Key for Manager Service
        /// </summary>
        [DataMember]
        public Guid UserPublishKey { get; set; }

        /// <summary>
        /// Flag as to whether to include order statistics.
        /// </summary>
        [DataMember]
        public bool IncludeOrderStatistics { get; set; }

        [DataMember]
        public bool IsDraftMode { get; set; }

        [DataMember]
        public DateTime StartDate { get; set; }

    }
}


text:
layout: post
date:	2006-11-07 15:21:00
title:  Crested Lark in Camouflage
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
....

Just to give non-birders an idea of how tough it can be to spot birds. Normally I do not post large-size pictures, but this time I will.

Can you spot the Crested Lark in the picture?

Awesome camouflage, isn't it!!

If you couldn't spot it...look along the line of the "vee"shaped bit of dry grass at the bottom of the picture, and you will see the bird.....

That's the kind of thing that raptors face they scan the ground from far above, looking for prey....builds a healthy respect for their abilities when you think about it!


text:
<?php

use Illuminate\Database\Seeder;

class MembersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $numberOfGroups = config('seeder.groups');
        $usersPerGroup = config('seeder.users_per_group');

        for ($i = 0; $i < $usersPerGroup; $i++) {
            $groupId = $i + 1;
            for ($j = 0; $j < $numberOfGroups; $j++) {
                $userId = $numberOfGroups*$i + $j + 1;
                factory(App\Member::class)->create(['user_id' => $userId, 'group_id' => $groupId]);
            }
        }
    }
}


text:
class Database
{
public:
    Database();
    bool Connect();
};

#endif // DATABASE_H


text:
<?xml version="1.0"?>
<project name="example-project" xmlns="http://nant.sf.net/release/0.85/nant.xsd">

	<property name="current.directory" value="${directory::get-current-directory()}" />
	<property name="project.directory" value="${directory::get-parent-directory(current.directory)}" />
	<property name="release.directory" value="${directory::get-parent-directory(project.directory)}\example-project-release" />

	<property name="tools.directory" value="${project.directory}\tools" />
	<property name="combiner" value="${tools.directory}\Rivet\Rivet.Console.exe" />

	<property name="project.version.major" value="1" />
	<property name="project.version.minor" value="0" />
	<property name="project.version.revision" value="${datetime::get-year(datetime::now())}-${datetime::get-month(datetime::now())}-${datetime::get-day(datetime::now())}" />
	<property name="project.version" value="${project.version.major}.${project.version.minor}-${project.version.revision}" />

	<target
		name="release"
		depends="exampleproject-build" />
		/>

	<target name="exampleproject-build">
		<delete dir="${release.directory}" />

		<!-- copy release files for example project -->
		<copy todir="${release.directory}">
			<fileset basedir="${project.directory}">
				<include name="/*.*"/>
				<include name="test/**"/>
				<include name="example/**"/>
			</fileset>
		</copy>
		<!--
		<copy todir="${project.directory}\release\example-project-release">
			<fileset>
				<include name="${project.directory}\example\*.bat"/>
				<include name="${project.directory}\lib\js.jar"/>
			</fileset>
		</copy>-->
		<exec
			program="${combiner}"
			commandline="${release.directory} -v:PRJ_VERSION=${project.version.major}.${project.version.minor}"
			workingdir="${release.directory}" />

	</target>

</project>


text:
require_relative 'spec_helper'
require_relative '../test/person'
require 'mongobzar/repository/repository'
require 'mongobzar/assembler/simple_assembler'
require 'mongobzar/assembler/entity_assembler'

module Mongobzar module Test
  class AddressWithId
    attr_accessor :id, :street

    def initialize(street)
      @street = street
    end
  end

  class PersonHavingAddressesWithIdAssembler < Assembler::Assembler
    def initialize(address_assembler)
      @address_assembler = address_assembler
    end

    def build_new(dto)
      Person.new
    end

    def build_domain_object!(person, dto)
      address_assembler.build_domain_objects(dto['addresses']).each do |address|
        person.add_address(address)
      end
      person.work_address = address_assembler.build_domain_object(
        dto['work_address']
      )
    end

    def build_dto!(dto, person)
      dto['addresses'] = person.addresses.map do |address|
        address_dto = address_assembler.build_dto(address)
        address.id = address_dto['_id']
        address_dto
      end
      if person.work_address
        dto['work_address'] = address_assembler.build_dto(person.work_address)
        person.work_address.id = dto['work_address']['_id']
      end
    end

    private
      attr_reader :address_assembler
  end

  class AddressWithIdAssembler < Assembler::Assembler
    def build_new(dto)
      AddressWithId.new(dto['street'])
    end

    def build_dto!(dto, address)
      dto['street'] = address.street
    end
  end

  class AddressWithIdentityMappingMatcher < EmbeddedMappingMatcher
    def find_one_document
      collection.find.to_a[0]['work_address']
    end

    def find_many_documents
      collection.find.to_a[0]['addresses']
    end

    def assert_single_loaded(specification, address)
      address.should_not be_nil
      address.id.should_not be_nil
      specification.id.should == address.id
      specification.street.should == address.street
    end

    def assert_correct_dto(address, dto)
      dto.should_not be_nil
      dto['_id'].should_not be_nil
      address.id.should == dto['_id']
      address.street.should == dto['street']
    end

    def assert_correct_dtos_collection(addresses, dtos)
      addresses.size.should == dtos.size
      addresses.each_with_index do |address, i|
        assert_correct_dto(address, dtos[i])
      end
    end
  end
end end

module Mongobzar module Test
describe 'Embedded association with identity' do
  let(:people_collection) { @db.collection('people_having_addresses_with_id') }
  let(:person_repository) do
    res = Repository::Repository.new('testing', 'people_having_addresses_with_id')
    res.assembler = Assembler::EntityAssembler.new(PersonHavingAddressesWithIdAssembler.new(Assembler::EntityAssembler.new(AddressWithIdAssembler.new)))
    res
  end
  let(:person) { Person.new }
  let(:matcher) { AddressWithIdentityMappingMatcher.new(people_collection) }

  before do
    setup_connection
    person_repository.clear_everything!
  end

  describe 'one' do
    let(:work_address) { AddressWithId.new('Work street') }

    describe 'insert' do
      it 'puts embedded document to the parent document' do
        person.work_address = work_address
        person_repository.insert(person)
        matcher.assert_single_persisted(work_address)
      end
    end

    describe 'update' do
      it 'updates embedded document preserving id' do
        person.work_address = work_address
        person_repository.insert(person)
        work_address_original_id = work_address.id

        work_address.street = 'New street'
        person_repository.update(person)
        matcher.assert_single_persisted_with_given_id(work_address, work_address_original_id)
      end
    end

    describe 'find' do
      it 'returns domain object with related domain object' do
        person.work_address = work_address
        person_repository.insert(person)
        matcher.assert_single_loaded(
          work_address,
          person_repository.find(person.id).work_address
        )
      end
    end
  end

  describe 'many' do
    let(:address) { AddressWithId.new('street') }
    let(:address2) { AddressWithId.new('street2') }
    let(:address3) { AddressWithId.new('street3') }
    let(:address4) { AddressWithId.new('street4') }

    describe 'insert' do
      it 'puts embedded documents to the parent document' do
        person.add_address(address)
        person.add_address(address2)
        person_repository.insert(person)
        matcher.assert_persisted([address, address2])
      end
    end

    describe 'update' do
      describe 'updates embedded documents' do
        describe 'creates new' do
          it 'works if was empty' do
            person_repository.insert(person)
            person.add_address(address)
            person.add_address(address2)
            person_repository.update(person)
            matcher.assert_persisted([address, address2])
          end

          it 'works if was not empty, preserving ids' do
            person.add_address(address)
            person_repository.insert(person)
            address_original_id = address.id

            person.add_address(address2)
            person_repository.update(person)

            matcher.assert_persisted([address, address2])
            matcher.assert_the_same_id(address, address_original_id)
          end
        end

        it 'deletes removed' do
          [address, address2, address3, address4].each do |address|
            person.add_address(address)
          end
          person_repository.insert(person)
          person.remove_address(address)
          person.remove_address(address3)
          person_repository.update(person)

          matcher.assert_persisted([address2, address4])
        end

        it 'updates existing, preserving ids' do
          person.add_address(address)
          person_repository.insert(person)
          original_id = address.id

          address.street = 'new_street'
          person_repository.update(person)

          matcher.assert_persisted([address])
          matcher.assert_the_same_id(address, original_id)
        end
      end
    end

    describe 'find' do
      it 'returns domain object with related domain objects' do
        person.add_address(address)
        person.add_address(address2)
        person_repository.insert(person)

        matcher.assert_loaded([address, address2], person_repository.find(person.id).addresses)
      end
    end
  end
end
end end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using zSprite;

namespace GameName1.Space
{
    public class ParallaxLayer2 : SpriteQuadTree
    {
        private Settings _settings;
        private float _speed = 0.9f;

        public GameObject layer;

        private void init()
        {
            _settings = rootObject.getScript<Settings>();
        }

        private void loadsector(int sectorid)
        {
            createLayer();
            spawnPlanet(123, Vector2.Zero, 1f, 3);
        }

        private void createLayer()
        {
            layer = rootObject.createChild("parallaxLayer2");
        }

        protected void spawnPlanet(int seed, Vector2 location, float tightness, int moons)
        {
            var random = new Random(seed);

            var root = Root.instance;
            var parallaxGO = layer;
            var planetSpace = parallaxGO.createChild("planetspace");
            planetSpace.transform.Position = location;

            var parallaxScript2 = layer.createScript<ParallaxScroller>();
            parallaxScript2.speed = 0.85f;

            var planetGO = planetSpace.createChild("planet");
            {
                var id = random.Next(0, 82) + 1;
                var sprite = planetGO.createScript<Sprite>();
                sprite.material = root.resources.createMaterialFromTexture("content/textures/planets/planet (" + id + ").png");
                sprite.material.SetSamplerState(SamplerState.LinearClamp);
                sprite.renderQueue = Game.LAYER_PARALLAX2;
                //sprite.material.transparency = new Color(1, 1, 1);
                sprite.size = new Vector2(400, 400);
            }

            {
                var sprite = planetGO.createScript<Sprite>();
                sprite.material = Root.instance.resources.createMaterialFromTexture("content/textures/flare/tunel.png");
                sprite.material.SetBlendState(BlendState.Additive);
                sprite.material.SetSamplerState(SamplerState.LinearClamp);
                sprite.color = new Color(0.4f, 0.2f, 0.1f);
                sprite.renderQueue = Game.LAYER_PARALLAX2;
                //sprite.color = new Color(
                sprite.size = new Vector2(400, 400);
            }

            for (var i = 0; i < moons; i++)
            {
                var rotation = random.Next(-MathHelper.Pi, MathHelper.Pi);
                var dir = new Vector2(Utility.Cos(rotation), Utility.Sin(rotation));
                var distance = random.Next(400, 750);
                var moonGO = planetSpace.createChild("moon" + i);

                var sprite = moonGO.createScript<Sprite>();
                sprite.material = root.resources.createMaterialFromTexture("content/textures/moon chunks/moon (" + random.Next(1, 13) + ").png");
                sprite.material.SetSamplerState(SamplerState.LinearClamp);
                sprite.renderQueue = Game.LAYER_PARALLAX2;
                //sprite.material.transparency = new Color(1, 1, 1);
                sprite.size = new Vector2(100, 100);
                moonGO.transform.Scale = Vector2.One * random.Next(0.75f, 1.25f);
                moonGO.transform.Orientation = random.Next(-MathHelper.Pi, MathHelper.Pi);
                moonGO.transform.Position = dir * distance * tightness;
            }
        }

        private void genMoon(float x, float y)
        {

        }

        private void unloadsector(int sectorid)
        {
            if (layer != null)
                layer.destroy();
        }
    }
}


text:
var JOURNAL = [
  {"events":["carrot","exercise","weekend"],"squirrel":false},
  {"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false},
  {"events":["carrot","nachos","brushed teeth","cycling","weekend"],"squirrel":false},
  {"events":["brussel sprouts","ice cream","brushed teeth","computer","weekend"],"squirrel":false},
  {"events":["potatoes","candy","brushed teeth","exercise","weekend","dentist"],"squirrel":false},
  {"events":["brussel sprouts","pudding","brushed teeth","running","weekend"],"squirrel":false},
  {"events":["pizza","brushed teeth","computer","work","touched tree"],"squirrel":false},
  {"events":["bread","beer","brushed teeth","cycling","work"],"squirrel":false},
  {"events":["cauliflower","brushed teeth","work"],"squirrel":false},
  {"events":["pizza","brushed teeth","cycling","work"],"squirrel":false},
  {"events":["lasagna","nachos","brushed teeth","work"],"squirrel":false},
  {"events":["brushed teeth","weekend","touched tree"],"squirrel":false},
  {"events":["lettuce","brushed teeth","television","weekend"],"squirrel":false},
  {"events":["spaghetti","brushed teeth","work"],"squirrel":false},
  {"events":["brushed teeth","computer","work"],"squirrel":false},
  {"events":["lettuce","nachos","brushed teeth","work"],"squirrel":false},
  {"events":["carrot","brushed teeth","running","work"],"squirrel":false},
  {"events":["brushed teeth","work"],"squirrel":false},
  {"events":["cauliflower","reading","weekend"],"squirrel":false},
  {"events":["bread","brushed teeth","weekend"],"squirrel":false},
  {"events":["lasagna","brushed teeth","exercise","work"],"squirrel":false},
  {"events":["spaghetti","brushed teeth","reading","work"],"squirrel":false},
  {"events":["carrot","ice cream","brushed teeth","television","work"],"squirrel":false},
  {"events":["spaghetti","nachos","work"],"squirrel":false},
  {"events":["cauliflower","ice cream","brushed teeth","cycling","work"],"squirrel":false},
  {"events":["spaghetti","peanuts","computer","weekend"],"squirrel":true},
  {"events":["potatoes","ice cream","brushed teeth","computer","weekend"],"squirrel":false},
  {"events":["potatoes","ice cream","brushed teeth","work"],"squirrel":false},
  {"events":["peanuts","brushed teeth","running","work"],"squirrel":false},
  {"events":["potatoes","exercise","work"],"squirrel":false},
  {"events":["pizza","ice cream","computer","work"],"squirrel":false},
  {"events":["lasagna","ice cream","work"],"squirrel":false},
  {"events":["cauliflower","candy","reading","weekend"],"squirrel":false},
  {"events":["lasagna","nachos","brushed teeth","running","weekend"],"squirrel":false},
  {"events":["potatoes","brushed teeth","work"],"squirrel":false},
  {"events":["carrot","work"],"squirrel":false},
  {"events":["pizza","beer","work","dentist"],"squirrel":false},
  {"events":["lasagna","pudding","cycling","work"],"squirrel":false},
  {"events":["spaghetti","brushed teeth","reading","work"],"squirrel":false},
  {"events":["spaghetti","pudding","television","weekend"],"squirrel":false},
  {"events":["bread","brushed teeth","exercise","weekend"],"squirrel":false},
  {"events":["lasagna","peanuts","work"],"squirrel":true},
  {"events":["pizza","work"],"squirrel":false},
  {"events":["potatoes","exercise","work"],"squirrel":false},
  {"events":["brushed teeth","exercise","work"],"squirrel":false},
  {"events":["spaghetti","brushed teeth","television","work"],"squirrel":false},
  {"events":["pizza","cycling","weekend"],"squirrel":false},
  {"events":["carrot","brushed teeth","weekend"],"squirrel":false},
  {"events":["carrot","beer","brushed teeth","work"],"squirrel":false},
  {"events":["pizza","peanuts","candy","work"],"squirrel":true},
  {"events":["carrot","peanuts","brushed teeth","reading","work"],"squirrel":false},
  {"events":["potatoes","peanuts","brushed teeth","work"],"squirrel":false},
  {"events":["carrot","nachos","brushed teeth","exercise","work"],"squirrel":false},
  {"events":["pizza","peanuts","brushed teeth","television","weekend"],"squirrel":false},
  {"events":["lasagna","brushed teeth","cycling","weekend"],"squirrel":false},
  {"events":["cauliflower","peanuts","brushed teeth","computer","work","touched tree"],"squirrel":false},
  {"events":["lettuce","brushed teeth","television","work"],"squirrel":false},
  {"events":["potatoes","brushed teeth","computer","work"],"squirrel":false},
  {"events":["bread","candy","work"],"squirrel":false},
  {"events":["potatoes","nachos","work"],"squirrel":false},
  {"events":["carrot","pudding","brushed teeth","weekend"],"squirrel":false},
  {"events":["carrot","brushed teeth","exercise","weekend","touched tree"],"squirrel":false},
  {"events":["brussel sprouts","running","work"],"squirrel":false},
  {"events":["brushed teeth","work"],"squirrel":false},
  {"events":["lettuce","brushed teeth","running","work"],"squirrel":false},
  {"events":["candy","brushed teeth","work"],"squirrel":false},
  {"events":["brussel sprouts","brushed teeth","computer","work"],"squirrel":false},
  {"events":["bread","brushed teeth","weekend"],"squirrel":false},
  {"events":["cauliflower","brushed teeth","weekend"],"squirrel":false},
  {"events":["spaghetti","candy","television","work","touched tree"],"squirrel":false},
  {"events":["carrot","pudding","brushed teeth","work"],"squirrel":false},
  {"events":["lettuce","brushed teeth","work"],"squirrel":false},
  {"events":["carrot","ice cream","brushed teeth","cycling","work"],"squirrel":false},
  {"events":["pizza","brushed teeth","work"],"squirrel":false},
  {"events":["spaghetti","peanuts","exercise","weekend"],"squirrel":true},
  {"events":["bread","beer","computer","weekend","touched tree"],"squirrel":false},
  {"events":["brushed teeth","running","work"],"squirrel":false},
  {"events":["lettuce","peanuts","brushed teeth","work","touched tree"],"squirrel":false},
  {"events":["lasagna","brushed teeth","television","work"],"squirrel":false},
  {"events":["cauliflower","brushed teeth","running","work"],"squirrel":false},
  {"events":["carrot","brushed teeth","running","work"],"squirrel":false},
  {"events":["carrot","reading","weekend"],"squirrel":false},
  {"events":["carrot","peanuts","reading","weekend"],"squirrel":true},
  {"events":["potatoes","brushed teeth","running","work"],"squirrel":false},
  {"events":["lasagna","ice cream","work","touched tree"],"squirrel":false},
  {"events":["cauliflower","peanuts","brushed teeth","cycling","work"],"squirrel":false},
  {"events":["pizza","brushed teeth","running","work"],"squirrel":false},
  {"events":["lettuce","brushed teeth","work"],"squirrel":false},
  {"events":["bread","brushed teeth","television","weekend"],"squirrel":false},
  {"events":["cauliflower","peanuts","brushed teeth","weekend"],"squirrel":false}
];

// This makes sure the data is exported in node.js —
// `require('./path/to/04_data.js')` will get you the array.
if (typeof module != "undefined" && module.exports)
  module.exports = JOURNAL;

var journal = [];

function addEntry(events, didITurnIntoASquirrel) {
  journal.push({
    events: events,
    squirrel: didITurnIntoASquirrel
  });
}

/*

addEntry(["work", "touched tree", "pizza", "running",
          "television"], false);
addEntry(["work", "ice cream", "cauliflower", "lasagna",
          "touched tree", "brushed teeth"], false);
addEntry(["weekend", "cycling", "break", "peanuts",
          "beer"], true);

*/

function phi(table) {
  return (table[3] * table[0] - table[2] * table[1]) /
    Math.sqrt((table[2] + table[3]) *
              (table[0] + table[1]) *
              (table[1] + table[3]) *
              (table[0] + table[2]));
}
// console.log(phi([76, 9, 4, 1]));
// → 0.068599434

// extract a table here
function hasEvent(event, entry) {
  return entry.events.indexOf(event) != -1;
}

function tableFor(event, journal) {
  var table = [0, 0, 0, 0];
  for (var i = 0; i < journal.length; i++) {
    var entry = journal[i], index = 0;
    if (hasEvent(event, entry)) index += 1;
    if (entry.squirrel) index += 2;
    table[index] += 1;
  }
  return table;
}

// console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]

function gatherCorrelations(journal) {
  var phis = {};
  for (var entry = 0; entry < journal.length; entry++) {
    var events = journal[entry].events;
    for (var i = 0; i < events.length; i++) {
      var event = events[i];
      if (!(event in phis))
        phis[event] = phi(tableFor(event, journal));
    }
  }
  return phis;
}

var correlations = gatherCorrelations(JOURNAL);

for (var event in correlations)
  console.log(event + ": " + correlations[event]);
// → carrot:   0.0140970969
// → exercise: 0.0685994341
// → weekend:  0.1371988681
// → bread:   -0.0757554019
// → pudding: -0.0648203724
// and so on...

for (var event in correlations) {
  var correlation = correlations[event];
  if (correlation > 0.1 || correlation < -0.1)
    console.log(event + ": " + correlation);
}
// → weekend:        0.1371988681
// → brushed teeth: -0.3805211953
// → candy:          0.1296407447
// → work:          -0.1371988681
// → spaghetti:      0.2425356250
// → reading:        0.1106828054
// → peanuts:        0.5902679812

for (var i = 0; i < JOURNAL.length; i++) {
  var entry = JOURNAL[i];
  if (hasEvent("peanuts", entry) &&
     !hasEvent("brushed teeth", entry))
    entry.events.push("peanut teeth");
}

console.log(phi(tableFor("peanut teeth", JOURNAL)));
// → 1

// maps
var map = {};
function storePhi(event, phi) {
  map[event] = phi;
}

storePhi("pizza", 0.069);
storePhi("touched tree", -0.081);
console.log("pizza" in map);
// → true
console.log(map["touched tree"]);
// → -0.081


text:
package de.bund.bva.isyfact.sicherheit.common.konstanten;

/**
 * Diese Klasse enthält alle die Fehler für alle Schlüssel der Komponente Sicherheit.
 *
 */
public abstract class SicherheitFehlerSchluessel {

    /** Der übergebene Parameter "{0}" ist null oder leer. */
    public static final String MSG_PARAMETER_FEHLT = "SIC1000";

    /** Ein Wert für die Initialisierung ist null oder leer (String). */
    public static final String MSG_INITIALISIERUNGS_ELEMENT_FEHLT = "SIC1001";

    // Konfigurationsfehler

    /** Innerhalb eines Berechtigungsmanager wird das Rollenrechtemapping benötigt, fehlt aber. */
    public static final String MSG_AUTORISIERUNG_ROLLENRECHTEMAPPING_FEHLT = "SIC2000";

    /** Fehler beim Parsen der Datei zum RollenRechteMapping: (String). */
    public static final String MSG_AUTORISIERUNG_ROLLENRECHTEMAPPING_FEHLERHAFT = "SIC2001";

    /** Tag wurde fehlerhaft konfiguriert. */
    public static final String MSG_TAG_KONFIGURATION_FEHLERHAFT = "SIC2002";

    /** Ein durch die Anwendung überprüftes Recht war im Rollenrechtemapping nicht definiert. */
    public static final String MSG_AUTORISIERUNG_RECHT_UNDEFINIERT = "SIC2003";

    /** Die Annotaton {0} fehlt an der Methode {1}. */
    public static final String MSG_ANNOTATION_FEHLT_AN_METHODE = "SIC2004";

    // Fehler bei der Autorisierung

    /** Der Berechtigungsmanager konnte nicht erzeugt werden. */
    public static final String MSG_BERECHTIGUNGSMANAGER_NICHT_VERFUEGBAR = "SIC2050";

    /** Das erforderliche Recht fehlt. */
    public static final String MSG_AUTORISIERUNG_FEHLGESCHLAGEN = "SIC2051";

    /** Der Berechtigungsmanager konnte den AufrufKontext nicht lesen. */
    public static final String MSG_AUFRUFKONTEXT_NICHT_VERFUEGBAR = "SIC2052";

    /** Die Autorisierung ist mit einem technischen Fehler gescheitert. */
    public static final String MSG_AUTORISIERUNG_TECHNISCH_FEHLGESCHLAGEN = "SIC2053";

    // Fehler bei Authentifizierung über den Access-Manager.
    /** Authentifizierung des Benutzers über Access Manager fehlgeschlagen. */
    public static final String MSG_AUTHENTIFIZIERUNG_FEHLGESCHLAGEN = "SIC4000";

    /** Zugriff auf den Access-Manager fehlgeschlagen. */
    public static final String MSG_ZUGRIFF_ACCESSMANAGER_FEHLGESCHLAGEN = "SIC4001";

    // Fehler bei Abruf und Auswertung der Sessioninformationen, die zu einer Session-Id vom Access-Manager
    // abgerufen wurden

}


text:
package name.chengchao.mylinuxtest.cpu;

/**
 * 指定cpu的使用率(单核版本)<br>
 * 原理:指定一个固定的时间单元,比如说是100ms,如果要跑30%的cpu,就需要跑30ms,休息70ms
 *
 * @author charles
 */
public class CpuUtil_Single {

    public static final int TIME_UNIT_MS = 100;

    public static double    tmp;

    public static void main(String[] args) throws Exception {
        // default is 30%
        int cpuUtil = 30;
        if (args.length != 0) {
            cpuUtil = Integer.valueOf(args[0]);
        }
        if (cpuUtil < 5 || cpuUtil > 80) {
            throw new IllegalArgumentException("cpuUtil must be between 5 and 80");
        }
        int runTime = TIME_UNIT_MS * cpuUtil / 100;
        int sleepTime = TIME_UNIT_MS - runTime;
        System.out.println("runTime(ms):" + runTime + ",sleepTime(ms):" + sleepTime);
        while (true) {
            eatCpuTime(runTime);
            Thread.sleep(sleepTime);
        }
    }

    public static void eatCpuTime(long useTimeMs) {
        long start = System.nanoTime();
        long useTimeNano = useTimeMs * 1000000;
        while (true) {
            // eat cpu
            for (int i = 0; i < 10000; i++) {
                tmp = Math.sqrt(i) * Math.sqrt(i);
            }

            if ((System.nanoTime() - start) >= useTimeNano) {
                break;
            }

        }
    }

}


text:
@implementation SocializeThirdPartyFacebook

+ (BOOL)available {
    NSString *facebookAppId = [self facebookAppId];
    if (facebookAppId == nil) {
        return NO;
    }

    if (![self canOpenFacebookURL]) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            NSLog(SOCIALIZE_FACEBOOK_CANNOT_OPEN_URL_MESSAGE);
        });
    }

    return YES;
}

+ (BOOL)canOpenFacebookURL {
    NSString *facebookAppId = [self facebookAppId];
    NSString *facebookLocalAppId = [self facebookLocalAppId];

    NSURL *testURL = [NSURL URLWithString:[self baseUrlForAppId:facebookAppId localAppId:facebookLocalAppId]];
    if (![[UIApplication sharedApplication] canOpenURL:testURL]) {
        return NO;
    }

    return YES;
}

+ (NSString *)baseUrlForAppId:(NSString*)appId localAppId:(NSString*)localAppId {
    return [NSString stringWithFormat:@"fb%@%@://authorize",
            appId,
            localAppId ? localAppId : @""];
}

+ (NSString*)facebookAppId {
    return [[NSUserDefaults standardUserDefaults] valueForKey:kSocializeFacebookAuthAppId];
}

+ (NSString*)facebookLocalAppId {
    return [[NSUserDefaults standardUserDefaults] valueForKey:kSocializeFacebookAuthLocalAppId];
}

+ (void)storeLocalCredentialsWithAccessToken:(NSString*)accessToken
                              expirationDate:(NSDate*)expirationDate {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:accessToken forKey:kSocializeFacebookAuthAccessToken];
    [defaults setObject:expirationDate forKey:kSocializeFacebookAuthExpirationDate];

    [defaults synchronize];
}

+ (NSString*)facebookUrlSchemeSuffix {
    return [self facebookLocalAppId];
}

+ (NSString*)facebookAccessToken {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kSocializeFacebookAuthAccessToken];
}

+ (NSDate*)facebookExpirationDate {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kSocializeFacebookAuthExpirationDate];
}

+ (NSString*)socializeAuthToken {
    return [self facebookAccessToken];
}

+ (NSString*)socializeAuthTokenSecret {
    return nil;
}

+ (SocializeThirdPartyAuthType)socializeAuthType {
    return SocializeThirdPartyAuthTypeFacebook;
}

+ (NSError*)thirdPartyUnavailableError {
    return [NSError defaultSocializeErrorForCode:SocializeErrorFacebookUnavailable];
}

+ (NSError*)userAbortedAuthError {
    return [NSError defaultSocializeErrorForCode:SocializeErrorFacebookCancelledByUser];
}

+ (NSString*)thirdPartyName {
    return @"Facebook";
}

+ (BOOL)isLinkedToSocialize {
    return [self available] && [self hasLocalCredentials] && [[Socialize sharedSocialize] isAuthenticatedWithAuthType:kSocializeFacebookStringForAPI];
}

+ (BOOL)hasLocalCredentials {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [defaults objectForKey:kSocializeFacebookAuthAccessToken] != nil &&
    [[defaults objectForKey:kSocializeFacebookAuthExpirationDate] timeIntervalSinceNow] > 0;
}

+ (void)removeFacebookCookies {
    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray* facebookCookies = [cookies cookiesForURL:
                                [NSURL URLWithString:@"http://login.facebook.com"]];

    for (NSHTTPCookie* cookie in facebookCookies) {
        [cookies deleteCookie:cookie];
    }
}

+ (void)removeLocalCredentials {
    [self removeFacebookCookies];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:kSocializeFacebookAuthAccessToken];
    [defaults removeObjectForKey:kSocializeFacebookAuthExpirationDate];
}

+ (Facebook*)createFacebookClient {
    NSAssert([self available], @"Tried to create facebook instance when facebook not available");
    NSAssert([self hasLocalCredentials], @"Tried to create facebook instance without local credentials");

    Facebook *facebook = [[[Facebook alloc] initWithAppId:[self facebookAppId] urlSchemeSuffix:[self facebookLocalAppId] andDelegate:nil] autorelease];
    facebook.accessToken = [self facebookAccessToken];
    facebook.expirationDate = [self facebookExpirationDate];

    return facebook;

}

+ (NSString*)dontPostKey {
    return kSocializeDontPostToFacebookKey;
}

+ (SZSocialNetwork)socialNetworkFlag {
    return SZSocialNetworkFacebook;
}

+ (BOOL)userPrefersPost {
    BOOL dontPost = [[[NSUserDefaults standardUserDefaults] objectForKey:[self dontPostKey]] boolValue];
    return !dontPost;
}

+ (BOOL)shouldAutopost {
    BOOL linked = [self isLinkedToSocialize];
    BOOL userPrefersPost = [self userPrefersPost];
    BOOL autopost = [[[NSUserDefaults standardUserDefaults] objectForKey:kSocializeAutoPostToSocialNetworksKey] boolValue];
    return linked && autopost && userPrefersPost;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Maui.Trading.Model;
using Maui.Entities;

namespace Maui.Trading.Binding
{
    public interface IEnumerableDataSource<T> : IDataSource
    {
        IEnumerable<T> ForStock( StockHandle stock );
    }
}


text:
package org.jmxtrans.agent.util.io;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.w3c.dom.Document;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

/**
 * @author Cyrille Le Clerc
 */
public class IoUtilsTest {

    @Rule
    public TemporaryFolder tmp = new TemporaryFolder();

    private String createFileUrl(String filePath) {
        // On windows machines we must replace backslashes with forward slashes and add a preceding slash.
        String res = filePath.replace('\\', '/');
        if (!res.startsWith("/")) {
            res = "/" + res;
        }
        return "file://" + res;
    }

    @Test
    public void getFileAsDocumentFromFile() throws Exception {
        Path xmlFile = tmp.newFile("b.xml").toPath();

        Files.write(xmlFile, "<parent></parent>".getBytes(StandardCharsets.UTF_8));

        String filePath = xmlFile.toString();

        System.out.println(filePath);
        Document document = IoUtils.getFileAsDocument(new FileResource(xmlFile.toFile()));
        System.out.println(document.getDocumentElement());
        assertThat(document, notNullValue());
    }

    @Test
    public void getFileAsDocumentFromClasspath() throws Exception {
        Document document = IoUtils.getFileAsDocument(new ClasspathResource("classpath:org/jmxtrans/agent/util/io/a.xml"));
        assertThat(document, notNullValue());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--L
   Copyright SAIC and Ellumen

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
L-->
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:oauth="http://www.springframework.org/schema/security/oauth"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
              http://www.springframework.org/schema/security/oauth http://www.springframework.org/schema/security/spring-security-oauth-1.0.xsd">

  <http auto-config='true' access-denied-page="/login.jsp">
    <intercept-url pattern="/services/v1/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/services/v2/**" access="ROLE_USER" />
    <intercept-url pattern="/services/v3/**" access="ROLE_USER" />
    <intercept-url pattern="/oauth/**" access="ROLE_USER" />
    <intercept-url pattern="/request_token_authorized.jsp" access="ROLE_USER" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

    <form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp" login-processing-url="/login.do"/>
    <logout logout-success-url="/index.jsp" logout-url="/logout.do"/>
  </http>

  <!--  authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="nbia_guest" password="changeme" authorities="ROLE_USER" />
        <user name="marissa" password="marissakoala" authorities="ROLE_USER" />
        <user name="paul" password="emu" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager-->

  <beans:bean id="csmAuthenticationProvider" class="gov.nih.nci.nbia.restSecurity.CsmAuthenticationProvider">
  </beans:bean>

  <authentication-manager>
    <authentication-provider ref="csmAuthenticationProvider">
    </authentication-provider>
  </authentication-manager>

  <oauth:provider consumer-details-service-ref="consumerDetails"
                  token-services-ref="tokenServices"
                  request-token-url="/oauth/request_token"
                  authenticate-token-url="/oauth/authorize"
                  user-approval-url="/oauth/confirm_access"
                  access-granted-url="/request_token_authorized.jsp"
                  access-token-url="/oauth/access_token"
                  require10a="false"/>

  <oauth:consumer-details-service id="consumerDetails">
    <oauth:consumer name="Tonr.com" key="tonr-consumer-key" secret="SHHHHH!!!!!!!!!!" resourceName="DICOM Image Resource" resourceDescription="Access DICOM Images and related info in imaging.nci.nih.gov."/>
  </oauth:consumer-details-service>

  <oauth:token-services id="tokenServices"/>

</beans:beans>


text:
<?php

namespace Aurora\Helper;

use ArrayAccess;

class Object implements ArrayAccess
{
    private $strict = false;

    use ObjectTrait,
        ArrayTrait,
        CallablePropertyTrait;
}


text:
/**
 * @file   AddTaskForwardQA.C
 * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
 * @date   Wed Mar 23 12:14:03 2011
 *
 * @brief  Include the Forward QA task in a train.
 *
 * @ingroup pwglf_forward_scripts_tasks
 */
/**
 * @defgroup pwglf_forward_qa Quality Assurance
 *
 * Code to deal with Quality Assurance
 *
 * @ingroup pwglf_forward_topical
 */
/**
 * This is the macro to include the Forward QA task in a train.
 *
 * @param mc       Monte-carlo input
 * @param useCent  Use centrality
 *
 * @return newly constructured task object
 *
 * @ingroup pwglf_forward_eloss
 */
 AliForwardQATask*
AddTaskForwardQA(Bool_t mc=false, Bool_t useCent=false)
{
  // --- Load libraries ----------------------------------------------
  gROOT->LoadClass("AliAODForwardMult", "libPWGLFforward2");

  // --- Make the task and add it to the manager ---------------------
  AliForwardQATask* task = new AliForwardQATask("forwardQA");

  // --- Cuts --------------------------------------------------------
  // Note, the absolute lowest signal to consider - ever -
  // irrespective of MC or real data, is 0.15.  Signals below this
  // will contain remenants of the pedestal (yes, the width of the
  // pedestal is small, but there are many _many_ channels with only
  // pedestal value in them, so the absolute number of high-value
  // pedestal signals is large - despite the low probablity).
  AliFMDMultCuts cSharingLow(AliFMDMultCuts::kFixed,0.15);
  AliFMDMultCuts cSharingHigh(AliFMDMultCuts::kLandauSigmaWidth,1);
  AliFMDMultCuts cDensity(AliFMDMultCuts::kLandauSigmaWidth,1);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Disable use of code from 1st Physics
  task->GetEventInspector().SetUseFirstPhysicsVtx(kFALSE);

  // --- Set parameters on energy loss fitter ------------------------
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(15);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(500);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set whether to do fit the energy distributions
  task->GetEnergyFitter().SetDoFits(kTRUE);
  // Set whether to make the correction object
  task->GetEnergyFitter().SetDoMakeObject(kFALSE);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.45);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetFitRangeBinWidth(4);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(10000);
  // Set reqularization cut
  task->GetEnergyFitter().SetRegularizationCut(1e8);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNParticles(4);

  // --- Sharing filter ----------------------------------------------
  // Enable use of angle corrected signals in the algorithm
  task->GetSharingFilter().SetUseAngleCorrectedSignals(true);
  // Disable use of angle corrected signals in the algorithm
  task->GetSharingFilter().SetZeroSharedHitsBelowThreshold(false);
  // Enable use of angle corrected signals in the algorithm
  task->GetSharingFilter().SetHCuts(cSharingHigh);
  // Lower cuts from object
  task->GetSharingFilter().SetLCuts(cSharingLow);
  // Whether to use simple merging algorithm
  task->GetSharingFilter().SetUseSimpleSharing(true);
  // Whether to allow for 3 strip hits - deprecated
  task->GetSharingFilter().SetAllow3Strips(false);

  // --- Density calculator ------------------------------------------
  // Least acceptable quality of ELoss fits
  task->GetDensityCalculator()
    .SetMinQuality(AliFMDCorrELossFit::kDefaultQuality);
  // Set the maximum number of particle to try to reconstruct
  task->GetDensityCalculator().SetMaxParticles(3);
  // Wet whether to use poisson statistics to estimate N_ch
  task->GetDensityCalculator().SetUsePoisson(true);
  // How to lump for Poisson calculator - 64 strips, 4 regions
  task->GetDensityCalculator().SetLumping(32,4);
  // Set whether or not to include sigma in cut
  task->GetDensityCalculator().SetCuts(cDensity);
  // Set the maximum ratio of outlier bins to the total number of bins
  // task->GetDensityCalculator().SetMaxOutliers(.10);
  task->GetDensityCalculator().SetMaxOutliers(1.0);//Disable filter
  // Set whether or not to use the phi acceptance
  //   AliFMDDensityCalculator::kPhiNoCorrect
  //   AliFMDDensityCalculator::kPhiCorrectNch
  //   AliFMDDensityCalculator::kPhiCorrectELoss
  task->GetDensityCalculator()
    .SetUsePhiAcceptance(AliFMDDensityCalculator::kPhiCorrectNch);

  // --- Set limits on fits the energy -------------------------------
  // Maximum relative error on parameters
  // AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12;
  // Least weight to use
  // AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5;
  // Maximum value of reduced chi^2
  // AliFMDCorrELossFit::ELossFit::fgMaxChi2nu   = 20;

  // --- Debug -------------------------------------------------------
  // Set the overall debug level (1: some output, 3: a lot of output)
  task->SetDebug(1);

  // --- Make the output container and connect it --------------------
  task->Connect(AliAnalysisManager::GetCommonFileName(), "trending.root");

  return task;
}
//
// EOF
//


text:
package org.jruby.internal.runtime.methods;

import org.jruby.Ruby;
import org.jruby.RubyModule;
import org.jruby.ast.ArgsNode;
import org.jruby.ast.Node;
import org.jruby.compiler.ASTInspector;
import org.jruby.exceptions.JumpException;
import org.jruby.internal.runtime.JumpTarget;
import org.jruby.lexer.yacc.ISourcePosition;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;

/**
 *
 */
public class InterpretedMethod extends DynamicMethod implements JumpTarget, MethodArgs {
    private StaticScope staticScope;
    private Node body;
    private ArgsNode argsNode;
    private ISourcePosition position;
    private boolean noArgHack;
    private boolean needsScope;

    public InterpretedMethod(RubyModule implementationClass, StaticScope staticScope, Node body,
            ArgsNode argsNode, Visibility visibility, ISourcePosition position) {
        super(implementationClass, visibility, CallConfiguration.FrameFullScopeFull);
        this.body = body;
        this.staticScope = staticScope;
        this.argsNode = argsNode;
        this.position = position;

        ASTInspector inspector = new ASTInspector();
        inspector.inspect(body);
        inspector.inspect(argsNode);

        if (inspector.hasClosure() || inspector.hasScopeAwareMethods() || staticScope.getNumberOfVariables() != 0) {
            // must have scope
            needsScope = true;
        } else {
            needsScope = false;
        }

        assert argsNode != null;
    }

    public Node getBodyNode() {
        return body;
    }

    public ArgsNode getArgsNode() {
        return argsNode;
    }

    public StaticScope getStaticScope() {
        return staticScope;
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
        assert args != null;

        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, block, runtime);
            argsNode.checkArgCount(runtime, args.length);
            argsNode.prepare(context, runtime, self, args, block);

            return body.interpret(runtime, context, self, block);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) {
        return call(context, self, clazz, name, args, Block.NULL_BLOCK);
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, Block.NULL_BLOCK, runtime);
            argsNode.checkArgCount(runtime, 0);
            argsNode.prepare(context, runtime, self, Block.NULL_BLOCK);

            return body.interpret(runtime, context, self, Block.NULL_BLOCK);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, Block block) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, block, runtime);
            argsNode.checkArgCount(runtime, 0);
            argsNode.prepare(context, runtime, self, block);

            return body.interpret(runtime, context, self, block);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, Block.NULL_BLOCK, runtime);
            argsNode.checkArgCount(runtime, 1);
            argsNode.prepare(context, runtime, self, arg0, Block.NULL_BLOCK);

            return body.interpret(runtime, context, self, Block.NULL_BLOCK);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, Block block) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, block, runtime);
            argsNode.checkArgCount(runtime, 1);
            argsNode.prepare(context, runtime, self, arg0, block);

            return body.interpret(runtime, context, self, block);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, Block.NULL_BLOCK, runtime);
            argsNode.checkArgCount(runtime, 2);
            argsNode.prepare(context, runtime, self, arg0, arg1, Block.NULL_BLOCK);

            return body.interpret(runtime, context, self, Block.NULL_BLOCK);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, block, runtime);
            argsNode.checkArgCount(runtime, 2);
            argsNode.prepare(context, runtime, self, arg0, arg1, block);

            return body.interpret(runtime, context, self, block);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, Block.NULL_BLOCK, runtime);
            argsNode.checkArgCount(runtime, 3);
            argsNode.prepare(context, runtime, self, arg0, arg1, arg2, Block.NULL_BLOCK);

            return body.interpret(runtime, context, self, Block.NULL_BLOCK);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    @Override
    public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
        Ruby runtime = context.getRuntime();

        try {
            pre(context, name, self, block, runtime);
            argsNode.checkArgCount(runtime, 3);

            if (!noArgHack) argsNode.prepare(context, runtime, self, arg0, arg1, arg2, block);

            return body.interpret(runtime, context, self, block);
        } catch (JumpException.ReturnJump rj) {
            return handleReturn(context, rj);
        } catch (JumpException.RedoJump rj) {
            return handleRedo(runtime);
        } finally {
            post(runtime, context, name);
        }
    }

    protected void pre(ThreadContext context, String name, IRubyObject self, Block block, Ruby runtime) {
        if (needsScope) {
            context.preMethodFrameAndScope(getImplementationClass(), name, self, block, staticScope);
        } else {
            context.preMethodFrameAndDummyScope(getImplementationClass(), name, self, block, staticScope);
        }
    }

    protected void post(Ruby runtime, ThreadContext context, String name) {
        context.postMethodFrameAndScope();
    }

    public ISourcePosition getPosition() {
        return position;
    }

    @Override
    public Arity getArity() {
        return argsNode.getArity();
    }

    public DynamicMethod dup() {
        return new InterpretedMethod(getImplementationClass(), staticScope, body, argsNode, getVisibility(), position);
    }
}


text:
import {CallSignatureDeclaration as tsCallSignatureDeclaration} from 'typescript';

import {ConvertedSyntaxKind} from '../converted_syntax_kinds';

import {SignatureDeclaration} from './signature_declaration';

export class CallSignatureDeclaration extends SignatureDeclaration {
  constructor(node: tsCallSignatureDeclaration) {
    super(node, ConvertedSyntaxKind.CallSignature);
  }
}