text:
<!DOCTYPE HTML>

<title>Francisco E. Paez -- homepage</title>

About me

Hi! My name is Francisco E. Paez, and this is my awesome homepage (always under construction.)

I have a Computer Science PhD from UNS and got my grad degree at Computer Science from UNPSJB. I am a JTP (Jefe de Trabajos Práticos) at UNPSJB and a member of the Real-Time Systems Group at UNPSJB on Puerto Madryn.

Research areas

My primary research areas are real-time and embedded systems, in particular real-time operating systems, schedulability methods, memory administration and the design and verification of real-time systems.

My publications

Check out some of my publications at the Real-Time Systems Group's publication page.
Visit my profiles at Google Scholar and ResearchGate for more info.

Software

I use both Windows and Linux as personal operating systems, as sooner or later both of them will make you mourn someday.
Said that, I really like free software, and kind of support it. And I think that you too should do it :)

Some stuff in my GitHub repos.

My other interests...

I'm a amateur photographer. You could see my photos on Flickr.

Not a music freak, but I'm into it. Check what i'm listening in last.fm.

I really, really, really like to read. Specially science-fiction literature. An (incomplete) list of books that i have read is here.


text:
@interface ResultModel : JSONModel

@property (nonatomic, strong) NSString *status;
@property (nonatomic, strong) NSString *msg;
@property (nonatomic, strong) id data;

@end

redpajama_set_name: RedPajamaGithub


text:
<?php
return array (
  'Dashboard' => 'Kokpit',
  'This is your dashboard.

Any new activities or posts that might interest you will be displayed here.' => 'To jest twój kokpit.

Każda nowa aktywność lub post który może ciebie interesować pojawi się tutaj. ',
);


text:
#pragma once
#include <aws/auditmanager/AuditManager_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace AuditManager
{
namespace Model
{

  /**
   *
 A system asset that's evaluated in an Audit Manager assessment.
   *

See Also:
   AWS
   * API Reference

   */
  class AWS_AUDITMANAGER_API Resource
  {
  public:
    Resource();
    Resource(Aws::Utils::Json::JsonView jsonValue);
    Resource& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline Resource& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline Resource& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
 The Amazon Resource Name (ARN) for the resource.

     */
    inline Resource& WithArn(const char* value) { SetArn(value); return *this;}

    /**
     *
 The value of the resource.

     */
    inline const Aws::String& GetValue() const{ return m_value; }

    /**
     *
 The value of the resource.

     */
    inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }

    /**
     *
 The value of the resource.

     */
    inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; }

    /**
     *
 The value of the resource.

     */
    inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }

    /**
     *
 The value of the resource.

     */
    inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); }

    /**
     *
 The value of the resource.

     */
    inline Resource& WithValue(const Aws::String& value) { SetValue(value); return *this;}

    /**
     *
 The value of the resource.

     */
    inline Resource& WithValue(Aws::String&& value) { SetValue(std::move(value)); return *this;}

    /**
     *
 The value of the resource.

     */
    inline Resource& WithValue(const char* value) { SetValue(value); return *this;}

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline const Aws::String& GetComplianceCheck() const{ return m_complianceCheck; }

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline bool ComplianceCheckHasBeenSet() const { return m_complianceCheckHasBeenSet; }

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline void SetComplianceCheck(const Aws::String& value) { m_complianceCheckHasBeenSet = true; m_complianceCheck = value; }

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline void SetComplianceCheck(Aws::String&& value) { m_complianceCheckHasBeenSet = true; m_complianceCheck = std::move(value); }

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline void SetComplianceCheck(const char* value) { m_complianceCheckHasBeenSet = true; m_complianceCheck.assign(value); }

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline Resource& WithComplianceCheck(const Aws::String& value) { SetComplianceCheck(value); return *this;}

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline Resource& WithComplianceCheck(Aws::String&& value) { SetComplianceCheck(std::move(value)); return *this;}

    /**
     *
 The evaluation status for a resource that was assessed when collecting
     * compliance check evidence.

Audit Manager classes the resource
     * as non-compliant if Security Hub reports a Fail result, or if Config
     * reports a Non-compliant result.

Audit Manager classes
     * the resource as compliant if Security Hub reports a Pass result, or if
     * Config reports a Compliant result.

If a compliance
     * check isn't available or applicable, then no compliance evaluation can be made
     * for that resource. This is the case if a resource assessment uses Config or
     * Security Hub as the underlying data source type, but those services aren't
     * enabled. This is also the case if the resource assessment uses an underlying
     * data source type that doesn't support compliance checks (such as manual
     * evidence, Amazon Web Services API calls, or CloudTrail).

     */
    inline Resource& WithComplianceCheck(const char* value) { SetComplianceCheck(value); return *this;}

  private:

    Aws::String m_arn;
    bool m_arnHasBeenSet = false;

    Aws::String m_value;
    bool m_valueHasBeenSet = false;

    Aws::String m_complianceCheck;
    bool m_complianceCheckHasBeenSet = false;
  };

} // namespace Model
} // namespace AuditManager
} // namespace Aws


text:
<?php

class Twig_Tests_Grammar_NumberTest extends \PHPUnit\Framework\TestCase
{
    public function testMagicToString()
    {
        $grammar = new Twig_Extensions_Grammar_Number('foo');
        $this->assertEquals('<foo:number>', (string) $grammar);
    }
}


text:
package redshift

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/client/metadata"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/signer/v4"
	"github.com/aws/aws-sdk-go/private/protocol/query"
)

// Overview
//
// This is an interface reference for Amazon Redshift. It contains documentation
// for one of the programming or command line interfaces you can use to manage
// Amazon Redshift clusters. Note that Amazon Redshift is asynchronous, which
// means that some interfaces may require techniques, such as polling or asynchronous
// callback handlers, to determine when a command has been applied. In this
// reference, the parameter descriptions indicate whether a change is applied
// immediately, on the next instance reboot, or during the next maintenance
// window. For a summary of the Amazon Redshift cluster management interfaces,
// go to Using the Amazon Redshift Management Interfaces (http://docs.aws.amazon.com/redshift/latest/mgmt/using-aws-sdk.html).
//
// Amazon Redshift manages all the work of setting up, operating, and scaling
// a data warehouse: provisioning capacity, monitoring and backing up the cluster,
// and applying patches and upgrades to the Amazon Redshift engine. You can
// focus on using your data to acquire new insights for your business and customers.
//
// If you are a first-time user of Amazon Redshift, we recommend that you begin
// by reading the Amazon Redshift Getting Started Guide (http://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html).
//
// If you are a database developer, the Amazon Redshift Database Developer Guide
// (http://docs.aws.amazon.com/redshift/latest/dg/welcome.html) explains how
// to design, build, query, and maintain the databases that make up your data
// warehouse.
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type Redshift struct {
	*client.Client
}

// Used for custom client initialization logic
var initClient func(*client.Client)

// Used for custom request initialization logic
var initRequest func(*request.Request)

// A ServiceName is the name of the service the client will make API calls to.
const ServiceName = "redshift"

// New creates a new instance of the Redshift client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
//     // Create a Redshift client from just a session.
//     svc := redshift.New(mySession)
//
//     // Create a Redshift client with additional configuration
//     svc := redshift.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *Redshift {
	c := p.ClientConfig(ServiceName, cfgs...)
	return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}

// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *Redshift {
	svc := &Redshift{
		Client: client.New(
			cfg,
			metadata.ClientInfo{
				ServiceName:   ServiceName,
				SigningRegion: signingRegion,
				Endpoint:      endpoint,
				APIVersion:    "2012-12-01",
			},
			handlers,
		),
	}

	// Handlers
	svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
	svc.Handlers.Build.PushBackNamed(query.BuildHandler)
	svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler)
	svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler)
	svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler)

	// Run custom client initialization if present
	if initClient != nil {
		initClient(svc.Client)
	}

	return svc
}

// newRequest creates a new request for a Redshift operation and runs any
// custom request initialization.
func (c *Redshift) newRequest(op *request.Operation, params, data interface{}) *request.Request {
	req := c.NewRequest(op, params, data)

	// Run custom request initialization if present
	if initRequest != nil {
		initRequest(req)
	}

	return req
}


text:
@interface ZQPreviewCell () <UIScrollViewDelegate>

@end
@implementation ZQPreviewCell

- (instancetype)init {
    return [self initWithFrame:CGRectMake(0, 0, kTPScreenWidth, kTPScreenHeight)];
}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        self.scrollView.bouncesZoom = YES;
        self.scrollView.maximumZoomScale = 2.5;
        self.scrollView.minimumZoomScale = 1.0;
        self.scrollView.multipleTouchEnabled = YES;
        self.scrollView.delegate = self;
        self.scrollView.scrollsToTop = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.scrollView.delaysContentTouches = NO;
        self.scrollView.canCancelContentTouches = YES;
        self.scrollView.alwaysBounceVertical = NO;
        self.scrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height);
        [self addSubview:self.scrollView];

        self.ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(kPhotoCellMargin, 0, frame.size.width-kPhotoCellMargin*2, frame.size.height)];
        self.ivPhoto.backgroundColor = [UIColor blackColor];
        self.ivPhoto.contentMode = UIViewContentModeScaleAspectFit;
        self.ivPhoto.layer.masksToBounds = YES;
        [self.scrollView addSubview:self.ivPhoto];

        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        [self addGestureRecognizer:tap1];

        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
        tap2.numberOfTapsRequired = 2;
        [tap1 requireGestureRecognizerToFail:tap2];
        [self addGestureRecognizer:tap2];

    }
    return self;
}

- (void)display:(BOOL)bSingleSelect cache:(NSCache *)cache indexPath:(NSIndexPath *)indexPath {
    ______WS();
    UIImage *image = [cache objectForKey:indexPath];
    if (image) {
        self.ivPhoto.image = image;
    }
    else {
        self.mPhoto.requestID = [ZQPhotoFetcher getPhotoFastWithAssets:self.mPhoto.asset photoWidth:kTPScreenWidth completionHandler:^(UIImage *image, NSDictionary *info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image) {
                    wSelf.ivPhoto.image = image;
                    [cache setObject:image forKey:indexPath];
                    [wSelf autouLayoutImageView:bSingleSelect];
                }

            });
        }];
    }

}

- (void)singleTap:(UITapGestureRecognizer *)tap {
    if (self.singleTapBlock) {
        self.singleTapBlock();
    }
}
- (void)doubleTap:(UITapGestureRecognizer *)tap {
    if (self.scrollView.zoomScale > 1.0) {
        [self.scrollView setZoomScale:1.0 animated:YES];
    }
    else {
        CGPoint touchPoint = [tap locationInView:self.ivPhoto];
        CGFloat newZoomScale = self.scrollView.maximumZoomScale;
        CGFloat xsize = self.frame.size.width / newZoomScale;
        CGFloat ysize = self.frame.size.height / newZoomScale;
        [self.scrollView zoomToRect:CGRectMake(touchPoint.x - xsize / 2.0, touchPoint.y - ysize / 2.0, xsize, ysize) animated:YES];
    }
}
#pragma mark - 调整图片大小
- (void)autouLayoutImageView:(BOOL)bSingleSelect {
    CGFloat viewWidth = CGRectGetWidth(self.frame);
    CGFloat viewHeight = CGRectGetHeight(self.frame);

    CGRect rect = CGRectZero;
    rect.origin = CGPointZero;
    rect.size.width = viewWidth;

    UIImage *image = self.ivPhoto.image;
    if (image.size.height / image.size.width > viewHeight / viewWidth) {//竖长图,算高度
        rect.size.height = floor(image.size.height / (image.size.width / viewWidth));
    }
    else {//横图
        CGFloat height = image.size.height / image.size.width * viewWidth;
        if (height < 1 || isnan(height)) {
            height = viewHeight;
        }
        height = floor(height);
        rect.size.height = height;
        rect.origin.y = (viewHeight - height) / 2.0;
    }
    if (rect.size.height > viewHeight && rect.size.height - viewHeight <= 1) {
        rect.size.height = viewHeight;
    }

    self.scrollView.contentSize = CGSizeMake(viewWidth, MAX(rect.size.height, viewHeight));
    [self.scrollView scrollRectToVisible:self.bounds animated:NO];
    self.scrollView.alwaysBounceVertical = rect.size.height <= viewHeight ? NO : YES;
    self.ivPhoto.frame = rect;

    if (bSingleSelect) {
        CGFloat height = self.scrollView.contentSize.height;
        CGFloat cropHeight = [UIScreen mainScreen].bounds.size.width;
        self.scrollView.contentSize = CGSizeMake(viewWidth, (rect.size.height-cropHeight)+height);
        [self.scrollView scrollRectToVisible:CGRectMake(0, (rect.size.height-cropHeight)/2, self.bounds.size.width, self.bounds.size.height) animated:NO];
        self.scrollView.alwaysBounceVertical = YES;
        self.ivPhoto.frame = CGRectMake(rect.origin.x, rect.origin.y+(rect.size.height-cropHeight)/2, rect.size.width, rect.size.height);
    }

}

#pragma mark - UIScrollView代理
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.ivPhoto;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGFloat width = CGRectGetWidth(scrollView.frame);
    CGFloat height = CGRectGetHeight(scrollView.frame);

    CGFloat offsetX = (width > scrollView.contentSize.width) ? (width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (height > scrollView.contentSize.height) ? (height - scrollView.contentSize.height) * 0.5 : 0.0;
    self.ivPhoto.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
}

#pragma mark - Crop Image
- (UIImage *)crop:(CGRect)rect {
    // F = frame
    // i = image
    // iv = imageview
    // sv = self.view
    // of = offset

    //Frame Image in imageView coordinates
    CGRect Fi_iv = [self frameForImage:self.ivPhoto.image inImageViewAspectFit:self.ivPhoto];

    //Frame ImageView in self.view coordinates
    CGRect Fiv_sv = self.ivPhoto.frame;

    //Frame Image in self.view coordinates
    CGRect Fi_sv = CGRectMake(Fi_iv.origin.x + Fiv_sv.origin.x
                              ,Fi_iv.origin.y + Fiv_sv.origin.y,
                              Fi_iv.size.width, Fi_iv.size.height);
    //ScrollView offset
    CGPoint offset = self.scrollView.contentOffset;

    //Frame Image in offset coordinates
    CGRect Fi_of = CGRectMake(Fi_sv.origin.x - offset.x,
                              Fi_sv.origin.y - offset.y,
                              Fi_sv.size.width,
                              Fi_sv.size.height);

    CGFloat scale = self.ivPhoto.image.size.width/Fi_of.size.width;

    //the crop frame in image offset coordinates
    CGRect Fcrop_iof = CGRectMake((rect.origin.x - Fi_of.origin.x)*scale,
                                  (rect.origin.y - Fi_of.origin.y)*scale,
                                  rect.size.width*scale,
                                  rect.size.height*scale);
    CGImageRef imageRef = CGImageCreateWithImageInRect(self.ivPhoto.image.CGImage, Fcrop_iof);
    return [UIImage imageWithCGImage:imageRef];
}

-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
    float imageRatio = image.size.width / image.size.height;
    float viewRatio = imageView.frame.size.width / imageView.frame.size.height;

    if(imageRatio < viewRatio)//竖长图
    {
        float scale = imageView.frame.size.height / image.size.height;
        float width = scale * image.size.width;
        float topLeftX = (imageView.frame.size.width - width) * 0.5;

        return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
    }
    else//横图
    {
        float scale = imageView.frame.size.width / image.size.width;
        float height = scale * image.size.height;
        float topLeftY = (imageView.frame.size.height - height) * 0.5;

        return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
    }
}

- (void)prepareForReuse {
    [ZQPhotoFetcher cancelRequest:self.mPhoto.requestID];
    self.mPhoto = nil;
}
@end


text:
static ghost_mpi_datatype GHOST_MPI_DT_C = MPI_DATATYPE_NULL;
static ghost_mpi_datatype GHOST_MPI_DT_Z = MPI_DATATYPE_NULL;

ghost_error ghost_mpi_datatype_get(ghost_mpi_datatype *dt, ghost_datatype datatype)
{
    if (!dt) {
        GHOST_ERROR_LOG("NULL pointer");
        return GHOST_ERR_INVALID_ARG;
    }
#ifdef GHOST_HAVE_MPI
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    if (datatype & GHOST_DT_FLOAT) {
        if (datatype & GHOST_DT_COMPLEX)
            *dt = GHOST_MPI_DT_C;
        else
            *dt = MPI_FLOAT;
    } else {
        if (datatype & GHOST_DT_COMPLEX)
            *dt = GHOST_MPI_DT_Z;
        else
            *dt = MPI_DOUBLE;
    }
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
#else
    UNUSED(datatype);
    *dt = MPI_DATATYPE_NULL;
#endif

    return GHOST_SUCCESS;
}

ghost_error ghost_mpi_datatypes_create()
{
#ifdef GHOST_HAVE_MPI
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_SETUP);
    MPI_CALL_RETURN(MPI_Type_contiguous(2,MPI_FLOAT,&GHOST_MPI_DT_C));
    MPI_CALL_RETURN(MPI_Type_commit(&GHOST_MPI_DT_C));

    MPI_CALL_RETURN(MPI_Type_contiguous(2,MPI_DOUBLE,&GHOST_MPI_DT_Z));
    MPI_CALL_RETURN(MPI_Type_commit(&GHOST_MPI_DT_Z));
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_SETUP);
#else
    UNUSED(GHOST_MPI_DT_C);
    UNUSED(GHOST_MPI_DT_Z);
#endif

    return GHOST_SUCCESS;
}

ghost_error ghost_mpi_datatypes_destroy()
{
#ifdef GHOST_HAVE_MPI
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_TEARDOWN);
    MPI_CALL_RETURN(MPI_Type_free(&GHOST_MPI_DT_C));
    MPI_CALL_RETURN(MPI_Type_free(&GHOST_MPI_DT_Z));
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_TEARDOWN);
#endif

    return GHOST_SUCCESS;
}

ghost_error ghost_datatype_size(size_t *size, ghost_datatype datatype)
{
    if (!ghost_datatype_valid(datatype)) {
        GHOST_ERROR_LOG("Invalid data type %d",(int)datatype);
        return GHOST_ERR_INVALID_ARG;
    }

    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    *size = 0;

    if (datatype & GHOST_DT_FLOAT) {
        *size = sizeof(float);
    } else {
        *size = sizeof(double);
    }

    if (datatype & GHOST_DT_COMPLEX) {
        *size *= 2;
    }

    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
    return GHOST_SUCCESS;
}

bool ghost_datatype_valid(ghost_datatype datatype)
{
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
    if (datatype == GHOST_DT_ANY) {
        return 1;
    }

    if ((datatype & GHOST_DT_FLOAT) &&
            (datatype & GHOST_DT_DOUBLE))
        return 0;

    if (!(datatype & GHOST_DT_FLOAT) &&
            !(datatype & GHOST_DT_DOUBLE))
        return 0;

    if ((datatype & GHOST_DT_REAL) &&
            (datatype & GHOST_DT_COMPLEX))
        return 0;

    if (!(datatype & GHOST_DT_REAL) &&
            !(datatype & GHOST_DT_COMPLEX))
        return 0;

    return 1;
}

const char * ghost_datatype_string(ghost_datatype datatype)
{
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
    if (!ghost_datatype_valid(datatype)) {
        return "Invalid";
    }

    if (datatype == GHOST_DT_ANY) {
        return "any";
    }

    if (datatype & GHOST_DT_FLOAT) {
        if (datatype & GHOST_DT_REAL) {
            return "float";
        } else {
            return "complex float";
        }
    } else {
        if (datatype & GHOST_DT_REAL) {
            return "double";
        } else {
            return "complex double";
        }
    }
}

ghost_error ghost_datatype_idx_get(ghost_datatype_idx *idx, ghost_datatype datatype)
{
    if (!ghost_datatype_valid(datatype)) {
        GHOST_ERROR_LOG("Invalid data type");
        return GHOST_ERR_INVALID_ARG;
    }
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);

    if (datatype & GHOST_DT_FLOAT) {
        if (datatype & GHOST_DT_COMPLEX) {
            *idx = GHOST_DT_C_IDX;
        } else {
            *idx = GHOST_DT_S_IDX;
        }
    } else {
        if (datatype & GHOST_DT_COMPLEX) {
            *idx = GHOST_DT_Z_IDX;
        } else {
            *idx = GHOST_DT_D_IDX;
        }
    }

    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
    return GHOST_SUCCESS;
}

ghost_error ghost_idx2datatype(ghost_datatype *datatype, ghost_datatype_idx idx)
{
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);

    switch(idx) {
        case (ghost_datatype_idx)0:
            *datatype = (ghost_datatype)(GHOST_DT_REAL|GHOST_DT_FLOAT);
            break;
        case (ghost_datatype_idx)1:
            *datatype = (ghost_datatype)(GHOST_DT_REAL|GHOST_DT_DOUBLE);
            break;
        case (ghost_datatype_idx)2:
            *datatype = (ghost_datatype)(GHOST_DT_COMPLEX|GHOST_DT_FLOAT);
            break;
        case (ghost_datatype_idx)3:
            *datatype = (ghost_datatype)(GHOST_DT_COMPLEX|GHOST_DT_DOUBLE);
            break;
        default:
            GHOST_ERROR_LOG("Invalid datatype index!");
            return GHOST_ERR_INVALID_ARG;
    }

    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);
    return GHOST_SUCCESS;
}

const char * ghost_location_string(ghost_location location)
{
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);

    if (location & GHOST_LOCATION_HOST) {
        if (location & GHOST_LOCATION_DEVICE) {
            return "Host&Device";
        } else {
            return "Host";
        }
    } else if (location & GHOST_LOCATION_DEVICE) {
        return "Device";
    } else {
        return "Invalid";
    }
}

const char * ghost_implementation_string(ghost_implementation implementation)
{
    GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL);
    GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL);

    switch(implementation) {
        case GHOST_IMPLEMENTATION_PLAIN:
            return "PLAIN";
        case GHOST_IMPLEMENTATION_SSE:
            return "SSE";
        case GHOST_IMPLEMENTATION_AVX:
            return "AVX";
        case GHOST_IMPLEMENTATION_AVX2:
            return "AVX2";
        case GHOST_IMPLEMENTATION_MIC:
            return "MIC";
        case GHOST_IMPLEMENTATION_CUDA:
            return "CUDA";
        default:
            return "unknown";
    }
}

int ghost_idx_of_location(ghost_location l)
{
    if (l == GHOST_LOCATION_HOST) {
        return GHOST_HOST_IDX;
    } else {
        return GHOST_DEVICE_IDX;
    }
}


text:
//
//  ShareDetailedViewController.m
//  thePlayApp
//
//  Created by Daniel Mathews on 2013-04-24.
//  Copyright (c) 2013 com.theplayapp. All rights reserved.
//

#import "ShareDetailedViewController.h"
#import "GAI.h"

@interface ShareDetailedViewController ()

@end

@implementation ShareDetailedViewController

#define xIndent 11.0f
#define yIndent 8.0f
#define ySpacerEventImageAndCaption 3.0f
#define ySpacerCaptionAndTime 3.0f
#define ySpacerTimeAndMapView 3.0f
#define heightofEventImage 250.0f
#define heightofSportImage 100.0f
#define widthofSportImage 100.0f
#define heightofEventCaption 75.0f
#define heightofStartTime 30.0f
#define heightofMapView 60.0f
#define heightofSportIcon 80.0f
#define inviteFriendsyIndent 360.0f

#define zoominMapArea 600

#define transitionDuration 0.3
#define transitionType kCATransitionFade

@synthesize addEventImage = _addEventImage;
@synthesize addSportImage = _addSportImage;
@synthesize picker =_picker;
@synthesize photoFile = _photoFile;
@synthesize eventCaption = _eventCaption;
@synthesize timeTextView = _timeTextView;
@synthesize locationTextView = _locationTextView;
@synthesize locationName = _locationName;
@synthesize actionSheetDatePicker = _actionSheetDatePicker;
@synthesize dateFormatterForTime = _dateFormatterForTime;
@synthesize eventIconType = _eventIconType;
@synthesize fileUploadBackgroundTaskId = _fileUploadBackgroundTaskId;
@synthesize photoPostBackgroundTaskId = _photoPostBackgroundTaskId;
@synthesize currentLocation = _currentLocation;
@synthesize userCurrentLocation = _userCurrentLocation;
@synthesize locationInfo = _locationInfo;
@synthesize createEventButton = _createEventButton;
@synthesize sportsCollectionController = _sportsCollectionController;
@synthesize instaCollectionController = _instaCollectionController;
@synthesize locationPickerController = _locationPickerController;
@synthesize searchTerm = _searchTerm;
@synthesize timeofEvent = _timeofEvent;
@synthesize endtimeofEvent = _endtimeofEvent;
@synthesize mapView = _mapView;
@synthesize eventType = _eventType;
@synthesize facebookPost = _facebookPost;
@synthesize shouldPostToFacebook = _shouldPostToFacebook;
@synthesize twitterPost = _twitterPost;
@synthesize shouldPostTwitter = _shouldPostTwitter;
@synthesize emailPost = _emailPost;
@synthesize utcOffset;
@synthesize displayStartTimeofEvent = _displayStartTimeofEvent;
@synthesize inviteFriends = _inviteFriends;
@synthesize invitedUsersSet = _invitedUsersSet;
@synthesize pushUsersSet = _pushUsersSet;
@synthesize profilePictureImageView = _profilePictureImageView;
@synthesize chooseAPhoto = _chooseAPhoto;
@synthesize timeTillEvent = _timeTillEvent;
@synthesize event = _event;
@synthesize dateString = _dateString;
@synthesize eventCaptionString = _eventCaptionString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    //
    //[super viewDidLoad];

    float iphone5spacer = 0;
    if (self.view.bounds.size.height == 460) {
        iphone5spacer = 0;
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"create2bgi4.png"]]];
    }else{
        iphone5spacer = 22;
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"create2bgi5.png"]]];
    }

    UIImage *eventImage = [UIImage imageNamed:@"photobox.png"];
    _addEventImage = [[PFImageView alloc] initWithImage:eventImage];

    if (iphone5spacer>0) {
        [_addEventImage setFrame:CGRectMake((self.view.frame.size.width/2)-(eventImage.size.width/2), yIndent+20, eventImage.size.width, eventImage.size.height)];
    }else{
        [_addEventImage setFrame:CGRectMake((self.view.frame.size.width/2)-(eventImage.size.width/2), yIndent+5, eventImage.size.width, eventImage.size.height)];
    }
    _addEventImage.userInteractionEnabled = NO;

    PFFile *imageFile = [self.event objectForKey:kPlayEventPictureKey];

    if (imageFile) {
        self.addEventImage.file = imageFile;
        [self.addEventImage loadInBackground];
    }

    [_addEventImage setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:_addEventImage];

    /*_chooseAPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    [_chooseAPhoto.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
    [_chooseAPhoto.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_chooseAPhoto setTitle:@"CHOOSE\nA\nPHOTO" forState:UIControlStateNormal];
    [_chooseAPhoto setTitleColor:[UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f blue:137.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
    _chooseAPhoto.titleLabel.font = [UIFont fontWithName:kPlayFontName size:15.0f];
    [_chooseAPhoto setFrame:_addEventImage.frame];
    //[_chooseAPhoto addTarget:self action:@selector(loadAddEventPic:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_chooseAPhoto];*/

    _eventIconType = [_event objectForKey:kPlayEventIconTypeKey];
    _addSportImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"Sport%@.png",_eventIconType]]];
    UIImage *logoImage = [UIImage imageNamed:@"logobox.png"];
    [_addSportImage setFrame:CGRectMake(xIndent, yIndent+5, logoImage.size.width, logoImage.size.height)];
    _addSportImage.userInteractionEnabled = YES;
    //[_addSportImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loadSportsPicker:)]];
    [self.view addSubview:_addSportImage];

    //UIView *chooseAPhotobkg = [[UIView alloc] initWithFrame:_addSportImage.frame];
    //[self.view addSubview:chooseAPhotobkg];

    UIImage *eventCaptionImage = [UIImage imageNamed:@"planbox.png"];
    UIImage *eventCaptionImagei5 = [UIImage imageNamed:@"planboxi5.png"];
    _eventCaption = [[UITextView alloc] init];
    _eventCaption.delegate = self;

    if(_eventCaptionString){
     _eventCaption.text = _eventCaptionString;
    }
    _eventCaption.textColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f];
    _eventCaption.scrollEnabled=NO;

    if (iphone5spacer>0) {
        [_eventCaption setFrame:CGRectMake(xIndent, 265+(3*iphone5spacer), eventCaptionImagei5.size.width, eventCaptionImagei5.size.height)];
        _eventCaption.backgroundColor = [UIColor colorWithPatternImage:eventCaptionImagei5];
    }else{
        [_eventCaption setFrame:CGRectMake(xIndent, 265+(3*iphone5spacer), eventCaptionImage.size.width, eventCaptionImage.size.height)];
        _eventCaption.backgroundColor = [UIColor colorWithPatternImage:eventCaptionImage];

    }

    [_eventCaption setReturnKeyType:UIReturnKeyDone];
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)]];

    UILabel *planLabel = [[UILabel alloc] initWithFrame:CGRectMake(_eventCaption.frame.origin.x, _eventCaption.frame.origin.y - 20, eventCaptionImage.size.width, 20)];
    planLabel.text = @"PLAN";
    planLabel.font = [UIFont fontWithName:kPlayFontName size:14.0f];
    planLabel.textColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f];
    planLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:planLabel];
    [self.view addSubview:_eventCaption];

    UIImage *startTimeImage = [UIImage imageNamed:@"timebox.png"];
    UIImage *startTimeImagei5 = [UIImage imageNamed:@"timeboxi5.png"];
    _timeTextView = [UIButton buttonWithType:UIButtonTypeCustom];

    if(_dateString){
        [_timeTextView setTitle:_dateString forState:UIControlStateNormal];
    }

    [_timeTextView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_timeTextView setContentHorizontalAlignment:UIControlContentVerticalAlignmentCenter];
    if (iphone5spacer>0) {
        [_timeTextView setFrame:CGRectMake(xIndent,210+(iphone5spacer*2),startTimeImagei5.size.width,startTimeImagei5.size.height)];
        [_timeTextView setBackgroundImage:startTimeImagei5 forState:UIControlStateNormal];
    }else{
        [_timeTextView setFrame:CGRectMake(xIndent,210+(iphone5spacer*2),startTimeImage.size.width,startTimeImage.size.height)];
        [_timeTextView setBackgroundImage:startTimeImage forState:UIControlStateNormal];
    }

    [_timeTextView setBackgroundImage:startTimeImage forState:UIControlStateNormal];
    _timeTextView.titleLabel.font = [UIFont fontWithName:kPlayFontName size:12.0f];
    [_timeTextView setTitleColor:[UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];

    //[_timeTextView addTarget:self action:@selector(selectADate:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_timeTextView.frame.origin.x, _timeTextView.frame.origin.y - 20, startTimeImage.size.width, 20)];
    timeLabel.text = @"TIME";
    timeLabel.font = [UIFont fontWithName:kPlayFontName size:14.0f];
    timeLabel.textColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:timeLabel];
    [self.view addSubview:_timeTextView];

    //CreateEventButton
    UIImage *createEventImage = [UIImage imageNamed:@"playbutton1.png"];
    _createEventButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_createEventButton setTitle:@"SHARE" forState:UIControlStateNormal];
    [_createEventButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _createEventButton.titleLabel.font = [UIFont fontWithName:kPlayFontName size:18.0f];
    _createEventButton.titleLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
    [_createEventButton setFrame:CGRectMake(222,347+(iphone5spacer*4),createEventImage.size.width,createEventImage.size.height)];
    [_createEventButton addTarget:self action:@selector(createEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_createEventButton setBackgroundImage:createEventImage forState:UIControlStateNormal];
    [self.view addSubview:_createEventButton];

    _dateFormatterForTime = [[NSDateFormatter alloc] init];
    _dateFormatterForTime.locale = [NSLocale currentLocale];
    [_dateFormatterForTime setTimeStyle: NSDateFormatterShortStyle];
    [_dateFormatterForTime setDateStyle: NSDateFormatterMediumStyle];

    _fileUploadBackgroundTaskId = UIBackgroundTaskInvalid;
    _photoPostBackgroundTaskId = UIBackgroundTaskInvalid;

    _eventIconType= [[NSNumber alloc] init];
    _locationName = [[NSString alloc] init];
    _timeTillEvent = [[NSString alloc] init];
    _eventType = [[NSString alloc] init];

    NSArray *locationArray = [_event objectForKey:kPlayEventLocationKey];
    NSString *locationTitle = [locationArray objectAtIndex:1];

    UIImage *locationImage = [UIImage imageNamed:@"locationbox.png"];
    UIImage *locationImagei5 = [UIImage imageNamed:@"locationboxi5.png"];
    _locationTextView = [UIButton buttonWithType:UIButtonTypeCustom];
    [_locationTextView setTitle:locationTitle forState:UIControlStateNormal];
    [_locationTextView setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_locationTextView.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
    [_locationTextView setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
    //[_locationTextView setTitleEdgeInsets:UIEdgeInsetsMake(0,(locationImage.size.width/2)+3, 3, 0)];
    //[_locationTextView setBackgroundColor:[UIColor clearColor]];
    _locationTextView.titleLabel.font = [UIFont fontWithName:kPlayFontName size:12.0f];
    if (iphone5spacer>0) {
        [_locationTextView setFrame:CGRectMake(xIndent, 140 + (iphone5spacer) , locationImagei5.size.width, locationImagei5.size.height)];
        [_locationTextView setBackgroundImage:locationImagei5 forState:UIControlStateNormal];
    }else{
        [_locationTextView setFrame:CGRectMake(xIndent, 140 + (iphone5spacer) , locationImage.size.width, locationImage.size.height)];
        [_locationTextView setBackgroundImage:locationImage forState:UIControlStateNormal];
    }
    //[_locationTextView setUserInteractionEnabled:NO];

    //[_locationTextView addTarget:self action:@selector(openLocationPicker:) forControlEvents:UIControlEventTouchUpInside];

    _mapView = [[MKMapView alloc] init];
    [_mapView setFrame:_locationTextView.frame];
    _mapView.userInteractionEnabled = NO;

    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(_locationTextView.frame.origin.x, _locationTextView.frame.origin.y - 20, locationImage.size.width, 20)];
    locationLabel.text = @"LOCATION";
    locationLabel.font = [UIFont fontWithName:kPlayFontName size:14.0f];
    locationLabel.textColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f];
    locationLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:locationLabel];

    [self.view addSubview:_mapView];
    [self.view addSubview:_locationTextView];

    _mapView.delegate = self;

    //remove Legal from Map
    UIView *legalView = nil;
    for (UIView *subview in self.mapView.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            legalView = subview;
            break;
        }
    }
    if (legalView) {
        [legalView removeFromSuperview];
    }

    _shouldPostToFacebook = NO;
    _shouldPostTwitter = NO;

    UIButton *inviteFriendsText = [UIButton buttonWithType:UIButtonTypeCustom];
    [inviteFriendsText setTitle:[NSString stringWithFormat:@"INVITE FRIENDS"] forState:UIControlStateNormal];
    [inviteFriendsText setTitleColor:[UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f blue:137.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
    inviteFriendsText.titleLabel.font = [UIFont fontWithName:kPlayFontName size:12.0f];
    [inviteFriendsText setFrame:CGRectMake(xIndent,343+(iphone5spacer*4),195,10)];;
    [self.view addSubview:inviteFriendsText];

    //Invite Friends Button
    UIImage *followsharebutton = [UIImage imageNamed:@"follower0.png"];
    _inviteFriends = [UIButton buttonWithType:UIButtonTypeCustom];
    [_inviteFriends setBackgroundImage:followsharebutton forState:UIControlStateNormal];
    [_inviteFriends setBackgroundImage:[UIImage imageNamed:@"follower1.png"] forState:UIControlStateSelected];
    [_inviteFriends setFrame:CGRectMake(111,inviteFriendsyIndent+(iphone5spacer*4),followsharebutton.size.width,followsharebutton.size.height)];
    [_inviteFriends addTarget:self action:@selector(pressedInviteFriends:) forControlEvents:UIControlEventTouchUpInside];
    [_inviteFriends setTitleColor:[UIColor colorWithRed:0.0f/255.0f green:178.0f/255.0f blue:137.0f/255.0f alpha:1.0f] forState:UIControlStateSelected];
    _inviteFriends.titleLabel.font = [UIFont fontWithName:kPlayFontName size:15.0f];
    _inviteFriends.titleEdgeInsets = UIEdgeInsetsMake(0, 25, 10, 0);

    [self.view addSubview:_inviteFriends];

    //Post to Facebook Button
    UIImage *facebookSharebutton = [UIImage imageNamed:@"facebook0.png"];
    _facebookPost = [UIButton buttonWithType:UIButtonTypeCustom];
    [_facebookPost setBackgroundImage:[UIImage imageNamed:@"facebook0.png"] forState:UIControlStateNormal];
    [_facebookPost setBackgroundImage:[UIImage imageNamed:@"facebook1.png"] forState:UIControlStateSelected];
    [_facebookPost setFrame:CGRectMake(61,inviteFriendsyIndent+(iphone5spacer*4),facebookSharebutton.size.width,facebookSharebutton.size.height)];
    [_facebookPost addTarget:self action:@selector(pressedPostToFacebookButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_facebookPost];

    //Post to Twitter Button
    UIImage *twitterSharebutton = [UIImage imageNamed:@"twitter0.png"];
    _twitterPost = [UIButton buttonWithType:UIButtonTypeCustom];
    [_twitterPost setBackgroundImage:[UIImage imageNamed:@"twitter0.png"] forState:UIControlStateNormal];
    [_twitterPost setBackgroundImage:[UIImage imageNamed:@"twitter1.png"] forState:UIControlStateSelected];
    [_twitterPost setFrame:CGRectMake(xIndent,inviteFriendsyIndent+(iphone5spacer*4),twitterSharebutton.size.width,twitterSharebutton.size.height)];
    [_twitterPost addTarget:self action:@selector(pressedPostToTwitterButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_twitterPost];

    //Post to Email Button
    UIImage *emailSharebutton = [UIImage imageNamed:@"email0.png"];
    _emailPost = [UIButton buttonWithType:UIButtonTypeCustom];
    [_emailPost setBackgroundImage:[UIImage imageNamed:@"email0.png"] forState:UIControlStateNormal];
    [_emailPost setBackgroundImage:[UIImage imageNamed:@"email1.png"] forState:UIControlStateSelected];
    [_emailPost setFrame:CGRectMake(161,inviteFriendsyIndent+(iphone5spacer*4),emailSharebutton.size.width,emailSharebutton.size.height)];
    [_emailPost addTarget:self action:@selector(pressedPostToEmailButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_emailPost];

    PFGeoPoint *eventPoint = [self.event objectForKey:kPlayEventCoordinatesKey];
    CLLocation *eventLocation = [[CLLocation alloc] initWithLatitude:eventPoint.latitude longitude:eventPoint.longitude];

    [self setMap:eventLocation];
    //[self showTime];
	// Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    [self setTitle:@"SHARE EVENT"];

    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker sendView:@"Share Event Screen"];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark TextView DelegateMethod

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if(textView == _eventCaption){
        if ([textView.text isEqualToString:kPlayCheckInPlaceholderText]) {
            textView.text = @"";
            textView.textColor = [UIColor blackColor]; //optional
        }
        [textView becomeFirstResponder];

        [self animateTextField:textView up:YES];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    if(textView == _eventCaption){
        if ([textView.text isEqualToString:@""]) {
            textView.text = kPlayCheckInPlaceholderText;
            textView.textColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f]; //optional
        }

        [textView resignFirstResponder];
        [self animateTextField:textView up:NO];
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if(textView == _eventCaption){
        if([text isEqualToString:@"\n"]) {
            [textView resignFirstResponder];
            return NO;
        }
    }
    return YES;
}

-(void) animateTextField:(UITextView*)textField up:(BOOL)up{
    const int movementDistance = -145; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? movementDistance : -movementDistance);

    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

- (void) dismissKeyboard:(id) sender {
    [_eventCaption resignFirstResponder];
}

- (void) setMap:(CLLocation*)location{

    [_mapView removeAnnotations:_mapView.annotations];

    CLLocationCoordinate2D zoomLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

    MKCoordinateRegion adjustedRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, zoominMapArea, zoominMapArea);

    //Adjust center to focus on Custom Pin
    adjustedRegion.center.latitude = adjustedRegion.center.latitude - 0.001;

    [_mapView setRegion:adjustedRegion animated:YES];

    Event *newAnnotation = [[Event alloc] initWithCoordinate:zoomLocation];

    [self.mapView addAnnotation:newAnnotation];
    NSLog(@"addAnnotation called, event is %@, _eventIconType is %@", newAnnotation,_eventIconType);

}

#pragma mark -
#pragma mark PinAnnotations

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{

    static NSString *identifier = @"Event";
    if ([annotation isKindOfClass:[Event class]]) {

        MKAnnotationView *annotationView = (MKAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];

        if (annotationView == nil) {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];

            //annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        } else {
            annotationView.annotation = annotation;
        }

        NSLog(@"in viewForAnnotation _eventIconType = %@", _eventIconType);

        annotationView.image = [PlayUtility imageForEventType:_eventIconType];
        annotationView.enabled = NO;
        annotationView.canShowCallout = NO;

        return annotationView;
    }
    return nil;
}

#pragma mark -
#pragma mark Sharing Actions

- (void)pressedPostToFacebookButton:(UIButton*)sender {

    [PlayUtility isLinkedToFacebook:[PFUser currentUser] block:^(BOOL success, NSError *error) {
        if (success) {
            sender.selected = !sender.selected;
            _shouldPostToFacebook = sender.selected;
        }
    }];
}

- (void)pressedPostToTwitterButton:(UIButton*)sender {

    [PlayUtility isLinkedToTwitter:[PFUser currentUser] block:^(BOOL success, NSError *error) {
        if (success) {
            sender.selected = !sender.selected;
            _shouldPostTwitter = sender.selected;
        }
    }];
}

- (void)pressedPostToEmailButton:(UIButton*)sender {

    if ([MFMailComposeViewController canSendMail]) {

        [self setTitle:@" "];

        MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        mailViewController.mailComposeDelegate = self;
        [mailViewController setSubject:[NSString stringWithFormat:@"%@ is inviting you to an event",[PFUser currentUser].username]];
        [mailViewController setMessageBody:[NSString stringWithFormat:@"%@ is inviting you to %@ <br><br>Interested in joining? <a href=\"https://itunes.apple.com/us/app/play-a-sports-community/id646639758?ls=1&mt=8\">Download the Play app (it's free!) </a>",[PFUser currentUser].username,_eventCaption.text] isHTML:YES];
        [self presentViewController:mailViewController animated:YES completion:nil];
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Device is currently unable to send email."
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Dismiss",nil];
        [alert show];
    }
}

- (void)pressedInviteFriends:(UIButton*)sender {

    [self setTitle:@" "];

    InviteUsersFollowViewController *followerViewController = [[InviteUsersFollowViewController alloc] initWithStyle:UITableViewStylePlain];
    //[followerViewController setUser:[PFUser currentUser]];
    [followerViewController setQueryType:@"Followers"];
    if (_invitedUsersSet) {
        [followerViewController setInvitedUsersSet:_invitedUsersSet];
        [followerViewController setPushUsersSet:_pushUsersSet];
    }
    followerViewController.delegate = self;

    CATransition* transition = [CATransition animation];
    transition.duration = transitionDuration;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = transitionType;
    //transition.subtype = kCATransitionFromTop; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    [[self navigationController] pushViewController:followerViewController animated:NO];
}

- (void)createEvent:(id)sender {
    NSString *eventDesc = [_eventCaption.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (!eventDesc || eventDesc.length == 0 || (!_shouldPostToFacebook && !_shouldPostTwitter && _invitedUsersSet.count == 0)) {

        NSMutableString *errorAlert = [[NSMutableString alloc] initWithString:@""];

       // NSLog(@"_shouldPostToFacebook is %d",_shouldPostToFacebook);

        if (!eventDesc || eventDesc.length == 0){
            [errorAlert appendString:@"Event description is blank\n"];
        }
        if (!_shouldPostToFacebook && !_shouldPostTwitter && _invitedUsersSet.count == 0) {
            [errorAlert appendString:@"Please choose a social network or Invite friends on Play\n"];
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:errorAlert
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Dismiss",nil];
        [alert show];
        return;
    }
    else {

            if(_shouldPostToFacebook){
                [PlayUtility authorizePermissionsForFacebook:_event postedString:_eventCaption.text];
            }

            if (_shouldPostTwitter) {
                [PlayUtility postTwitterStatus:_eventCaption.text];
            }

            NSLog(@"_invitedUsersSet.count is %d", _invitedUsersSet.count);

            if (_invitedUsersSet.count > 0) {

                NSLog(@"in _invitedUsersSet.count");

                [PlayUtility inviteFollowersInBackground:_event invitedUsers:_invitedUsersSet];

                NSLog(@"_pushUsersSet.count is %d", _pushUsersSet.count);

                if(_pushUsersSet.count > 0){

                    NSLog(@"in _pushUsersSet.count");

                    [PlayUtility pushNotificationsinBackground:[NSDictionary dictionaryWithObjectsAndKeys:
                                [NSString stringWithFormat:@"Yea! %@ has invited you to an event",[PFUser currentUser].username], @"alert",
                                                                _event.objectId,@"e",
                                                                @"Increment", @"badge",nil]
                                                     pushUsers:_pushUsersSet];
                }
            }

            [[NSNotificationCenter defaultCenter] postNotificationName:PlayUtilityUserRefreshPinsNotificationBecauseEventCreated object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:_event,@"event",_currentLocation,@"eventCoordinates",nil]];

        [self.parentViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -
#pragma mark InviteUsersControllerDelegate

-(void)inviteFriendsController:(InviteUsersFollowViewController *)inviteFriendsController invitedUserSet:(NSSet *)invitedUserSet pushUserSet:(NSSet *)pushUserSet{

    //    NSLog(@"inside inviteFriendsController Delegate");

    _invitedUsersSet = [NSMutableSet setWithSet:invitedUserSet];
    _pushUsersSet = [NSMutableSet setWithSet:pushUserSet];

    if(_invitedUsersSet.count > 0){
        [_inviteFriends setSelected:YES];
        [_inviteFriends setTitle:[NSString stringWithFormat:@"%d",_invitedUsersSet.count] forState:UIControlStateNormal];
    }else{
        [_inviteFriends setSelected:NO];
        [_inviteFriends setTitle:@"" forState:UIControlStateNormal];
    }
}

@end


text:
module Formaggio
  module PumaManager

    def self.puma_config(*args)
      PumaConfig.new(*args)
    end

    # Start the puma web server on the given port
    def self.start(port, opts)
      config = puma_config(port)
      exec config.start_cmd
    end

    # Restart the puma web server on the given port
    def self.restart(port, opts)
      config = puma_config(port)
      exec config.restart_cmd
    end

    # Stop the puma web server on the given port
    def self.stop(port, opts)
      config = puma_config(port)
      exec config.stop_cmd
    end

    # Write the start and restart scripts to files
    # Does not overwrite if the files exist
    def self.write_scripts(port, opts)
      config = puma_config(port, opts)
      make_scripts_dir(config)
      write_start_script(config)
      write_restart_script(config)
    end

    # Write the start script to a file
    # Does not overwrite if the file exists
    def self.write_start_script(config)
      write_script_to_file(config.start_script, config.start_file)
    end

    # Write the restart script to a file
    # Does not overwrite if the file exists
    def self.write_restart_script(config)
      write_script_to_file(config.restart_script, config.restart_file)
    end

    # Write the given script to the given file and make executable
    # Does not overwrite if the file exists
    def self.write_script_to_file(script, file)
      # Put the start script code in a file
      File.open(file, "w") { |f| f.write(script) } unless File.exists? file
      # Make the file executable
      FileUtils.chmod "a+x", file unless File.executable? file
    end

    # Create the scripts directory if necessary
    def self.make_scripts_dir(config)
      FileUtils.mkdir_p config.scripts_path unless Dir.exist? config.scripts_path
    end
  end
end


text:
<?php
App::uses('FishController', 'Controller');

/**
 * FishController Test Case
 *
 */
class FishControllerTest extends ControllerTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'app.fish',
		'app.biology',
		'app.water_type',
		'app.description',
		'app.fish_taxonomy',
		'app.taxonomy',
		'app.founder',
		'app.gallery',
		'app.morphological',
		'app.status',
		'app.common_name',
		'app.location',
		'app.reference'
	);

}


text:
/**
 * Module dependencies.
 */
var passport = require('passport'),
    util = require('util'),
    BadRequestError = require('./errors/badrequesterror'),
    AuthTkt = require('./authtkt'),
    _ = require('underscore');

/**
 * `Strategy` constructor.
 *
 *   - `key`               Name of the cookie.
 *   - `encodeUserData`    Encode and decode the userData string using base64.
 *                         Defaults to true.
 *   - `jsonUserData`      Encode and decode the userData string as JSON.
 *                         Defaults to false.
 *   - `ip`                Use the given IP address (a dotted quad string)
 *                         to create/validate tickets.
 *   - `timeout`           Time, in seconds, for ticket validation.
 *
 * @param {Object} secret The server-side authentication secret
 * @param {Object} options Options hash
 * @api public
 */
function Strategy(secret, options) {
    options = options || {};

    if(!secret)
        throw new Error("secret is required");

    passport.Strategy.call(this);
    this.name = 'authtkt';
    this.authtkt = new AuthTkt(secret, options);
    this.key = options.key || 'authtkt';
    this.options = options;
}

/**
 * Inherit from `passport.Strategy`.
 */
util.inherits(Strategy, passport.Strategy);

/**
 * Authenticate request based on the presence of an authentication cookie
 *
 * @param {Object} req the request
 * @param {Object} options Can be used to override any of the options above
 * @api protected
 */
Strategy.prototype.authenticate = function(req, options) {
    options =_.extend({
        timeout: null,
        ip: '0.0.0.0',
        tokens: []
    }, this.options, options || {});

    if(!req.cookies)
        throw new Error("The cookieParser() middleware must be configured before passport to use this strategy");

    var cookieValue = req.cookies[this.key],
        strategy = this,
        authInfo;

    if(cookieValue) {
        authInfo = this.authtkt.validateCookie(cookieValue, options);
    }

    if (authInfo) {
        this.success(authInfo.userData, _.clone(authInfo));
    } else {
        this.fail(new BadRequestError(options.badRequestMessage || 'Missing credentials'));
    }

    // Refresh the cookie on response if necessary
    req.res.on('header', function() {
        if(req.authInfo) {
            var userid = req.authInfo.userid;
            var userData = req.authInfo.userData;
            var tokens = req.authInfo.tokens;

            // We don't want to set the cookie if nothing's changed and we
            // are not refreshing for use with a timeout
            if(options.timeout || !authInfo ||
               !_.isEqual(userid, authInfo.userid) ||
               !_.isEqual(userData, authInfo.userData) ||
               !_.isEqual(tokens, authInfo.tokens)
            ) {
                var newCookieValue = strategy.authtkt.getCookie(userid, _.extend(options, {
                    userData: userData,
                    tokens: tokens
                }));
                req.res.cookie(strategy.key, newCookieValue);
            }
        } else if(cookieValue) {
            req.res.clearCookie(strategy.key);
        }
    });
};

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
    /// This is used while computing the values of constant fields.  Since they can depend on each
    /// other, we need to keep track of which ones we are currently computing in order to avoid (and
    /// report) cycles.
    /// </summary>
    internal sealed class ConstantFieldsInProgress
    {
        private readonly SourceFieldSymbol _fieldOpt;
        private readonly HashSet<SourceFieldSymbolWithSyntaxReference> _dependencies;

        internal static readonly ConstantFieldsInProgress Empty = new ConstantFieldsInProgress(null, null);

        internal ConstantFieldsInProgress(
            SourceFieldSymbol fieldOpt,
            HashSet<SourceFieldSymbolWithSyntaxReference> dependencies)
        {
            _fieldOpt = fieldOpt;
            _dependencies = dependencies;
        }

        public bool IsEmpty
        {
            get { return (object)_fieldOpt == null; }
        }

        internal void AddDependency(SourceFieldSymbolWithSyntaxReference field)
        {
            _dependencies.Add(field);
        }
    }
}


text:
package java.sql;

import java.time.Instant;
import java.time.LocalDate;

/**
 *
A thin wrapper around a millisecond value that allows
 * JDBC to identify this as an SQL DATE value.  A
 * milliseconds value represents the number of milliseconds that
 * have passed since January 1, 1970 00:00:00.000 GMT.
 *

 * To conform with the definition of SQL DATE, the
 * millisecond values wrapped by a java.sql.Date instance
 * must be 'normalized' by setting the
 * hours, minutes, seconds, and milliseconds to zero in the particular
 * time zone with which the instance is associated.
 */
public class Date extends java.util.Date {

    /**
     * Constructs a Date object initialized with the given
     * year, month, and day.
     *

     * The result is undefined if a given argument is out of bounds.
     *
     * @param year the year minus 1900; must be 0 to 8099. (Note that
     *        8099 is 9999 minus 1900.)
     * @param month 0 to 11
     * @param day 1 to 31
     * @deprecated instead use the constructor Date(long date)
     */
    @Deprecated
    public Date(int year, int month, int day) {
        super(year, month, day);
    }

    /**
     * Constructs a Date object using the given milliseconds
     * time value.  If the given milliseconds value contains time
     * information, the driver will set the time components to the
     * time in the default time zone (the time zone of the Java virtual
     * machine running the application) that corresponds to zero GMT.
     *
     * @param date milliseconds since January 1, 1970, 00:00:00 GMT not
     *        to exceed the milliseconds representation for the year 8099.
     *        A negative number indicates the number of milliseconds
     *        before January 1, 1970, 00:00:00 GMT.
     */
    public Date(long date) {
        // If the millisecond date value contains time info, mask it out.
        super(date);

    }

    /**
     * Sets an existing Date object
     * using the given milliseconds time value.
     * If the given milliseconds value contains time information,
     * the driver will set the time components to the
     * time in the default time zone (the time zone of the Java virtual
     * machine running the application) that corresponds to zero GMT.
     *
     * @param date milliseconds since January 1, 1970, 00:00:00 GMT not
     *        to exceed the milliseconds representation for the year 8099.
     *        A negative number indicates the number of milliseconds
     *        before January 1, 1970, 00:00:00 GMT.
     */
    public void setTime(long date) {
        // If the millisecond date value contains time info, mask it out.
        super.setTime(date);
    }

    /**
     * Converts a string in JDBC date escape format to
     * a Date value.
     *
     * @param s a String object representing a date in
     *        in the format "yyyy-[m]m-[d]d". The leading zero for mm
     * and dd may also be omitted.
     * @return a java.sql.Date object representing the
     *         given date
     * @throws IllegalArgumentException if the date given is not in the
     *         JDBC date escape format (yyyy-[m]m-[d]d)
     */
    public static Date valueOf(String s) {
        final int YEAR_LENGTH = 4;
        final int MONTH_LENGTH = 2;
        final int DAY_LENGTH = 2;
        final int MAX_MONTH = 12;
        final int MAX_DAY = 31;
        int firstDash;
        int secondDash;
        Date d = null;
        if (s == null) {
            throw new IllegalArgumentException();
        }

        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash + 1);

        if ((firstDash > 0) && (secondDash > 0) && (secondDash < s.length() - 1)) {
            String yyyy = s.substring(0, firstDash);
            String mm = s.substring(firstDash + 1, secondDash);
            String dd = s.substring(secondDash + 1);
            if (yyyy.length() == YEAR_LENGTH &&
                    (mm.length() >= 1 && mm.length() <= MONTH_LENGTH) &&
                    (dd.length() >= 1 && dd.length() <= DAY_LENGTH)) {
                int year = Integer.parseInt(yyyy);
                int month = Integer.parseInt(mm);
                int day = Integer.parseInt(dd);

                if ((month >= 1 && month <= MAX_MONTH) && (day >= 1 && day <= MAX_DAY)) {
                    d = new Date(year - 1900, month - 1, day);
                }
            }
        }
        if (d == null) {
            throw new IllegalArgumentException();
        }

        return d;

    }

    /**
     * Formats a date in the date escape format yyyy-mm-dd.
     *

     * @return a String in yyyy-mm-dd format
     */
    @SuppressWarnings("deprecation")
    public String toString () {
        int year = super.getYear() + 1900;
        int month = super.getMonth() + 1;
        int day = super.getDate();

        char buf[] = "2000-00-00".toCharArray();
        buf[0] = Character.forDigit(year/1000,10);
        buf[1] = Character.forDigit((year/100)%10,10);
        buf[2] = Character.forDigit((year/10)%10,10);
        buf[3] = Character.forDigit(year%10,10);
        buf[5] = Character.forDigit(month/10,10);
        buf[6] = Character.forDigit(month%10,10);
        buf[8] = Character.forDigit(day/10,10);
        buf[9] = Character.forDigit(day%10,10);

        return new String(buf);
    }

    // Override all the time operations inherited from java.util.Date;

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #setHours
    */
    @Deprecated
    public int getHours() {
        throw new IllegalArgumentException();
    }

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #setMinutes
    */
    @Deprecated
    public int getMinutes() {
        throw new IllegalArgumentException();
    }

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #setSeconds
    */
    @Deprecated
    public int getSeconds() {
        throw new IllegalArgumentException();
    }

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #getHours
    */
    @Deprecated
    public void setHours(int i) {
        throw new IllegalArgumentException();
    }

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #getMinutes
    */
    @Deprecated
    public void setMinutes(int i) {
        throw new IllegalArgumentException();
    }

   /**
    * This method is deprecated and should not be used because SQL Date
    * values do not have a time component.
    *
    * @deprecated
    * @exception IllegalArgumentException if this method is invoked
    * @see #getSeconds
    */
    @Deprecated
    public void setSeconds(int i) {
        throw new IllegalArgumentException();
    }

   /**
    * Private serial version unique ID to ensure serialization
    * compatibility.
    */
    static final long serialVersionUID = 1511598038487230103L;

    /**
     * Obtains an instance of {@code Date} from a {@link LocalDate} object
     * with the same year, month and day of month value as the given
     * {@code LocalDate}.
     *

     * The provided {@code LocalDate} is interpreted as the local date
     * in the local time zone.
     *
     * @param date a {@code LocalDate} to convert
     * @return a {@code Date} object
     * @exception NullPointerException if {@code date} is null
     * @since 1.8
     */
    @SuppressWarnings("deprecation")
    public static Date valueOf(LocalDate date) {
        return new Date(date.getYear() - 1900, date.getMonthValue() -1,
                        date.getDayOfMonth());
    }

    /**
     * Converts this {@code Date} object to a {@code LocalDate}
     *

     * The conversion creates a {@code LocalDate} that represents the same
     * date value as this {@code Date} in local time zone
     *
     * @return a {@code LocalDate} object representing the same date value
     *
     * @since 1.8
     */
    @SuppressWarnings("deprecation")
    public LocalDate toLocalDate() {
        return LocalDate.of(getYear() + 1900, getMonth() + 1, getDate());
    }

   /**
    * This method always throws an UnsupportedOperationException and should
    * not be used because SQL {@code Date} values do not have a time
    * component.
    *
    * @exception UnsupportedOperationException if this method is invoked
    */
    @Override
    public Instant toInstant() {
        throw new UnsupportedOperationException();
    }
}


text:
BOOL TCTableViewSupportsConstraintsProperty();
BOOL TCCollectionViewSupportsConstraintsProperty();

#pragma mark - UICollectionReusableView

@implementation UICollectionReusableView (TCLayoutSizeFittingSize)

// This is kind of a hack because cells don't have an intrinsic content size or any other way to constrain them to a size. As a result, labels that _should_ wrap at the bounds of a cell, don't. So by adding width and height constraints to the cell temporarily, we can make the labels wrap and the layout compute correctly.
- (CGSize)tc_preferredLayoutSizeFittingSize:(CGSize)fittingSize {
    CGRect frame = self.frame;
    frame.size = fittingSize;
    self.frame = frame;

    NSArray *constraints = @[[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:fittingSize.width],
                             [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:UILayoutFittingExpandedSize.height]];
    [self addConstraints:constraints];
    [self updateConstraints];
    CGSize size = [self systemLayoutSizeFittingSize:fittingSize];
    [self removeConstraints:constraints];

    frame.size = size;
    self.frame = frame;

    return size;
}

@end

#pragma mark - UICollectionViewCell

@implementation UICollectionViewCell (TCLayoutSizeFittingSize)

- (CGSize)tc_preferredLayoutSizeFittingSize:(CGSize)fittingSize {
    CGRect frame = self.frame;
    frame.size = fittingSize;
    self.frame = frame;

    CGSize size;
    if (TCCollectionViewSupportsConstraintsProperty()) {
        [self layoutSubviews];
        size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    } else {
        NSArray *constraints = @[
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:fittingSize.width],
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:UILayoutFittingExpandedSize.height]];

        [self addConstraints:constraints];
        [self updateConstraints];
        size = [self systemLayoutSizeFittingSize:fittingSize];
        [self removeConstraints:constraints];
    }

    // Only consider the height for cells, because the contentView isn't anchored correctly sometimes.
    fittingSize.height = size.height;
    frame.size = fittingSize;
    self.frame = frame;

    return fittingSize;
}

@end

#pragma mark - UITableViewCell

@implementation UITableViewCell (TCLayoutSizeFittingSize)

/// **Note**: You should indicate the `preferredMaxLayoutWidth` by this way:
/// **Note**: You should indicate the `preferredMaxLayoutWidth` by this way:
/// ```Swift
/// override func layoutSubviews() {
///    super.layoutSubviews()
///    contentView.setNeedsLayout()
///    contentView.layoutIfNeeded()
///    nameLabel.preferredMaxLayoutWidth = CGRectGetWidth(nameLabel.bounds)
/// }
/// ```
- (CGSize)tc_preferredLayoutSizeFittingSize:(CGSize)fittingSize {
    CGRect frame = self.frame;
    frame.size = fittingSize;
    self.frame = frame;

    CGSize size;
    if (TCCollectionViewSupportsConstraintsProperty()) {
        [self layoutSubviews];
        size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    } else {
        NSArray *constraints = @[
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:fittingSize.width],
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:UILayoutFittingExpandedSize.height]];

        [self addConstraints:constraints];
        [self updateConstraints];
        size = [self systemLayoutSizeFittingSize:fittingSize];
        [self removeConstraints:constraints];
    }

    // Only consider the height for cells, because the contentView isn't anchored correctly sometimes.
    size.width = fittingSize.width;
    frame.size = size;
    self.frame = frame;

    return size;
}

@end

#pragma mark - UITableViewHeaderFooterView

@implementation UITableViewHeaderFooterView (TCLayoutSizeFittingSize)

- (CGSize)tc_preferredLayoutSizeFittingSize:(CGSize)fittingSize {
    CGRect frame = self.frame;
    frame.size = fittingSize;
    self.frame = frame;

    CGSize size;
    if (TCCollectionViewSupportsConstraintsProperty()) {
        [self layoutSubviews];
        // Apple's implement like folow, somehow, it doesn't work.
        // size = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
        size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    } else {
        NSArray *constraints = @[
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:fittingSize.width],
                                 [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:UILayoutFittingExpandedSize.height]];

        [self addConstraints:constraints];
        [self updateConstraints];
        size = [self systemLayoutSizeFittingSize:fittingSize];
        [self removeConstraints:constraints];
    }

    // Only consider the height for cells, because the contentView isn't anchored correctly sometimes.
    fittingSize.height = size.height;
    frame.size = fittingSize;
    self.frame = frame;

    return fittingSize;
}

@end

#pragma mark - Helpers

static inline BOOL _supportsConstraintsProperty() {
    static BOOL constraintsSupported;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *versionString = [[UIDevice currentDevice] systemVersion];
        constraintsSupported = ([versionString integerValue] > 7);
    });

    return constraintsSupported;
}

BOOL TCTableViewSupportsConstraintsProperty() {
    return _supportsConstraintsProperty();
}

BOOL TCCollectionViewSupportsConstraintsProperty() {
    return _supportsConstraintsProperty();
}

#pragma mark - UITableView TCComputeLayoutSize

@implementation UITableView (TCComputeLayoutSize)

- (CGFloat)tc_heightForReusableCellByIdentifier:(nonnull NSString *)identifier dataConfigurationHandler:(nonnull void (^)(UITableViewCell * _Nonnull cell))dataConfigurationHandler {
    UITableViewCell *reusableCell = [self dequeueReusableCellWithIdentifier:identifier];
    if (!reusableCell) {
        [NSException raise:@"FatalError" format:@"Cell must be registered to tableView for identifier: %@", identifier];
    }

    [reusableCell prepareForReuse];
    dataConfigurationHandler(reusableCell);

    CGSize fittingSize = CGSizeMake(CGRectGetWidth(self.bounds), UILayoutFittingExpandedSize.height);
    return [reusableCell tc_preferredLayoutSizeFittingSize:fittingSize].height + 1.0f / [UIScreen mainScreen].scale;
}

- (CGFloat)tc_heightForReusableHeaderFooterViewByIdentifier:(nonnull NSString *)identifier dataConfigurationHandler:(nonnull void (^)(UITableViewHeaderFooterView * _Nonnull reusableHeaderFooterView))dataConfigurationHandler {
    UITableViewHeaderFooterView *reusableHeaderFooterView = [self dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!reusableHeaderFooterView) {
        [NSException raise:@"FatalError" format:@"HeaderFooterView must be registered to tableView for identifier: %@", identifier];
    }

    [reusableHeaderFooterView prepareForReuse];
    dataConfigurationHandler(reusableHeaderFooterView);

    CGSize fittingSize = CGSizeMake(CGRectGetWidth(self.bounds), UILayoutFittingExpandedSize.height);
    return [reusableHeaderFooterView tc_preferredLayoutSizeFittingSize:fittingSize].height + 1.0f / [UIScreen mainScreen].scale;
}

@end

#pragma mark -

@implementation UICollectionView (TCComputeLayoutSize)

- (CGSize)tc_sizeForReusableViewByClass:(nonnull Class)cls preferredLayoutSizeFittingSize:(CGSize)fittingSize dataConfigurationHandler:(nonnull void (^)(UICollectionReusableView * _Nonnull reusableView))dataConfigurationHandler {
    NSMutableDictionary<NSString *, UICollectionReusableView *> *reusableViews = [self.tc_reusableViews mutableCopy];
    if (!reusableViews) {
        reusableViews = [NSMutableDictionary new];
    }

    NSString *key = NSStringFromClass(cls);
    UICollectionReusableView *reusableView = [reusableViews objectForKey:key];
    if (!reusableView) {
        reusableView = [[cls alloc] initWithFrame:CGRectZero];
        [reusableViews setObject:reusableView forKey:key];
        [self tc_setReusableViews:reusableViews];
    }

    [reusableView prepareForReuse];
    dataConfigurationHandler(reusableView);

    return [reusableView tc_preferredLayoutSizeFittingSize:fittingSize];
}

static const void *ReusableViewsAccocaitionKey = @"reusableViews";
- (NSDictionary<NSString *, UICollectionReusableView *> *)tc_reusableViews {
    return objc_getAssociatedObject(self, &ReusableViewsAccocaitionKey);
}

- (void)tc_setReusableViews:(NSDictionary<NSString *, UICollectionReusableView *> *)reusableViews {
    objc_setAssociatedObject(self, &ReusableViewsAccocaitionKey, reusableViews, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


text:
<?php

require_once 'PHPUnit/Framework.php';

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

/**
 * Extension to PHPUnit_Framework_AssertionFailedError to mark the special
 * case of an incomplete test.
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 2.0.0
 */
class PHPUnit_Framework_IncompleteTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_IncompleteTest
{
}
?>


text:
<?php namespace Arx\classes;

use Arx;

/**
 * Class Assets
 *
 * Smarter assets handler
 *
 * @example
 *
 * Asset::js(['file1.js', 'file2.js]);
 *
 * #output
 *
 * <script type="text/javascript" src="file1.js"></script>
 * <script type="text/javascript" src="file2.js"></script>
 *
 * @package Arx\classes
 *
 */
class Asset extends singleton
{

    protected $_aInstances = array();

    public static function js($data = array(), $params = array(
        'compiled' => false,
        'attributes' => [],
        'secure' => false,
    ))
    {

        return Load::js($data, $params);
    }

    public static function css($data = array(), $params = array(
        'compiled' => false,
        'attributes' => [],
        'secure' => false,
    ))
    {
        return Load::css($data, $params);
    }

}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.file.formats.android.fbpk.v1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ghidra.app.util.bin.BinaryReader;
import ghidra.file.formats.android.fbpk.*;
import ghidra.program.model.data.*;
import ghidra.util.exception.DuplicateNameException;

public class FBPTv1 extends FBPT {
	private String magic;
	private int nEntries;
	private List<FBPT_Entry> entries = new ArrayList<>();

	public FBPTv1(BinaryReader reader) throws IOException {
		magic = reader.readNextAsciiString(FBPK_Constants.FBPT.length());
		reader.readNextInt();//unknown0
		reader.readNextInt();//unknown1
		reader.readNextInt();//unknown2
		nEntries = reader.readNextInt();
		reader.readNextInt();//unknown3
		reader.readNextInt();//unknown4
		reader.readNextInt();//unknown5
		reader.readNextInt();//unknown6
		reader.readNextInt();//unknown7
		reader.readNextInt();//unknown8
		reader.readNextInt();//unknown9
		reader.readNextInt();//unknownA
		reader.readNextInt();//unknownB
		reader.readNextInt();//unknownC
		reader.readNextInt();//unknownD
		reader.readNextInt();//unknownE
		reader.readNextInt();//unknownF

		for (int i = 0; i < nEntries; ++i) {
			entries.add(new FBPTv1_Entry(reader, i == nEntries - 1));
		}
	}

	@Override
	public String getMagic() {
		return magic;
	}

	public int getNEntries() {
		return nEntries;
	}

	@Override
	public List<FBPT_Entry> getEntries() {
		return entries;
	}

	@Override
	public DataType toDataType() throws DuplicateNameException, IOException {
		Structure struct = new StructureDataType(FBPTv1.class.getSimpleName(), 0);
		struct.add(STRING, FBPK_Constants.FBPT.length(), "magic", null);
		struct.add(DWORD, "unknown0", null);
		struct.add(DWORD, "unknown1", null);
		struct.add(DWORD, "unknown2", null);
		struct.add(DWORD, "nEntries", null);
		struct.add(DWORD, "unknown3", null);
		struct.add(DWORD, "unknown4", null);
		struct.add(DWORD, "unknown5", null);
		struct.add(DWORD, "unknown6", null);
		struct.add(DWORD, "unknown7", null);
		struct.add(DWORD, "unknown8", null);
		struct.add(DWORD, "unknown9", null);
		struct.add(DWORD, "unknownA", null);
		struct.add(DWORD, "unknownB", null);
		struct.add(DWORD, "unknownC", null);
		struct.add(DWORD, "unknownD", null);
		struct.add(DWORD, "unknownE", null);
		struct.add(DWORD, "unknownF", null);
		return struct;
	}

}


text:
/**
 * Renders a simple panel for displaying a link to the API reference documentation, plus a summary of key interfaces.
 *

 * The tag attributes are read from the lk-api-reference element, as shown in the example below:
 *

 *    <lk-api-reference href="http://api.jquery.com/ready/">
 *      $( document ).ready( handler )

 *      $( handler )
 *    </lk-api-reference>
 *

 *
 *

 *
Tag Attributes:

 *

 *

Name	Description

 *
href	URL to the API reference documentation.

 *
width	optional width for the wrapper div.

 *

 *
 * @module lkApiReferenceTag
 */
var lkApiReferenceTag = (function(tzGeneralUtils, tzDomHelper, tzCustomTagHelper) {
  "use strict";

  var template =
      ['
',
       '
api
',
       '
{{context.rawRightColumnHtml}}
',
       '
'
      ].join('\n');

  return {
    /**
     * Return the name of this tag.
     *
     * @returns {string}
     */
    getTagName: function() {
      return "lk-api-reference";
    },

    /**
     * Render all <lk-api-reference> tags on the page.
     */
    renderAll: function() {
      tzCustomTagHelper.renderAll(this);
    },

    /**
     * Render the <lk-api-reference> tag identified by the given tagId.
     *
     * @param tagId ID of the tag to render.
     */
    renderTagById: function(tagId) {
      tzCustomTagHelper.renderTagById(this, tagId);
    },

    /**
     * Render the given lkApiReferenceTagNode.
     *
     * @param lkApiReferenceTagNode the node to retrieve the attributes from and then render the result to.
     */
    renderTag: function(lkApiReferenceTagNode) {
      // build the context
      var width = lkApiReferenceTagNode.getAttribute("width");
      var context = {
        "href": lkApiReferenceTagNode.getAttribute("href"),
        "width": lkApiReferenceTagNode.getAttribute("width"),
        "rawRightColumnHtml": lkApiReferenceTagNode.innerHTML.trim()
      };

      // remove child nodes (e.g., rawRightColumnHtml retrieved for use by the right column)
      tzDomHelper.removeAllChildNodes(lkApiReferenceTagNode);

      // render the result
      this.render(lkApiReferenceTagNode, context);
    },

    /**
     * Render the <lk-api-reference> tag into the given containerNode.
     *
     * @param containerNode where to render the result.
     * @param context object containing the values needed to render the result:
     *

     *
href: URL to the API reference documentation.
     *
width: optional width for the wrapper div.
     *
rawRightColumnHtml: the raw HTML to render into the right column (e.g., APIs to be referenced).
     *

     */
    render: function(containerNode, context) {
      //var template = tzCustomTagHelper.getTemplate(this.getTagName() + "Template"); // @-@:p1(geo) Experimental

      tzCustomTagHelper.renderTagFromTemplate(containerNode, template, context);

      // update the width
      if (tzGeneralUtils.isNotEmpty(context.width)) {
        containerNode.style.width = context.width;
      }
    }
  };

}(tzGeneralUtilsModule, tzDomHelperModule, tzCustomTagHelperModule));


text:
package cn.lhfei.zookeeper;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;

/**
 * @version 0.1
 *
 * @author Hefei Li
 *
 * @since May 3, 2015
 */
public class ResilientActiveKeyValueStore extends ConnectionWatcher {

	private static final Charset CHARSET = Charset.forName("UTF-8");
	private static final int MAX_RETRIES = 5;
	private static final int RETRY_PERIOD_SECONDS = 10;

	public void write(String path, String value) throws InterruptedException,
			KeeperException {
		int retries = 0;
		while (true) {
			try {
				Stat stat = zk.exists(path, false);
				if (stat == null) {
					zk.create(path, value.getBytes(CHARSET),
							Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
				} else {
					zk.setData(path, value.getBytes(CHARSET), stat.getVersion());
				}
				return;
			} catch (KeeperException.SessionExpiredException e) {
				throw e;
			} catch (KeeperException e) {
				if (retries++ == MAX_RETRIES) {
					throw e;
				}
				// sleep then retry
				TimeUnit.SECONDS.sleep(RETRY_PERIOD_SECONDS);
			}
		}
	}

	public String read(String path, Watcher watcher)
			throws InterruptedException, KeeperException {
		byte[] data = zk.getData(path, watcher, null/* stat */);
		return new String(data, CHARSET);
	}
}


text:
package io.gravitee.reporter.elastic.config;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author Guillaume Gillon
 */
public class PipelineConfiguration {

    private final Logger LOGGER = LoggerFactory.getLogger(PipelineConfiguration.class);

    enum Processor {
        geoip("request", builder -> {
                return builder.append(
                        "{\"geoip\":{\"field\":\"remote-address\"}}," +
                        "{\"set\": {\"field\": \"geoip.city_name\",\"value\": \"Unknown\",\"override\": false}},"+
                                "{\"set\": {\"field\": \"geoip.continent_name\",\"value\": \"Unknown\",\"override\": false}}," +
                                "{\"set\": {\"field\": \"geoip.region_name\",\"value\": \"Unknown\",\"override\": false}}"
                );
        });

        private String indexType;
        private Function<StringBuilder, StringBuilder> contentBuilder;

        public final static List<String> ingestManaged = Arrays.stream(Processor.values()).map(Processor::name).collect(Collectors.toList());

        Processor(String indexType, Function<StringBuilder, StringBuilder> contentBuilder) {
            this.indexType = indexType;
            this.contentBuilder = contentBuilder;
        }
    }

    private final String pipeline = "gravitee_pipeline";

    private boolean valid = false;
    private boolean initialize = false;

    private static StringBuilder initPipeline() {
        StringBuilder stringBuilder = new StringBuilder();
        return stringBuilder.append("{\"description\":\"Gravitee pipeline\",\"processors\":[");
    }

    private static StringBuilder finisherPipeline(StringBuilder stringBuilder) {
        return stringBuilder.append("]}");
    }

    public XContentBuilder createPipeline() throws IOException {
        XContentBuilder template = null;

        StringBuilder stringBuilder = Processor.ingestManaged.stream()
                .map(processor -> Processor.valueOf(processor).contentBuilder)
                .collect(Collector.of(
                        PipelineConfiguration::initPipeline,
                        (response, processor) -> processor.apply(response),
                        StringBuilder::append,
                        PipelineConfiguration::finisherPipeline
                ));

        try (XContentParser parser =
                     XContentFactory.xContent(XContentType.JSON).createParser(stringBuilder.toString().getBytes())) {
            parser.nextToken();
            template = XContentFactory.jsonBuilder().copyCurrentStructure(parser);
        }

        return template;
    }

    public String getIngestManaged() {
        return Processor.ingestManaged.stream().collect(Collectors.joining(","));
    }

    public String getPipelineName() { return this.pipeline; }

    public String getPipeline() { return valid ? this.pipeline : null; }

    public void valid() {
        this.valid = true;
    }

    public boolean isValid() {
        return this.valid;
    }

    public void initialize() {
        this.initialize = true;
    }
    public boolean isInitialize() {
        return this.initialize;
    }
}


text:
<x<warning descr="Non-ASCII symbols in ASCII word">Ш</warning>>
  блабла
  <t<warning descr="Non-ASCII symbols in ASCII word">Ы</warning> attr="ИИИИ23" attr2="ИИИfoo">
    <warning descr="Non-ASCII symbols in ASCII word">бла</warning>foo
  </t<warning descr="Non-ASCII symbols in ASCII word">Ы</warning>>
</x<warning descr="Non-ASCII symbols in ASCII word">Ш</warning>>