text:
/*jslint node: true*/

var Promise = require('bluebird');
var chai = require("chai"),
    expect = require("chai").expect;
var randomWords = require('random-words');

var argv = require('optimist').demand('config').argv;
var environment = argv.config;
var nconf = require('nconf');
nconf.argv().env().file({ file: 'config.json' });

var cf_api_url = nconf.get(environment + "_" + 'CF_API_URL'),
    username = nconf.get(environment + "_" + 'username'),
    password = nconf.get(environment + "_" + 'password');

var CloudController = require("../../../../lib/model/cloudcontroller/CloudController");
var CloudFoundryUsersUAA = require("../../../../lib/model/uaa/UsersUAA");
var CloudFoundryApps = require("../../../../lib/model/cloudcontroller/Apps");
var CloudFoundrySpaces = require("../../../../lib/model/cloudcontroller/Spaces");
var CloudFoundryDomains = require("../../../../lib/model/cloudcontroller/Domains");
var CloudFoundryRoutes = require("../../../../lib/model/cloudcontroller/Routes");
var CloudFoundryJobs = require("../../../../lib/model/cloudcontroller/Jobs");
var BuildPacks = require("../../../../lib/model/cloudcontroller/BuildPacks");
CloudController = new CloudController();
CloudFoundryUsersUAA = new CloudFoundryUsersUAA();
CloudFoundryApps = new CloudFoundryApps();
CloudFoundrySpaces = new CloudFoundrySpaces();
CloudFoundryDomains = new CloudFoundryDomains();
CloudFoundryRoutes = new CloudFoundryRoutes();
CloudFoundryJobs = new CloudFoundryJobs();
BuildPacks = new BuildPacks();
var HttpUtils = require('../../../../lib/utils/HttpUtils');
HttpUtils = new HttpUtils();

var fs = require('fs');
var ZipGenerator = require('../../../utils/ZipGenerator');
ZipGenerator = new ZipGenerator();

describe("Cloud Foundry Jobs", function () {
    "use strict";
    var authorization_endpoint = null;
    var token_endpoint = null;
    var token_type = null;
    var access_token = null;
    var domain_guid = null;
    var space_guid = null;

    before(function () {
        this.timeout(10000);

        CloudController.setEndPoint(cf_api_url);
        CloudFoundryApps.setEndPoint(cf_api_url);
        CloudFoundrySpaces.setEndPoint(cf_api_url);
        CloudFoundryDomains.setEndPoint(cf_api_url);
        CloudFoundryRoutes.setEndPoint(cf_api_url);
        CloudFoundryJobs.setEndPoint(cf_api_url);

        return CloudController.getInfo().then(function (result) {
            authorization_endpoint = result.authorization_endpoint;
            token_endpoint = result.token_endpoint;
            CloudFoundryUsersUAA.setEndPoint(authorization_endpoint);
            return CloudFoundryUsersUAA.login(username, password);
        }).then(function (result) {
            CloudFoundryApps.setToken(result);
            CloudFoundrySpaces.setToken(result);
            CloudFoundryDomains.setToken(result);
            CloudFoundryRoutes.setToken(result);
            CloudFoundryJobs.setToken(result);
            return CloudFoundryDomains.getDomains();
        }).then(function (result) {
            domain_guid = result.resources[0].metadata.guid;
            return CloudFoundrySpaces.getSpaces();
        }).then(function (result) {
            space_guid = result.resources[0].metadata.guid;
        });

    });

    function randomInt(low, high) {
        return Math.floor(Math.random() * (high - low) + low);
    }

    function sleep(time, callback) {
        var stop = new Date().getTime();
        while (new Date().getTime() < stop + time) {
            ;
        }
        callback();
    }

    function createApp(appOptions) {

        var app_guid = null;
        var routeName = null;
        var route_guid = null;
        var route_create_flag = false;
        var appName = appOptions.name;

        return new Promise(function (resolve, reject) {

            var filter = {
                'q': 'name:' + appName,
                'inline-relations-depth': 1
            };

            //VALIDATIONS
            //1. Duplicated app
            return CloudFoundrySpaces.getSpaceApps(space_guid, filter).then(function (result) {

                //If exist the application, REJECT
                if (result.total_results === 1) {
                    return reject("Exist the app: " + appName);
                }

                var filter = {
                    'q': 'host:' + appName + ';domain_guid:' + domain_guid,
                    'inline-relations-depth': 1
                };
                return CloudFoundryRoutes.getRoutes(filter);
            //2. Duplicated route
            }).then(function (result) {

                if (result.total_results === 1) {
                    return reject("Exist the route:" + appName);
                }

                return CloudFoundryApps.add(appOptions).then(function (result) {
                    return new Promise(function (resolve) {
                        //console.log(result);
                        app_guid = result.metadata.guid;
                        return resolve();
                    });
                });
            }).then(function () {
                //TODO: How to make the inference?
                return CloudFoundryDomains.getSharedDomains();
            }).then(function () {
                var routeOptions = {
                    'domain_guid' : domain_guid,
                    'space_guid' : space_guid,
                    'host' : appName
                };
                return CloudFoundryRoutes.add(routeOptions).then(function (result) {
                    return new Promise(function (resolve) {
                        route_guid = result.metadata.guid;
                        return resolve(result);
                    });
                });
            }).then(function () {
                return CloudFoundryApps.associateRoute(app_guid, route_guid);
            }).then(function (result) {
                return resolve(result);
            }).catch(function (reason) {
                console.error("Error: " + reason);
                return reject(reason);
            });

        });

    }

    function recursiveCheckJobState(job_guid) {
        var counter = 0;
        var maximumLoops = 15;

        return new Promise(function check(resolve, reject) {

            CloudFoundryJobs.getJob(job_guid).then(function (result) {
                console.log(result.entity.status);
                //console.log(counter);
                if (result.entity.status === "finished") {
                    resolve(result);
                } else if (counter === maximumLoops) {
                    reject(new Error("Timeout Job"));
                } else {
                    //console.log("next try");
                    counter += 1;
                    setTimeout(check, 1000, resolve, reject);
                }
            });

        });

    }

    it("Create a Static App, Upload 1MB (async = false) zip & Remove app", function () {
        this.timeout(40000);

        var app_guid = null;
        var appName = "app2" + randomWords() + randomInt(1, 100);
        var staticBuildPack = BuildPacks.get("static");
        var zipPath = "./staticApp.zip";
        var weight = 1;//MB
        var compressionRate = 0;//No compression
        var job_guid = null;
        var job_status = null;
        var route_guid = null;
        var appOptions = {
            "name": appName,
            "space_guid": space_guid,
            "instances" : 1,
            "memory" : 32,
            "disk_quota" : 32,
            "buildpack" : staticBuildPack
        };

        return createApp(appOptions).then(function (result) {
            app_guid = result.metadata.guid;
            expect(app_guid).is.a("string");
            expect(result.entity.buildpack).to.equal(staticBuildPack);
            return ZipGenerator.generate(zipPath, weight, compressionRate);
        }).then(function () {
            //Does exist the zip?
            fs.exists(zipPath, function (result) {
                expect(result).to.equal(true);
            });
            return CloudFoundryApps.upload(app_guid, zipPath, true);
        }).then(function (result) {
            expect(result.metadata.guid).to.be.a('string');

            job_guid = result.metadata.guid;
            job_status = result.entity.status;

            return ZipGenerator.remove(zipPath);
        }).then(function (result) {
            fs.exists(zipPath, function (result) {
                expect(result).be.equal(false);
            });

            return recursiveCheckJobState(job_guid);
        }).then(function (result) {
            expect(result.metadata.guid).to.be.a('string');

            return CloudFoundryApps.getAppRoutes(app_guid);
        }).then(function (result) {
            route_guid = result.resources[0].metadata.guid;
            return CloudFoundryApps.remove(app_guid);
        }).then(function () {
            return CloudFoundryRoutes.remove(route_guid);
        }).then(function () {
            //console.log(result);
            expect(true).to.equal(true);
        });

    });

    it.skip("[OLD] Create a Static App, Upload 1MB (async = false) zip & Remove app", function () {
        this.timeout(40000);

        var app_guid = null;
        var appName = "app2" + randomWords() + randomInt(1, 100);
        var staticBuildPack = BuildPacks.get("static");
        var zipPath = "./staticApp.zip";
        var weight = 1;//MB
        var compressionRate = 0;//No compression
        var job_guid = null;
        var job_status = null;
        var route_guid = null;
        var appOptions = {
            "name": appName,
            "space_guid": space_guid,
            "instances" : 1,
            "memory" : 32,
            "disk_quota" : 32,
            "buildpack" : staticBuildPack
        };

        return createApp(appOptions).then(function (result) {
            app_guid = result.metadata.guid;
            expect(app_guid).is.a("string");
            expect(result.entity.buildpack).to.equal(staticBuildPack);
            return ZipGenerator.generate(zipPath, weight, compressionRate);
        }).then(function () {
            //Does exist the zip?
            fs.exists(zipPath, function (result) {
                expect(result).to.equal(true);
            });
            return CloudFoundryApps.upload(app_guid, zipPath, true);
        }).then(function (result) {
            expect(result.metadata.guid).to.be.a('string');

            job_guid = result.metadata.guid;
            job_status = result.entity.status;

            return ZipGenerator.remove(zipPath);
        }).then(function (result) {
            fs.exists(zipPath, function (result) {
                expect(result).be.equal(false);
            });

            if (job_status === "queued") {

                sleep(5000, function () {
                    console.log("5 second");
                });

                return CloudFoundryJobs.getJob(job_guid).then(function (result) {
                    return new Promise(function (resolve) {
                        var status = result.entity.status;
                        console.log(status);
                        resolve(result);
                    });
                });

            }

            return new Promise(function (resolve) {
                resolve(result);
            });

        }).then(function (result) {
            expect(result.metadata.guid).to.be.a('string');

            //console.log(result);
            job_guid = result.metadata.guid;
            job_status = result.entity.status;
            //console.log(result.metadata.guid);
            //console.log(result.entity.status);

            if (job_status === "queued") {

                sleep(5000, function () {
                    console.log("5 second");
                });

                return CloudFoundryJobs.getJob(job_guid).then(function (result) {
                    return new Promise(function (resolve) {
                        var status = result.entity.status;
                        console.log(status);
                        resolve(result);
                    });
                });
            }

            return new Promise(function (resolve) {
                resolve(result);
            });

        }).then(function (result) {
            expect(result.metadata.guid).to.be.a('string');

            job_guid = result.metadata.guid;
            job_status = result.entity.status;
            //console.log(result.metadata.guid);
            //console.log(result.entity.status);

            if (job_status === "queued") {

                sleep(5000, function () {
                    console.log("5 second");
                });

                return CloudFoundryJobs.getJob(job_guid).then(function (result) {
                    return new Promise(function (resolve) {
                        var status = result.entity.status;
                        console.log(status);
                        resolve(result);
                    });
                });

            }

            return new Promise(function (resolve) {
                resolve(result);
            });

        }).then(function () {
            return CloudFoundryApps.getAppRoutes(app_guid);
        }).then(function (result) {
            route_guid = result.resources[0].metadata.guid;
            return CloudFoundryApps.remove(app_guid);
        }).then(function () {
            return CloudFoundryRoutes.remove(route_guid);
        }).then(function () {
            //console.log(result);
            expect(true).to.equal(true);
        });

    });

});


text:
package com.mossle.api.cms;

import com.mossle.core.page.Page;

public interface CmsConnector {
    /**
     * 根据code获得catalog分类.
     */
    CatalogDTO findCatalogByCode(String code, String tenantId);

    /**
     * 获取分类下文章.
     */
    Page findArticles(String code, String tenantId, int pageNo, int pageSize);

    /**
     * 只返回分页信息,不返回数据.
     */
    Page findArticlePageInfo(String code, String tenantId, int pageNo,
            int pageSize);

    /**
     * 根据id获取一个article文章.
     */
    ArticleDTO findArticleById(String id);

    /**
     * 获取对应文章的评论.
     */
    Page findComments(String id, int pageNo, int pageSize);

    /**
     * 只返回分页信息,不返回数据.
     */
    Page findCommentPageInfo(String id, int pageNo, int pageSize);

    /**
     * 添加评论.
     */
    void addComment(String articleId, String content, String userId);
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Duplicates a dashboard.
 *
 * @param integer $id The dashboard to duplicate
 * @param string $name The name of the new chunk.
 *
 * @var modX $modx
 * @var array $scriptProperties
 * @var modProcessor $this
 *
 * @package modx
 * @subpackage processors.system.dashboard
 */
class modDashboardDuplicateProcessor extends modObjectDuplicateProcessor {
    public $classKey = 'modDashboard';
    public $languageTopics = array('dashboards');
    public $permission = 'dashboards';
    public $objectType = 'dashboard';

    public function beforeSave() {
        $this->duplicatePlacements();
        return parent::beforeSave();
    }

    public function duplicatePlacements() {
        $oldPlacements = $this->modx->getCollection('modDashboardWidgetPlacement',array(
            'dashboard' => $this->object->get('id'),
        ));
        $placements = array();
        /** @var modDashboardWidgetPlacement $placement */
        foreach ($oldPlacements as $placement) {
            /** @var modDashboardWidgetPlacement $placementCopy */
            $placementCopy = $this->modx->newObject('modDashboardWidgetPlacement');
            $placementCopy->fromArray(array(
                'widget' => $placement->get('widget'),
                'rank' => $placement->get('rank'),
            ),'',true,true);
            $placements[] = $placementCopy;
        }
        $this->newObject->addMany($placements);
    }
}
return 'modDashboardDuplicateProcessor';


text:
<?php
/**
 * The template for Managing Theme Structure
 *
 * @package Catch Themes
 * @subpackage Catch Responsive
 * @since Catch Responsive 1.0
 */

if ( ! defined( 'CATCHRESPONSIVE_THEME_VERSION' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit();
}

if ( ! function_exists( 'catchresponsive_doctype' ) ) :
	/**
	 * Doctype Declaration
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_doctype() {
		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
		<?php
	}
endif;
add_action( 'catchresponsive_doctype', 'catchresponsive_doctype', 10 );

if ( ! function_exists( 'catchresponsive_head' ) ) :
	/**
	 * Header Codes
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_head() {
		?>
		<meta charset="<?php bloginfo( 'charset' ); ?>">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="profile" href="http://gmpg.org/xfn/11">
		<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

		<?php
	}
endif;
add_action( 'catchresponsive_before_wp_head', 'catchresponsive_head', 10 );

if ( ! function_exists( 'catchresponsive_doctype_start' ) ) :
	/**
	 * Start div id #page
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_page_start() {
		?>

		<?php
	}
endif;
add_action( 'catchresponsive_header', 'catchresponsive_page_start', 10 );

if ( ! function_exists( 'catchresponsive_page_end' ) ) :
	/**
	 * End div id #page
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_page_end() {
		?>

		<?php
	}
endif;
add_action( 'catchresponsive_footer', 'catchresponsive_page_end', 200 );

if ( ! function_exists( 'catchresponsive_header_start' ) ) :
	/**
	 * Start Header id #masthead and class .wrapper
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_header_start() {
		?>

		<?php
	}
endif;
add_action( 'catchresponsive_header', 'catchresponsive_header_start', 20 );

if ( ! function_exists( 'catchresponsive_header_end' ) ) :
	/**
	 * End Header id #masthead and class .wrapper
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_header_end() {
		?>

		<?php
	}
endif;
add_action( 'catchresponsive_header', 'catchresponsive_header_end', 100 );

if ( ! function_exists( 'catchresponsive_content_start' ) ) :
	/**
	 * Start div id #content and class .wrapper
	 *
	 * @since Catch Responsive 1.0
	 *
	 */
	function catchresponsive_content_start() {
		?>

	<?php
	}
endif;
add_action('catchresponsive_content', 'catchresponsive_content_start', 10 );

if ( ! function_exists( 'catchresponsive_content_end' ) ) :
	/**
	 * End div id #content and class .wrapper
	 *
	 * @since Catch Responsive 1.0
	 */
	function catchresponsive_content_end() {
		?>

		<?php
	}

endif;
add_action( 'catchresponsive_after_content', 'catchresponsive_content_end', 30 );

if ( ! function_exists( 'catchresponsive_footer_content_start' ) ) :
/**
 * Start footer id #colophon
 *
 * @since Catch Responsive 1.0
 */
function catchresponsive_footer_content_start() {
	?>

    <?php
}
endif;
add_action( 'catchresponsive_footer', 'catchresponsive_footer_content_start', 30 );

if ( ! function_exists( 'catchresponsive_footer_sidebar' ) ) :
/**
 * Footer Sidebar
 *
 * @since Catch Responsive 1.0
 */
function catchresponsive_footer_sidebar() {
	get_sidebar( 'footer' );
}
endif;
add_action( 'catchresponsive_footer', 'catchresponsive_footer_sidebar', 40 );

if ( ! function_exists( 'catchresponsive_footer_content_end' ) ) :
/**
 * End footer id #colophon
 *
 * @since Catch Responsive 1.0
 */
function catchresponsive_footer_content_end() {
	?>

	<?php
}
endif;
add_action( 'catchresponsive_footer', 'catchresponsive_footer_content_end', 110 );

if ( ! function_exists( 'catchresponsive_header_right' ) ) :
/**
 * Shows Header Right Social Icon
 *
 * @since Catch Responsive 1.0
 */
function catchresponsive_header_right() { ?>

				<?php echo get_search_form(); ?>

		<?php if ( '' != ( $catchresponsive_social_icons = catchresponsive_get_social_icons() ) ) { ?>

					<?php echo $catchresponsive_social_icons; ?>

		<?php
		} ?>

<?php
}
endif;
add_action( 'catchresponsive_header', 'catchresponsive_header_right', 60 );


text:
void _YKCGContextDrawStyledRect(CGContextRef context, CGRect rect, YKUIBorderStyle style, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius);
void _YKCGContextDrawImage(CGContextRef context, CGImageRef image, CGSize imageSize, CGRect rect, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius, UIViewContentMode contentMode, CGColorRef backgroundColor, CGColorRef shadowColor, CGFloat shadowBlur);
void _horizontalEdgeColorBlendFunctionImpl(void *info, const CGFloat *in, CGFloat *out, BOOL reverse);
void _metalEdgeColorBlendFunctionImpl(void *info, const CGFloat *in, CGFloat *out);
void _horizontalEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out);
void _horizontalReverseEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out);
void _metalEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out);
void _linearColorBlendFunction(void *info, const CGFloat *in, CGFloat *out);
void _exponentialColorBlendFunction(void *info, const CGFloat *in, CGFloat *out);
void _colorReleaseInfoFunction(void *info);

const CGPoint YKCGPointNull = {CGFLOAT_MAX, CGFLOAT_MAX};

bool YKCGPointIsNull(CGPoint point) {
  return point.x == YKCGPointNull.x && point.y == YKCGPointNull.y;
}

const CGSize YKCGSizeNull = {CGFLOAT_MAX, CGFLOAT_MAX};

bool YKCGSizeIsNull(CGSize size) {
  return size.width == YKCGSizeNull.width && size.height == YKCGSizeNull.height;
}

CGPathRef YKCGPathCreateLine(CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2) {
  CGMutablePathRef path = CGPathCreateMutable();
  CGPathMoveToPoint(path, NULL, x1, y1);
  CGPathAddLineToPoint(path, NULL, x2, y2);
  return path;
}

CGPathRef YKCGPathCreateRoundedRect(CGRect rect, CGFloat strokeWidth, CGFloat cornerRadius) {

  // TODO: Switch to UIBezierPath?
  // UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
  // return path.CGPath;

  CGMutablePathRef path = CGPathCreateMutable();

  CGFloat fw, fh;

  CGRect insetRect = CGRectInset(rect, strokeWidth/2.0, strokeWidth/2.0);
  CGFloat cornerWidth = cornerRadius, cornerHeight = cornerRadius;

  CGAffineTransform transform = CGAffineTransformIdentity;
  transform = CGAffineTransformTranslate(transform, CGRectGetMinX(insetRect), CGRectGetMinY(insetRect));
  transform = CGAffineTransformScale(transform, cornerWidth, cornerHeight);

  fw = CGRectGetWidth(insetRect) / cornerWidth;
  fh = CGRectGetHeight(insetRect) / cornerHeight;
  CGPathMoveToPoint(path, &transform, fw, fh/2);
  CGPathAddArcToPoint(path, &transform, fw, fh, fw/2, fh, 1);
  CGPathAddArcToPoint(path, &transform, 0, fh, 0, fh/2, 1);
  CGPathAddArcToPoint(path, &transform, 0, 0, fw/2, 0, 1);
  CGPathAddArcToPoint(path, &transform, fw, 0, fw, fh/2, 1);
  CGPathCloseSubpath(path);

  return path;
}

void YKCGContextAddRoundedRect(CGContextRef context, CGRect rect, CGFloat strokeWidth, CGFloat cornerRadius) {
  CGPathRef path = YKCGPathCreateRoundedRect(rect, strokeWidth, cornerRadius);
  CGContextAddPath(context, path);
  CGPathRelease(path);
}

void YKCGContextDrawPath(CGContextRef context, CGPathRef path, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth) {
  if (fillColor != NULL) CGContextSetFillColorWithColor(context, fillColor);
  if (strokeColor != NULL) CGContextSetStrokeColorWithColor(context, strokeColor);
  CGContextSetLineWidth(context, strokeWidth);
  CGContextAddPath(context, path);
  if (strokeColor != NULL && fillColor != NULL) CGContextDrawPath(context, kCGPathFillStroke);
  else if (strokeColor == NULL && fillColor != NULL) CGContextDrawPath(context, kCGPathFill);
  else if (strokeColor != NULL && fillColor == NULL) CGContextDrawPath(context, kCGPathStroke);
}

void YKCGContextDrawRoundedRect(CGContextRef context, CGRect rect, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius) {
  CGPathRef path = YKCGPathCreateRoundedRect(rect, strokeWidth, cornerRadius);
  YKCGContextDrawPath(context, path, fillColor, strokeColor, strokeWidth);
  CGPathRelease(path);
}

void YKCGContextAddLine(CGContextRef context, CGFloat x, CGFloat y, CGFloat x2, CGFloat y2) {
  CGContextMoveToPoint(context, x, y);
  CGContextAddLineToPoint(context, x2, y2);
}

void YKCGContextDrawLine(CGContextRef context, CGFloat x, CGFloat y, CGFloat x2, CGFloat y2, CGColorRef strokeColor, CGFloat strokeWidth) {
  CGContextBeginPath(context);
  YKCGContextAddLine(context, x, y, x2, y2);
  if (strokeColor != NULL) CGContextSetStrokeColorWithColor(context, strokeColor);
  CGContextSetLineWidth(context, strokeWidth);
  CGContextStrokePath(context);
}

void YKCGContextDrawImage(CGContextRef context, CGImageRef image, CGSize imageSize, CGRect rect, CGColorRef strokeColor, CGFloat strokeWidth,
                          UIViewContentMode contentMode, CGColorRef backgroundColor) {
  _YKCGContextDrawImage(context, image, imageSize, rect, strokeColor, strokeWidth, 0.0, contentMode, backgroundColor, NULL, 0);
}

void YKCGContextDrawRoundedRectImage(CGContextRef context, CGImageRef image, CGSize imageSize, CGRect rect, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius, UIViewContentMode contentMode, CGColorRef backgroundColor) {
  YKCGContextDrawRoundedRectImageWithShadow(context, image, imageSize, rect, strokeColor, strokeWidth, cornerRadius, contentMode, backgroundColor, NULL, 0);
}

void YKCGContextDrawRoundedRectImageWithShadow(CGContextRef context, CGImageRef image, CGSize imageSize, CGRect rect, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius, UIViewContentMode contentMode, CGColorRef backgroundColor, CGColorRef shadowColor, CGFloat shadowBlur) {
  CGContextSaveGState(context);
  _YKCGContextDrawImage(context, image, imageSize, rect, strokeColor, strokeWidth, cornerRadius, contentMode, backgroundColor, shadowColor, shadowBlur);
  CGContextRestoreGState(context);
}

void _YKCGContextDrawImage(CGContextRef context, CGImageRef image, CGSize imageSize, CGRect rect, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius, UIViewContentMode contentMode, CGColorRef backgroundColor, CGColorRef shadowColor, CGFloat shadowBlur) {

  // Clip for rounded corners
  if (cornerRadius > 0) {
    YKCGContextAddRoundedRect(context, rect, 0, cornerRadius);
    CGContextClip(context);
  }

  // Fill background color
  if (backgroundColor != NULL) {
    CGContextSetFillColorWithColor(context, backgroundColor);
    CGContextFillRect(context, rect);
  }

  CGRect imageBounds = YKCGRectConvert(rect, imageSize, contentMode);
  if (image == NULL) imageBounds = rect;

  if (image != NULL) {
    CGContextSaveGState(context);
    // Flip coordinate system, otherwise image will be drawn upside down
    CGContextTranslateCTM (context, 0, imageBounds.size.height);
    CGContextScaleCTM (context, 1.0, -1.0);
    imageBounds.origin.y *= -1; // Going opposite direction
    CGContextDrawImage(context, imageBounds, image);
    CGContextRestoreGState(context);
  }

  if (shadowColor != NULL) {
    YKCGContextDrawBorderWithShadow(context, rect, YKUIBorderStyleRounded, NULL, strokeColor, strokeWidth, 0, cornerRadius, shadowColor, shadowBlur);
  } else if (strokeColor != NULL && strokeWidth > 0) {
    YKCGContextDrawRoundedRect(context, rect, NULL, strokeColor, strokeWidth, cornerRadius);
  }
}

CGRect YKCGRectScaleAspectAndCenter(CGSize size, CGSize inSize, BOOL fill) {
  if (YKCGSizeIsEmpty(size)) return CGRectZero;

  CGRect rect;
  CGFloat widthScaleRatio = inSize.width / size.width;
  CGFloat heightScaleRatio = inSize.height / size.height;

  if (widthScaleRatio < heightScaleRatio) {
    if (fill) {
      CGFloat height = inSize.height;
      CGFloat width = roundf(size.width * heightScaleRatio);
      CGFloat x = roundf((inSize.width - width) / 2.0);
      rect = CGRectMake(x, 0, width, height);
    } else {
      CGFloat height = roundf(size.height * widthScaleRatio);
      CGFloat y = roundf((inSize.height / 2.0) - (height / 2.0));
      rect = CGRectMake(0, y, inSize.width, height);
    }
  } else {
    if (fill) {
      CGFloat width = inSize.width;
      CGFloat height = roundf(size.height * widthScaleRatio);
      CGFloat y = roundf((inSize.height - height) / 2.0);
      rect = CGRectMake(0, y, width, height);
    } else {
      CGFloat width = roundf(size.width * heightScaleRatio);
      CGFloat x = roundf((inSize.width / 2.0) - (width / 2.0));
      rect = CGRectMake(x, 0, width, inSize.height);
    }
  }
  return rect;
}

BOOL YKCGPointIsZero(CGPoint p) {
  return (YKIsEqualWithAccuracy(p.x, 0, 0.0001) && YKIsEqualWithAccuracy(p.y, 0, 0.0001));
}

BOOL YKCGPointIsEqual(CGPoint p1, CGPoint p2) {
  return (YKIsEqualWithAccuracy(p1.x, p2.x, 0.0001) && YKIsEqualWithAccuracy(p1.y, p2.y, 0.0001));
}

BOOL YKCGRectIsEqual(CGRect rect1, CGRect rect2) {
  return (YKCGPointIsEqual(rect1.origin, rect2.origin) && YKCGSizeIsEqual(rect1.size, rect2.size));
}

CGPoint YKCGPointToCenterY(CGSize size, CGSize inSize) {
  CGPoint p = CGPointMake(0, roundf((inSize.height - size.height) / 2.0));
  if (p.y < 0) p.y = 0;
  return p;
}

CGPoint YKCGPointToCenter(CGSize size, CGSize inSize) {
  // We round otherwise views will anti-alias
  CGPoint p = CGPointMake(roundf((inSize.width - size.width) / 2.0), roundf((inSize.height - size.height) / 2.0));
  // Allowing negative values here allows us to center a larger view on a smaller view.
  // Though set to 0 if inSize.height was 0
  if (inSize.height == 0) p.y = 0;
  return p;
}

CGPoint YKCGPointToRight(CGSize size, CGSize inSize) {
  CGPoint p = CGPointMake(inSize.width - size.width, roundf(inSize.height / 2.0 - size.height / 2.0));
  if (p.x < 0) p.x = 0;
  if (p.y < 0) p.y = 0;
  return p;
}

BOOL YKCGSizeIsEqual(CGSize size1, CGSize size2) {
  return (YKIsEqualWithAccuracy(size1.height, size2.height, 0.0001) && YKIsEqualWithAccuracy(size1.width, size2.width, 0.0001));
}

BOOL YKCGSizeIsZero(CGSize size) {
  return (size.width == 0 && size.height == 0);
}

BOOL YKCGSizeIsEmpty(CGSize size) {
  return (YKIsEqualWithAccuracy(size.height, 0, 0.0001) && YKIsEqualWithAccuracy(size.width, 0, 0.0001));
}

CGRect YKCGRectToCenter(CGSize size, CGSize inSize) {
  CGPoint p = YKCGPointToCenter(size, inSize);
  return CGRectMake(p.x, p.y, size.width, size.height);
}

CGRect YKCGRectToCenterInRect(CGSize size, CGRect inRect) {
  CGPoint p = YKCGPointToCenter(size, inRect.size);
  return CGRectMake(p.x + inRect.origin.x, p.y + inRect.origin.y, size.width, size.height);
}

CGRect YKCGRectToCenterY(CGRect rect, CGRect inRect) {
  CGPoint centeredPoint = YKCGPointToCenter(rect.size, inRect.size);
  return YKCGRectSetY(rect, centeredPoint.y);
}

CGFloat YKCGFloatToCenter(CGFloat length, CGFloat inLength, CGFloat min) {
  CGFloat pos = roundf(inLength / 2.0 - length / 2.0);
  if (pos < min) pos = min;
  return pos;
}

CGRect YKCGRectAdd(CGRect rect1, CGRect rect2) {
  return CGRectMake(rect1.origin.x + rect2.origin.x, rect1.origin.y + rect2.origin.y, rect1.size.width + rect2.size.width, rect1.size.height + rect2.size.height);
}

CGRect YKCGRectRightAlign(CGFloat y, CGFloat width, CGFloat inWidth, CGFloat maxWidth, CGFloat padRight, CGFloat height) {
  if (width > maxWidth) width = maxWidth;
  CGFloat x = (inWidth - width - padRight);
  return CGRectMake(x, y, width, height);
}

CGRect YKCGRectZeroOrigin(CGRect rect) {
  return CGRectMake(0, 0, rect.size.width, rect.size.height);
}

CGRect YKCGRectSetSize(CGRect rect, CGSize size) {
  rect.size = size;
  return rect;
}

CGRect YKCGRectSetHeight(CGRect rect, CGFloat height) {
  rect.size.height = height;
  return rect;
}

CGRect YKCGRectAddHeight(CGRect rect, CGFloat add) {
  rect.size.height += add;
  return rect;
}

CGRect YKCGRectAddX(CGRect rect, CGFloat add) {
  rect.origin.x += add;
  return rect;
}

CGRect YKCGRectAddY(CGRect rect, CGFloat add) {
  rect.origin.y += add;
  return rect;
}

CGRect YKCGRectSetWidth(CGRect rect, CGFloat width) {
  rect.size.width = width;
  return rect;
}

CGRect YKCGRectSetOrigin(CGRect rect, CGFloat x, CGFloat y) {
  rect.origin = CGPointMake(x, y);
  return rect;
}

CGRect YKCGRectSetX(CGRect rect, CGFloat x) {
  rect.origin.x = x;
  return rect;
}

CGRect YKCGRectSetY(CGRect rect, CGFloat y) {
  rect.origin.y = y;
  return rect;
}

CGRect YKCGRectSetOriginPoint(CGRect rect, CGPoint p) {
  rect.origin = p;
  return rect;
}

CGRect YKCGRectOriginSize(CGPoint origin, CGSize size) {
  CGRect rect;
  rect.origin = origin;
  rect.size = size;
  return rect;
}

CGRect YKCGRectAddPoint(CGRect rect, CGPoint p) {
  rect.origin.x += p.x;
  rect.origin.y += p.y;
  return rect;
}

CGPoint YKCGPointBottomRight(CGRect rect) {
  return CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
}

CGFloat YKCGDistanceBetween(CGPoint pointA, CGPoint pointB) {
  CGFloat dx = pointB.x - pointA.x;
  CGFloat dy = pointB.y - pointA.y;
  return sqrt(dx*dx + dy*dy);
}

CGRect YKCGRectWithInsets(CGSize size, UIEdgeInsets insets) {
  CGRect rect = CGRectZero;
  rect.origin.x = insets.left;
  rect.origin.y = insets.top;
  rect.size.width = size.width - insets.left - insets.right;
  rect.size.height = size.height - insets.top - insets.bottom;
  return rect;
}

#pragma mark Border Styles

void YKCGContextAddStyledRect(CGContextRef context, CGRect rect, YKUIBorderStyle style, CGFloat strokeWidth, CGFloat alternateStrokeWidth, CGFloat cornerRadius) {
  CGPathRef path = YKCGPathCreateStyledRect(rect, style, strokeWidth, alternateStrokeWidth, cornerRadius);
  CGContextAddPath(context, path);
  CGPathRelease(path);
}

CGPathRef YKCGPathCreateStyledRect(CGRect rect, YKUIBorderStyle style, CGFloat strokeWidth, CGFloat alternateStrokeWidth, CGFloat cornerRadius) {

  CGFloat fw, fh;
  CGFloat cornerWidth = cornerRadius, cornerHeight = cornerRadius;

  // Handle case where we have 0 corner radius
  if (cornerRadius == 0 && style == YKUIBorderStyleRounded) {
    style = YKUIBorderStyleNormal;
  }

  if (style == YKUIBorderStyleRounded) {
    return YKCGPathCreateRoundedRect(rect, strokeWidth, cornerRadius);
  }

  CGFloat strokeInset = strokeWidth/2.0;
  CGFloat alternateStrokeInset = alternateStrokeWidth/2.0;

  // Need to adjust path rect to inset (since the stroke is drawn from the middle of the path)
  CGRect insetBounds;
  switch(style) {
    case YKUIBorderStyleRoundedBottomWithAlternateTop:
      insetBounds = CGRectMake(rect.origin.x + strokeInset, rect.origin.y + alternateStrokeInset, rect.size.width - (strokeInset * 2), rect.size.height - strokeInset - alternateStrokeInset);
      break;

    case YKUIBorderStyleLeftRightWithAlternateTop:
      insetBounds = CGRectMake(rect.origin.x + strokeInset, rect.origin.y + alternateStrokeInset, rect.size.width - (strokeInset * 2), rect.size.height - alternateStrokeInset);
      break;

    case YKUIBorderStyleRoundedTop:
    case YKUIBorderStyleRoundedTopOnly:
      insetBounds = CGRectMake(rect.origin.x + strokeInset, rect.origin.y + strokeInset, rect.size.width - (strokeInset * 2), rect.size.height - strokeInset);
      break;

    case YKUIBorderStyleTopOnly:
      insetBounds = CGRectMake(rect.origin.x, rect.origin.y + strokeInset, rect.size.width, rect.size.height - strokeInset);
      break;

    case YKUIBorderStyleTopBottom:
      insetBounds = CGRectMake(rect.origin.x, rect.origin.y + strokeInset, rect.size.width, rect.size.height - (strokeInset * 2));
      break;

    case YKUIBorderStyleBottomOnly:
      insetBounds = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height - strokeInset);
      break;

    case YKUIBorderStyleNormal:
    case YKUIBorderStyleRounded:
    case YKUIBorderStyleRoundedLeftCap:
    case YKUIBorderStyleRoundedRightCap:
      insetBounds = CGRectMake(rect.origin.x + strokeInset, rect.origin.y + strokeInset, rect.size.width - (strokeInset * 2), rect.size.height - (strokeInset * 2));
      break;

    case YKUIBorderStyleNone:
      insetBounds = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
      break;
  }
  rect = insetBounds;

  CGAffineTransform transform = CGAffineTransformIdentity;
  transform = CGAffineTransformTranslate(transform, CGRectGetMinX(rect), CGRectGetMinY(rect));
  if (cornerWidth > 0 && cornerHeight > 0) {
    transform = CGAffineTransformScale(transform, cornerWidth, cornerHeight);
    fw = CGRectGetWidth(rect) / cornerWidth;
    fh = CGRectGetHeight(rect) / cornerHeight;
  } else {
    fw = CGRectGetWidth(rect);
    fh = CGRectGetHeight(rect);
  }

  CGMutablePathRef path = CGPathCreateMutable();

  switch(style) {
    case YKUIBorderStyleRoundedBottomWithAlternateTop:
      CGPathMoveToPoint(path, &transform, fw, 0);
      CGPathAddLineToPoint(path, &transform, fw, fh/2);
      CGPathAddArcToPoint(path, &transform, fw, fh, fw/2, fh, 1);
      CGPathAddArcToPoint(path, &transform, 0, fh, 0, fh/2, 1);
      CGPathAddLineToPoint(path, &transform, 0, 0);
      CGPathMoveToPoint(path, &transform, fw, 0); // Don't draw top border
      break;

    case YKUIBorderStyleRoundedTop:
      CGPathMoveToPoint(path, &transform, 0, fh);
      CGPathAddLineToPoint(path, &transform, 0, fh/2);
      CGPathAddArcToPoint(path, &transform, 0, 0, fw/2, 0, 1);
      CGPathAddArcToPoint(path, &transform, fw, 0, fw, fh/2, 1);
      CGPathAddLineToPoint(path, &transform, fw, fh);
      CGPathMoveToPoint(path, &transform, 0, fh); // Don't draw bottom border
      break;

    case YKUIBorderStyleRoundedTopOnly:
      CGPathMoveToPoint(path, &transform, 0, 1);
      CGPathAddArcToPoint(path, &transform, 0, 0, fw/2, 0, 1);
      CGPathAddArcToPoint(path, &transform, fw, 0, fw, fh/2, 1);
      CGPathMoveToPoint(path, &transform, fw, fh);
      break;

    case YKUIBorderStyleTopOnly:
      CGPathMoveToPoint(path, &transform, fw, 0);
      CGPathAddLineToPoint(path, &transform, 0, 0);
      break;

    case YKUIBorderStyleBottomOnly:
      CGPathMoveToPoint(path, &transform, fw, fh);
      CGPathAddLineToPoint(path, &transform, 0, fh);
      break;

    case YKUIBorderStyleTopBottom:
      CGPathMoveToPoint(path, &transform, 0, 0);
      CGPathAddLineToPoint(path, &transform, fw, 0);
      CGPathMoveToPoint(path, &transform, fw, fh);
      CGPathAddLineToPoint(path, &transform, 0, fh);
      break;

    case YKUIBorderStyleLeftRightWithAlternateTop:
      // Go +/- 2 in order to clip the top and bottom border; Only draw left, right border
      CGPathMoveToPoint(path, &transform, 0, fh + 2);
      CGPathAddLineToPoint(path, &transform, 0, -2);
      CGPathAddLineToPoint(path, &transform, fw, -2);
      CGPathAddLineToPoint(path, &transform, fw, fh + 2);
      CGPathAddLineToPoint(path, &transform, 0, fh + 2);
      break;

    case YKUIBorderStyleNormal:
      CGPathMoveToPoint(path, &transform, 0, fh);
      CGPathAddLineToPoint(path, &transform, 0, 0);
      CGPathAddLineToPoint(path, &transform, fw, 0);
      CGPathAddLineToPoint(path, &transform, fw, fh);
      CGPathAddLineToPoint(path, &transform, 0, fh);
      break;

    case YKUIBorderStyleRoundedLeftCap:
      CGPathMoveToPoint(path, &transform, 0, fh/2);
      CGPathAddArcToPoint(path, &transform, 0, 0, fw/2, 0, 1);
      CGPathAddLineToPoint(path, &transform, fw, 0);
      CGPathAddLineToPoint(path, &transform, fw, fh);
      CGPathAddLineToPoint(path, &transform, fw/2, fh);
      CGPathAddArcToPoint(path, &transform, 0, fh, 0, fh/2, 1);
      CGPathAddLineToPoint(path, &transform, 0, fh/2);
      break;

    case YKUIBorderStyleRoundedRightCap:
      CGPathMoveToPoint(path, &transform, 0, fh);
      CGPathAddLineToPoint(path, &transform, 0, 0);
      CGPathAddLineToPoint(path, &transform, fw/2, 0);
      CGPathAddArcToPoint(path, &transform, fw, 0, fw, fh/2, 1);
      CGPathAddArcToPoint(path, &transform, fw, fh, fw/2, fh, 1);
      CGPathAddLineToPoint(path, &transform, 0, fh);
      break;

    case YKUIBorderStyleRounded:
      // Drawn in different method
      break;

    case YKUIBorderStyleNone:
      break;
  }

  return path;
}

BOOL YKCGContextAddAlternateBorderToPath(CGContextRef context, CGRect rect, YKUIBorderStyle style) {
  // Skip styles that don't have alternate border path
  if (style != YKUIBorderStyleRoundedBottomWithAlternateTop &&
      style != YKUIBorderStyleLeftRightWithAlternateTop) {
    return NO;
  }

  CGFloat cornerWidth = 10, cornerHeight = 10;

  CGContextSaveGState(context);
  CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
  CGContextScaleCTM (context, cornerWidth, cornerHeight);
  CGFloat fw = CGRectGetWidth(rect) / cornerWidth;

  CGContextMoveToPoint(context, 0, 0);
  CGContextAddLineToPoint(context, fw, 0);
  CGContextRestoreGState(context);
  return YES;
}

void _YKCGContextDrawStyledRect(CGContextRef context, CGRect rect, YKUIBorderStyle style, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat cornerRadius) {

  // If style is not a complete path, then we need to fill the rect as a separate operation
  if (fillColor != NULL && (style == YKUIBorderStyleTopOnly || style == YKUIBorderStyleBottomOnly || style == YKUIBorderStyleTopBottom)) {
    if (fillColor != NULL) CGContextSetFillColorWithColor(context, fillColor);
    CGContextFillRect(context, rect);
    fillColor = NULL;
  }

  CGContextSetLineWidth(context, strokeWidth);

  YKCGContextAddStyledRect(context, rect, style, strokeWidth, 0, cornerRadius);

  if (strokeColor != NULL) CGContextSetStrokeColorWithColor(context, strokeColor);
  if (fillColor != NULL) CGContextSetFillColorWithColor(context, fillColor);

  if (fillColor != NULL && strokeColor != NULL) {
    CGContextDrawPath(context, kCGPathFillStroke);
  } else if (strokeColor != NULL) {
    CGContextDrawPath(context, kCGPathStroke);
  } else if (fillColor != NULL) {
    CGContextDrawPath(context, kCGPathFill);
  }
}

void YKCGContextDrawBorder(CGContextRef context, CGRect rect, YKUIBorderStyle style, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat alternateStrokeWidth, CGFloat cornerRadius) {

  _YKCGContextDrawStyledRect(context, rect, style, fillColor, strokeColor, strokeWidth, cornerRadius);

  if (alternateStrokeWidth > 0) {
    CGContextSetLineWidth(context, alternateStrokeWidth);
    CGContextBeginPath(context);
    if (YKCGContextAddAlternateBorderToPath(context, rect, style))
      CGContextDrawPath(context, kCGPathStroke);
  }
}

void YKCGContextDrawBorderWithShadow(CGContextRef context, CGRect rect, YKUIBorderStyle style, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth, CGFloat alternateStrokeWidth, CGFloat cornerRadius, CGColorRef shadowColor, CGFloat shadowBlur) {
  CGContextSaveGState(context);
  CGContextSetShadowWithColor(context, CGSizeZero, shadowBlur, shadowColor);
  YKCGContextDrawBorder(context, rect, style, fillColor, strokeColor, strokeWidth, alternateStrokeWidth, cornerRadius);
  CGContextRestoreGState(context);
}

void YKCGContextDrawRect(CGContextRef context, CGRect rect, CGColorRef fillColor, CGColorRef strokeColor, CGFloat strokeWidth) {
  _YKCGContextDrawStyledRect(context, rect, YKUIBorderStyleNormal, fillColor, strokeColor, strokeWidth, 1);
}

#pragma mark Colors

void YKCGColorGetComponents(CGColorRef color, CGFloat *red, CGFloat *green, CGFloat *blue, CGFloat *alpha) {
  const CGFloat *components = CGColorGetComponents(color);
  *red = *green = *blue = 0.0;
  *alpha = 1.0;
  size_t num = CGColorGetNumberOfComponents(color);
  if (num <= 2) {
    *red = components[0];
    *green = components[0];
    *blue = components[0];
    if (num == 2) *alpha = components[1];
  } else if (num >= 3) {
    *red = components[0];
    *green = components[1];
    *blue = components[2];
    if (num >= 4) *alpha = components[3];
  }
}

#pragma mark Shading

//
// Portions adapted from:
// http://wilshipley.com/blog/2005/07/pimp-my-code-part-3-gradient.html
//

// For shading
typedef struct {
  CGFloat red1, green1, blue1, alpha1;
  CGFloat red2, green2, blue2, alpha2;
  CGFloat red3, green3, blue3, alpha3;
  CGFloat red4, green4, blue4, alpha4;
} _YKUIColors;

void _horizontalEdgeColorBlendFunctionImpl(void *info, const CGFloat *in, CGFloat *out, BOOL reverse) {
  _YKUIColors *colors = (_YKUIColors *)info;

  float v = *in;
  if ((!reverse && v < 0.5) || (reverse && v >= 0.5)) {
    v = (v * 2.0) * 0.3 + 0.6222;
    *out++ = 1.0 - v + colors->red1 * v;
    *out++ = 1.0 - v + colors->green1 * v;
    *out++ = 1.0 - v + colors->blue1 * v;
    *out++ = 1.0 - v + colors->alpha1 * v;
  } else {
    *out++ = colors->red2;
    *out++ = colors->green2;
    *out++ = colors->blue2;
    *out++ = colors->alpha2;
  }
}

void _metalEdgeColorBlendFunctionImpl(void *info, const CGFloat *in, CGFloat *out) {
  _YKUIColors *colors = (_YKUIColors *)info;

  float v = *in;
  if (v < 0.5) {
    v = (v * 2.0);
    *out++ = (v * colors->red2) + (1 - v) * colors->red1;
    *out++ = (v * colors->green2) + (1 - v) * colors->green1;
    *out++ = (v * colors->blue2) + (1 - v) * colors->blue1;
    *out++ = (v * colors->alpha2) + (1 - v) * colors->alpha1;
  } else {
    v = ((v - 0.5) * 2.0);
    *out++ = (v * colors->red4) + (1 - v) * colors->red3;
    *out++ = (v * colors->green4) + (1 - v) * colors->green3;
    *out++ = (v * colors->blue4) + (1 - v) * colors->blue3;
    *out++ = (v * colors->alpha4) + (1 - v) * colors->alpha3;
  }
}

void _horizontalEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out) {
  _horizontalEdgeColorBlendFunctionImpl(info, in, out, NO);
}

void _horizontalReverseEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out) {
  _horizontalEdgeColorBlendFunctionImpl(info, in, out, YES);
}

void _metalEdgeColorBlendFunction(void *info, const CGFloat *in, CGFloat *out) {
  _metalEdgeColorBlendFunctionImpl(info, in, out);
}

void _linearColorBlendFunction(void *info, const CGFloat *in, CGFloat *out) {
  _YKUIColors *colors = info;

  out[0] = (1.0 - *in) * colors->red1 + *in * colors->red2;
  out[1] = (1.0 - *in) * colors->green1 + *in * colors->green2;
  out[2] = (1.0 - *in) * colors->blue1 + *in * colors->blue2;
  out[3] = (1.0 - *in) * colors->alpha1 + *in * colors->alpha2;
}

void _exponentialColorBlendFunction(void *info, const CGFloat *in, CGFloat *out) {
  _YKUIColors *colors = info;
  float amount1 = (1.0 - powf(*in, 2));
  float amount2 = (1.0 - amount1);

  out[0] = (amount1 * colors->red1) + (amount2 * colors->red2);
  out[1] = (amount1 * colors->green1) + (amount2 * colors->green2);
  out[2] = (amount1 * colors->blue1) + (amount2 * colors->blue2);
  out[3] = (amount1 * colors->alpha1) + (amount2 * colors->alpha2);
}

void _colorReleaseInfoFunction(void *info) {
  free(info);
}

static const CGFunctionCallbacks linearFunctionCallbacks = {0, &_linearColorBlendFunction, &_colorReleaseInfoFunction};
static const CGFunctionCallbacks horizontalEdgeFunctionCallbacks = {0, &_horizontalEdgeColorBlendFunction, &_colorReleaseInfoFunction};
static const CGFunctionCallbacks horizontalReverseEdgeFunctionCallbacks = {0, &_horizontalReverseEdgeColorBlendFunction, &_colorReleaseInfoFunction};
static const CGFunctionCallbacks exponentialFunctionCallbacks = {0, &_exponentialColorBlendFunction, &_colorReleaseInfoFunction};
static const CGFunctionCallbacks metalEdgeFunctionCallbacks = {0, &_metalEdgeColorBlendFunction, &_colorReleaseInfoFunction};

void YKCGContextDrawShadingWithHeight(CGContextRef context, CGColorRef color, CGColorRef color2, CGColorRef color3, CGColorRef color4, CGFloat height, YKUIShadingType shadingType) {
  YKCGContextDrawShading(context, color, color2, color3, color4, CGPointMake(0, 0), CGPointMake(0, height), shadingType, YES, YES);
}

void YKCGContextDrawShading(CGContextRef context, CGColorRef color, CGColorRef color2, CGColorRef color3, CGColorRef color4, CGPoint start, CGPoint end, YKUIShadingType shadingType,
                            BOOL extendStart, BOOL extendEnd) {

  const CGFunctionCallbacks *callbacks;

  switch (shadingType) {
    case YKUIShadingTypeHorizontalEdge:
      callbacks = &horizontalEdgeFunctionCallbacks;
      break;
    case YKUIShadingTypeHorizontalReverseEdge:
      callbacks = &horizontalReverseEdgeFunctionCallbacks;
      break;
    case YKUIShadingTypeLinear:
      callbacks = &linearFunctionCallbacks;
      break;
    case YKUIShadingTypeExponential:
      callbacks = &exponentialFunctionCallbacks;
      break;
    case YKUIShadingTypeMetalEdge:
      callbacks = &metalEdgeFunctionCallbacks;
      break;
    default:
      return;
  }

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

  _YKUIColors *colors = malloc(sizeof(_YKUIColors));

  YKCGColorGetComponents(color, &colors->red1, &colors->green1, &colors->blue1, &colors->alpha1);
  YKCGColorGetComponents((color2 != NULL ? color2 : color), &colors->red2, &colors->green2, &colors->blue2, &colors->alpha2);
  if (color3 != NULL) {
    YKCGColorGetComponents(color3, &colors->red3, &colors->green3, &colors->blue3, &colors->alpha3);
  }
  if (color4 != NULL) {
    YKCGColorGetComponents(color4, &colors->red4, &colors->green4, &colors->blue4, &colors->alpha4);
  }

  static const CGFloat domainAndRange[8] = {0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0};

  CGFunctionRef blendFunctionRef = CGFunctionCreate(colors, 1, domainAndRange, 4, domainAndRange, callbacks);
  CGShadingRef shading = CGShadingCreateAxial(colorSpace, start, end, blendFunctionRef, extendStart, extendEnd);
  CGContextDrawShading(context, shading);
  CGShadingRelease(shading);
  CGFunctionRelease(blendFunctionRef);
  CGColorSpaceRelease(colorSpace);
}

// From Three20: UIImageAdditions#convertRect
// https://github.com/facebook/three20/blob/master/src/Three20Style/Sources/UIImageAdditions.m
CGRect YKCGRectConvert(CGRect rect, CGSize size, UIViewContentMode contentMode) {
  if (size.width != rect.size.width || size.height != rect.size.height) {
    if (contentMode == UIViewContentModeLeft) {
      return CGRectMake(rect.origin.x,
                        rect.origin.y + floor(rect.size.height/2 - size.height/2),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeRight) {
      return CGRectMake(rect.origin.x + (rect.size.width - size.width),
                        rect.origin.y + floor(rect.size.height/2 - size.height/2),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeTop) {
      return CGRectMake(rect.origin.x + floor(rect.size.width/2 - size.width/2),
                        rect.origin.y,
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeBottom) {
      return CGRectMake(rect.origin.x + floor(rect.size.width/2 - size.width/2),
                        rect.origin.y + floor(rect.size.height - size.height),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeCenter) {
      return CGRectMake(rect.origin.x + floor(rect.size.width/2 - size.width/2),
                        rect.origin.y + floor(rect.size.height/2 - size.height/2),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeBottomLeft) {
      return CGRectMake(rect.origin.x,
                        rect.origin.y + floor(rect.size.height - size.height),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeBottomRight) {
      return CGRectMake(rect.origin.x + (rect.size.width - size.width),
                        rect.origin.y + (rect.size.height - size.height),
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeTopLeft) {
      return CGRectMake(rect.origin.x,
                        rect.origin.y,
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeTopRight) {
      return CGRectMake(rect.origin.x + (rect.size.width - size.width),
                        rect.origin.y,
                        size.width, size.height);
    } else if (contentMode == UIViewContentModeScaleAspectFill) {
      CGSize imageSize = size;
      CGFloat imageRatio = imageSize.width / imageSize.height;
      CGFloat rectRatio = rect.size.width / rect.size.height;
      if (imageRatio > rectRatio) {
        imageSize.width = floorf(imageRatio * rect.size.height);
        imageSize.height = rect.size.height;
      } else {
        imageSize.height = floorf(rect.size.width / imageRatio);
        imageSize.width = rect.size.width;
      }
      return CGRectMake(rect.origin.x + floorf(rect.size.width/2 - imageSize.width/2),
                        rect.origin.y + floorf(rect.size.height/2 - imageSize.height/2),
                        imageSize.width, imageSize.height);
    } else if (contentMode == UIViewContentModeScaleAspectFit) {
      if ((size.height/size.width) < (rect.size.height/rect.size.width)) {
        size.height = floorf((size.height/size.width) * rect.size.width);
        size.width = rect.size.width;
      } else {
        size.width = floorf((size.width/size.height) * rect.size.height);
        size.height = rect.size.height;
      }
      return CGRectMake(rect.origin.x + floorf(rect.size.width/2 - size.width/2),
                        rect.origin.y + floorf(rect.size.height/2 - size.height/2),
                        size.width, size.height);
    }
  }
  return rect;
}

NSString *YKNSStringFromUIViewContentMode(UIViewContentMode contentMode) {
  switch (contentMode) {
    case UIViewContentModeScaleToFill: return @"UIViewContentModeScaleToFill";
    case UIViewContentModeScaleAspectFit: return @"UIViewContentModeScaleAspectFit";
    case UIViewContentModeScaleAspectFill: return @"UIViewContentModeScaleAspectFill";
    case UIViewContentModeRedraw: return @"UIViewContentModeRedraw";
    case UIViewContentModeCenter: return @"UIViewContentModeCenter";
    case UIViewContentModeTop: return @"UIViewContentModeTop";
    case UIViewContentModeBottom: return @"UIViewContentModeBottom";
    case UIViewContentModeLeft: return @"UIViewContentModeLeft";
    case UIViewContentModeRight: return @"UIViewContentModeRight";
    case UIViewContentModeTopLeft: return @"UIViewContentModeTopLeft";
    case UIViewContentModeTopRight: return @"UIViewContentModeTopRight";
    case UIViewContentModeBottomLeft: return @"UIViewContentModeBottomLeft";
    case UIViewContentModeBottomRight: return @"UIViewContentModeBottomRight";
  }
  return @"Unknown content mode";
}

CGRect YKCGRectScaleFromCenter(CGRect rect, CGFloat scale) {
  CGSize newRectSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale);
  return YKCGRectToCenterInRect(newRectSize, rect);
}

// Linear gradient function from Ray Wenderlich
// http://www.raywenderlich.com/2033/core-graphics-101-lines-rectangles-and-gradients
void YKCGContextDrawLinearGradient(CGContextRef context, CGRect rect, CGColorRef startColor, CGColorRef  endColor) {
  CGColorSpaceRef startColorSpace = CGColorGetColorSpace(startColor);
  CGColorSpaceRef endColorSpace = CGColorGetColorSpace(endColor);
  // Cannot draw a gradient if the color spaces are not the same
  if (startColorSpace != endColorSpace) {
    return;
  }

  CGFloat locations[] = { 0.0, 1.0 };

  NSArray *colors = [NSArray arrayWithObjects:(id)startColor, (id)endColor, nil];

  CGGradientRef gradient = CGGradientCreateWithColors(startColorSpace, (CFArrayRef) colors, locations);

  CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
  CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

  CGContextSaveGState(context);
  CGContextAddRect(context, rect);
  CGContextClip(context);
  CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
  CGContextRestoreGState(context);

  CGGradientRelease(gradient);
}

UIImage *YKCreateVerticalGradientImage(CGFloat height, CGColorRef topColor, CGColorRef bottomColor) {

  // If there are performance issues with tiling a lot of skinny images,
  // maybe this could be increased or made into a parameter
  CGFloat width = 1;

  // Create new offscreen context with desired size
  UIGraphicsBeginImageContext(CGSizeMake(width, height));

  CGContextRef context = UIGraphicsGetCurrentContext();

  YKCGContextDrawRect(context, CGRectMake(0, 0, width, height), [UIColor whiteColor].CGColor, [UIColor whiteColor].CGColor, 0.0);
  YKCGContextDrawLinearGradient(context, CGRectMake(0, 0, width, height), topColor, bottomColor);

  // assign context to UIImage
  UIImage *outputImg = UIGraphicsGetImageFromCurrentImageContext();

  // end context
  UIGraphicsEndImageContext();

  return outputImg;
}

UIImage *YKCGContextRoundedMask(CGRect rect, CGFloat cornerRadius) {
  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  CGContextRef context = CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
  CGColorSpaceRelease(colorSpace);

  if (context == NULL) {
    return NULL;
  }

  CGContextBeginPath(context);
  CGContextSetGrayFillColor(context, 1.0, 0.0);
  CGContextAddRect(context, rect);
  CGContextClosePath(context);
  CGContextDrawPath(context, kCGPathFill);

  CGContextSetGrayFillColor(context, 1.0, 1.0);
  CGPathRef path = YKCGPathCreateRoundedRect(rect, 0.0, cornerRadius);
  CGContextAddPath(context, path);
  CGPathRelease(path);
  CGContextDrawPath(context, kCGPathFill);

  CGImageRef bitmapContext = CGBitmapContextCreateImage(context);
  CGContextRelease(context);

  UIImage *image = [UIImage imageWithCGImage:bitmapContext];
  CGImageRelease(bitmapContext);
  return image;
}


text:
body {
    min-width: 0px;
    padding: 0;
    margin: 0;
    background: #fff;
}

.admin_all{
  background: none #fff!important;
}

.admin_content{
  margin-bottom:0!important;
}

.header_logo{
    float: none;
    overflow: hidden;
    width: 635px;
    margin: 0 auto;
}

.contentsections_bottom, .footer-dialog{
    display: none;
}

.admin_popup{
    background: #fff;
}

.admin_popup .header_logo .logo{
    padding: 0;
}

.admin_popup .main{
    padding: 0;
}

.admin_popup .middle-content{
    box-shadow:none;
    margin-top: 0;
}

.admin_popup .tabs{
    width: 100%;
}

.admin_popup .box input.small_input[type="text"]{
    width: 100px;
}

.admin_popup .box input.category[type="text"]{
    width: 230px;
}

.admin_popup .tab_general_content .input_field_1 .search_options label{
    display: block;
    float: left;
    padding: 0;
    width: 175px !important;
    line-height: auto;
}

.admin_popup .search_options{
    width: 370px;
    float: left;
}

.admin_popup .tab_general_content .input_field_1 label, .admin_popup .tab_general_content .input_field_0 label{
    width: 190px;
}

.admin_popup .box{
    padding: 5px 0;
    margin: 0;
}

.admin_popup .box#manufacturer{
    padding-top: 0;
    margin-top: -10px;
}

#page-container{
    width: auto!important;
    padding-top: 0px;
    background: none transparent;
}

#page-container2{
    padding: 0;
}

.shipping_estimator{
    margin: 0 10px;
    margin-bottom: 30px;
}

.navigation{
    display: none!important;
}

label{
    width: 120px;
    float: left;
}

.product_info .image{
  padding: 10px 0;
}

.product_info{
  padding-bottom: 15px;
  margin-bottom: 15px;
}

#foot{
  display: none;
}

#main_area{
  width: auto;
  margin: 0;
  max-width: 100% !important;
}
.prod_options label{
  padding-top: 4px;
}


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

import { UserListComponent } from './user-list.component';
import {TestModule} from '../../../test/test.module';
import {UserService} from '../shared/user.service';
import {RegistrationService} from '../shared/registration.service';
import {UserComponent} from '../user/user.component';

describe('UserListComponent', () => {
  let component: UserListComponent;
  let fixture: ComponentFixture<UserListComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule(TestModule.forTest({
      imports: [],
      providers: [
        UserService,
        RegistrationService
      ],
      declarations: [
        UserComponent,
        UserListComponent
      ]
    }));
    TestBed.compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UserListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
//
//  YKCAShapeLayer+YKCandleLayer.m
//  YKKline
//
//  Created by nethanhan on 2018/3/7.
//  Copyright © 2018年 nethanhan. All rights reserved.
//

#import "YKCAShapeLayer+YKCandleLayer.h"
#import "UIColor+YKKlineThemeColor.h"
#import <UIKit/UIColor.h>
#import <UIKit/UIBezierPath.h>

@implementation YKCAShapeLayer (YKCandleLayer)

/**
 生成OHLC

 @param model 蜡烛坐标模型
 @return 返回图层
 */
+ (YKCAShapeLayer *)getOHLCLayerWithPointModel:(YKCandlePointModel *)model candleW:(double)candleW
{
    //判断是否为涨跌
    BOOL isRed = model.oPoint.y >= model.cPoint.y ? YES : NO;

    UIBezierPath *path = [UIBezierPath bezierPath];
    //绘制上下影线
    [path moveToPoint:model.lPoint];
    [path addLineToPoint:model.hPoint];
    //开盘线
    [path moveToPoint:model.oPoint];
    [path addLineToPoint:CGPointMake(model.oPoint.x - candleW/2 + 1, model.oPoint.y)];
    //开盘线
    [path moveToPoint:model.cPoint];
    [path addLineToPoint:CGPointMake(model.cPoint.x + candleW/2 - 1, model.cPoint.y)];

    YKCAShapeLayer *layer = [YKCAShapeLayer layer];
    layer.path = path.CGPath;

    //判断涨跌来设置颜色
    if (isRed)
    {
        //涨,设置红色
        layer.strokeColor = [UIColor kLineCandleRedColor].CGColor;
    } else
    {
        //跌,设置绿色
        layer.strokeColor = [UIColor kLineCandleGreenColor].CGColor;
    }
    layer.fillColor = [UIColor clearColor].CGColor;

    return layer;
}

/**
 生成蜡烛

 @param model 蜡烛坐标模型
 @return 返回layer
 */
+ (YKCAShapeLayer *)getCandleLayerWithPointModel:(YKCandlePointModel *)model candleW:(double)candleW
{
    //判断是否为涨跌
    BOOL isRed = model.oPoint.y >= model.cPoint.y ? YES : NO;

    //生成柱子的rect
    CGRect candleFrame = CGRectMake(isRed ? model.cPoint.x - candleW/2 + 1 : model.oPoint.x - candleW/2 + 1,
                                    isRed ? model.cPoint.y : model.oPoint.y,
                                    candleW-2,
                                    ABS(model.oPoint.y - model.cPoint.y));

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:candleFrame];

    //绘制上下影线
    [path moveToPoint:model.lPoint];
    [path addLineToPoint:model.hPoint];

    YKCAShapeLayer *layer = [YKCAShapeLayer layer];
    layer.path = path.CGPath;

    //判断涨跌来设置颜色
    if (isRed)
    {
        //涨,设置红色
        layer.strokeColor = [UIColor kLineCandleRedColor].CGColor;
        layer.fillColor = [UIColor kLineCandleRedColor].CGColor;

    } else
    {
        //跌,设置绿色
        layer.strokeColor = [UIColor kLineCandleGreenColor].CGColor;
        layer.fillColor = [UIColor kLineCandleGreenColor].CGColor;
    }

    return layer;
}

@end


text:
package org.htmlcleaner;

/**
 *
 *
 */
public enum OptionalOutput {
    /**
     * Never outputed even if supplied in the source.
     */
    omit,
    /**
     * outputed ONLY if supplied in the source.
     */
    preserve,
    /**
     * Always outputed, if information is not supplied in the source a default is created.
     */
    alwaysOutput;
}


text:
require_relative 'single/value'
require_relative 'single/required_value'
require_relative 'single/row'
require_relative 'single/required_row'
require_relative 'single/column'

module DbMod
  module Statements
    module Configuration
      # Provides convenience extensions for statement and
      # prepared methods that return only a single result,
      # row, or column. The normal way to access this functionality
      # is via {MethodConfiguration#single}, which is available
      # when defining a statement method or prepared method:
      #
      #  def_statement(:a, 'SELECT name FROM a WHERE id=$1') { single(:value) }
      #  def_prepared(:b, 'SELECT id FROM b WHERE x > $y') { single(:column) }
      #  def_prepared(:c, 'SELECT * FROM c WHERE id = $id') { single(:row) }
      #
      #  def do_stuff
      #    a(1)    # => "foo"
      #    b(y: 2) # => ['1','2','3',...]
      #    c id: 3 # => Hash
      #  end
      #
      # +.single(:row)+ and +.single(:value)+ will return the first
      # row or the first value of the first row respectively, or +nil+
      # if no results are found. To generate a
      # {DbMod::Exceptions::NoResults} failure
      # instead of returning +nil+, use +.single(:row!)+ or
      # +.single(:value!)+.
      module Single
        # List of allowed parameters for {MethodConfiguration#single},
        # and the methods used to process them.
        COERCERS = {
          value: Single::Value,
          value!: Single::RequiredValue,
          row: Single::Row,
          row!: Single::RequiredRow,
          column: Single::Column
        }

        # Extend the given method definition with additional
        # result coercion, if specified using {MethodConfiguration#single.
        #
        # @param definition [Proc] base method definition
        # @param config [MethodConfiguration] method configuration
        # @return [Proc] wrapped method definition, or the original
        #   definition if no coercion has been specified
        def self.extend(definition, config)
          type = config[:single]
          return definition if type.nil?

          Configuration.attach_result_processor definition, COERCERS[type]
        end
      end
    end
  end
end


text:
Uniforms.Images
===============

Custom images controls and helpers for Xamarin.Forms

Install
-------

Install via NuGet:

```
PM> Install-Package Uniforms.Images
```

You may also clone repository and add projects directly to your solution. Just don't forget to add references.

Tinted Image
------------

`TintedImage` extends `Image` and adds `TintColor` property.

Available for **iOS** and **Android** at the moment.

Rounded Image
-------------

`RoundedImage` extends `Image` class and supports arbitrary border radius as well as border color and thickness.

Available for **iOS** and **Android** at the moment.

Usage:

1. Init renderer in platform specific project like that:

    ```csharp
    #if __IOS__
    Xamarin.Forms.Forms.Init ();
    Uniforms.Images.iOS.RoundedImageRenderer.Init ();
    Uniforms.Images.iOS.TintedImageRenderer.Init ();
    #endif

    #if __ANDROID__
    Xamarin.Forms.Forms.Init (activity, bundle);
    Uniforms.Images.Droid.RoundedImageRenderer.Init ();
    Uniforms.Images.Droid.TintedImageRenderer.Init ();
    #endif
    ```

2. Add `usage` statement and just use `RoundedImage` class:

    ```csharp
    using Uniforms.Images;

    // ...

    var image = new RoundedImage {
        Aspect = Aspect.AspectFill,
        HorizontalOptions = LayoutOptions.Center,
        BorderRadius = 10,
        WidthRequest = 100,
        HeightRequest = 50,
        Source = "photo.jpg"
    };
    ```

If you need circle image, you may also specify `BorderRadius = -1.0` and it will be automatically set to half of the image size.

Note the `Aspect` and `HorizontalOptions` parameters values, they could prevent unwanted stretching in layout.

Based on [Xam.Plugins.Forms.ImageCircle](https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle) plugin and provides the same basic interface.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>edu.kit.iti.formal.pse.worthwhile</groupId>
    <artifactId>edu.kit.iti.formal.pse.worthwhile.expressions</artifactId>
    <version>0.1.0</version>
    <packaging>eclipse-plugin</packaging>
    <parent>
        <groupId>edu.kit.iti.formal.pse</groupId>
        <artifactId>worthwhile</artifactId>
        <version>0.1</version>
    </parent>
    <build>
        <resources>
            <resource><directory>src</directory></resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.fornax.toolsupport</groupId>
                <artifactId>fornax-oaw-m2-plugin</artifactId>
                <version>3.3.0-SNAPSHOT</version>
                <configuration>
                    <workflowEngine>mwe2</workflowEngine>
                    <workflowDescriptor>src/edu/kit/iti/formal/pse/worthwhile/expressions/GenerateWorthwhileExpressions.mwe2</workflowDescriptor>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals><goal>run-workflow</goal></goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            org.fornax.toolsupport
                                        </groupId>
                                        <artifactId>
                                            fornax-oaw-m2-plugin
                                        </artifactId>
                                        <versionRange>
                                            [3.3.0-SNAPSHOT,)
                                        </versionRange>
                                        <goals>
                                            <goal>run-workflow</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
</project>


text:
<#

.SYNOPSIS

Demonstrates the functionality of PowerShell's debugging support.

#>

Set-StrictMode -Version Latest

Write-Host "Calculating lots of complex information"

$runningTotal = 0
$runningTotal += [Math]::Pow(5 * 5 + 10, 2)

Write-Debug "Current value: $runningTotal"

Set-PsDebug -Trace 1
$dirCount = @(Get-ChildItem $env:WINDIR).Count

Set-PsDebug -Trace 2
$runningTotal -= 10
$runningTotal /= 2

Set-PsDebug -Step
$runningTotal *= 3
$runningTotal /= 2

$host.EnterNestedPrompt()

Set-PsDebug -off


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const space_infix_ops_1 = __importDefault(require("eslint/lib/rules/space-infix-ops"));
const util = __importStar(require("../util"));
const UNIONS = ['|', '&'];
exports.default = util.createRule({
    name: 'space-infix-ops',
    meta: {
        type: 'layout',
        docs: {
            description: 'This rule is aimed at ensuring there are spaces around infix operators.',
            category: 'Stylistic Issues',
            recommended: false,
            extendsBaseRule: true,
        },
        fixable: space_infix_ops_1.default.meta.fixable,
        schema: space_infix_ops_1.default.meta.schema,
        messages: (_a = space_infix_ops_1.default.meta.messages) !== null && _a !== void 0 ? _a : {
            missingSpace: "Operator '{{operator}}' must be spaced.",
        },
    },
    defaultOptions: [
        {
            int32Hint: false,
        },
    ],
    create(context) {
        const rules = space_infix_ops_1.default.create(context);
        const sourceCode = context.getSourceCode();
        const report = (node, operator) => {
            context.report({
                node: node,
                loc: operator.loc,
                messageId: 'missingSpace',
                data: {
                    operator: operator.value,
                },
                fix(fixer) {
                    const previousToken = sourceCode.getTokenBefore(operator);
                    const afterToken = sourceCode.getTokenAfter(operator);
                    let fixString = '';
                    if (operator.range[0] - previousToken.range[1] === 0) {
                        fixString = ' ';
                    }
                    fixString += operator.value;
                    if (afterToken.range[0] - operator.range[1] === 0) {
                        fixString += ' ';
                    }
                    return fixer.replaceText(operator, fixString);
                },
            });
        };
        function isSpaceChar(token) {
            return token.type === experimental_utils_1.AST_TOKEN_TYPES.Punctuator && token.value === '=';
        }
        function checkAndReportAssignmentSpace(node, leftNode, rightNode) {
            if (!rightNode) {
                return;
            }
            const operator = sourceCode.getFirstTokenBetween(leftNode, rightNode, isSpaceChar);
            const prev = sourceCode.getTokenBefore(operator);
            const next = sourceCode.getTokenAfter(operator);
            if (!sourceCode.isSpaceBetween(prev, operator) ||
                !sourceCode.isSpaceBetween(operator, next)) {
                report(node, operator);
            }
        }
        /**
         * Check if it has an assignment char and report if it's faulty
         * @param node The node to report
         */
        function checkForEnumAssignmentSpace(node) {
            if (!node.initializer) {
                return;
            }
            const leftNode = sourceCode.getTokenByRangeStart(node.id.range[0]);
            const rightNode = sourceCode.getTokenByRangeStart(node.initializer.range[0]);
            checkAndReportAssignmentSpace(node, leftNode, rightNode);
        }
        /**
         * Check if it has an assignment char and report if it's faulty
         * @param node The node to report
         */
        function checkForClassPropertyAssignmentSpace(node) {
            var _a, _b;
            const leftNode = sourceCode.getTokenByRangeStart((_b = (_a = node.typeAnnotation) === null || _a === void 0 ? void 0 : _a.range[0]) !== null && _b !== void 0 ? _b : node.range[0]);
            const rightNode = node.value
                ? sourceCode.getTokenByRangeStart(node.value.range[0])
                : undefined;
            checkAndReportAssignmentSpace(node, leftNode, rightNode);
        }
        /**
         * Check if it is missing spaces between type annotations chaining
         * @param typeAnnotation TypeAnnotations list
         */
        function checkForTypeAnnotationSpace(typeAnnotation) {
            const types = typeAnnotation.types;
            types.forEach(type => {
                const operator = sourceCode.getTokenBefore(type);
                if (operator != null && UNIONS.includes(operator.value)) {
                    const prev = sourceCode.getTokenBefore(operator);
                    const next = sourceCode.getTokenAfter(operator);
                    if (!sourceCode.isSpaceBetween(prev, operator) ||
                        !sourceCode.isSpaceBetween(operator, next)) {
                        report(typeAnnotation, operator);
                    }
                }
            });
        }
        /**
         * Check if it has an assignment char and report if it's faulty
         * @param node The node to report
         */
        function checkForTypeAliasAssignment(node) {
            const leftNode = sourceCode.getTokenByRangeStart(node.id.range[0]);
            const rightNode = sourceCode.getTokenByRangeStart(node.typeAnnotation.range[0]);
            checkAndReportAssignmentSpace(node, leftNode, rightNode);
        }
        return Object.assign(Object.assign({}, rules), { TSEnumMember: checkForEnumAssignmentSpace, ClassProperty: checkForClassPropertyAssignmentSpace, TSTypeAliasDeclaration: checkForTypeAliasAssignment, TSUnionType: checkForTypeAnnotationSpace, TSIntersectionType: checkForTypeAnnotationSpace });
    },
});
//# sourceMappingURL=space-infix-ops.js.map


text:
'use strict';

const http = require('http');

class ProxyServer {
  constructor() {
    this.called = false;
    this.lastReq = null;
    this.httpServer = http.createServer((req, res) => {
      this.called = true;
      this.lastReq = req;
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('okay');
    });
    this.httpServer.listen(3001);
  }
}

module.exports = ProxyServer;


text:
import os

from datetime import timedelta
from socrate import system
import ipaddress

DEFAULT_CONFIG = {
    # Specific to the admin UI
    'DOCKER_SOCKET': 'unix:///var/run/docker.sock',
    'BABEL_DEFAULT_LOCALE': 'en',
    'BABEL_DEFAULT_TIMEZONE': 'UTC',
    'BOOTSTRAP_SERVE_LOCAL': True,
    'RATELIMIT_STORAGE_URL': '',
    'QUOTA_STORAGE_URL': '',
    'DEBUG': False,
    'DOMAIN_REGISTRATION': False,
    'TEMPLATES_AUTO_RELOAD': True,
    'MEMORY_SESSIONS': False,
    # Database settings
    'DB_FLAVOR': None,
    'DB_USER': 'mailu',
    'DB_PW': None,
    'DB_HOST': 'database',
    'DB_NAME': 'mailu',
    'SQLITE_DATABASE_FILE':'data/main.db',
    'SQLALCHEMY_DATABASE_URI': 'sqlite:////data/main.db',
    'SQLALCHEMY_TRACK_MODIFICATIONS': False,
    # Statistics management
    'INSTANCE_ID_PATH': '/data/instance',
    'STATS_ENDPOINT': '19.{}.stats.mailu.io',
    # Common configuration variables
    'SECRET_KEY': 'changeMe',
    'DOMAIN': 'mailu.io',
    'HOSTNAMES': 'mail.mailu.io,alternative.mailu.io,yetanother.mailu.io',
    'POSTMASTER': 'postmaster',
    'WILDCARD_SENDERS': '',
    'TLS_FLAVOR': 'cert',
    'INBOUND_TLS_ENFORCE': False,
    'DEFER_ON_TLS_ERROR': True,
    'AUTH_RATELIMIT_IP': '60/hour',
    'AUTH_RATELIMIT_IP_V4_MASK': 24,
    'AUTH_RATELIMIT_IP_V6_MASK': 56,
    'AUTH_RATELIMIT_USER': '100/day',
    'AUTH_RATELIMIT_EXEMPTION': '',
    'AUTH_RATELIMIT_EXEMPTION_LENGTH': 86400,
    'DISABLE_STATISTICS': False,
    # Mail settings
    'DMARC_RUA': None,
    'DMARC_RUF': None,
    'WELCOME': False,
    'WELCOME_SUBJECT': 'Dummy welcome topic',
    'WELCOME_BODY': 'Dummy welcome body',
    'DKIM_SELECTOR': 'dkim',
    'DKIM_PATH': '/dkim/{domain}.{selector}.key',
    'DEFAULT_QUOTA': 1000000000,
    'MESSAGE_RATELIMIT': '200/day',
    'MESSAGE_RATELIMIT_EXEMPTION': '',
    'RECIPIENT_DELIMITER': '',
    # Web settings
    'SITENAME': 'Mailu',
    'WEBSITE': 'https://mailu.io',
    'ADMIN' : 'none',
    'WEB_ADMIN': '/admin',
    'WEB_WEBMAIL': '/webmail',
    'WEBMAIL': 'none',
    'RECAPTCHA_PUBLIC_KEY': '',
    'RECAPTCHA_PRIVATE_KEY': '',
    'LOGO_URL': None,
    'LOGO_BACKGROUND': None,
    # Advanced settings
    'LOG_LEVEL': 'WARNING',
    'SESSION_KEY_BITS': 128,
    'SESSION_TIMEOUT': 3600,
    'PERMANENT_SESSION_LIFETIME': 30*24*3600,
    'SESSION_COOKIE_SECURE': True,
    'CREDENTIAL_ROUNDS': 12,
    'TZ': 'Etc/UTC',
    # Host settings
    'HOST_IMAP': 'imap',
    'HOST_LMTP': 'imap:2525',
    'HOST_POP3': 'imap',
    'HOST_SMTP': 'smtp',
    'HOST_AUTHSMTP': 'smtp',
    'HOST_ADMIN': 'admin',
    'HOST_WEBMAIL': 'webmail',
    'HOST_WEBDAV': 'webdav:5232',
    'HOST_REDIS': 'redis',
    'HOST_FRONT': 'front',
    'SUBNET': '192.168.203.0/24',
    'SUBNET6': None,
    'POD_ADDRESS_RANGE': None
}

class ConfigManager:
    """ Naive configuration manager that uses environment only
    """

    DB_TEMPLATES = {
        'sqlite': 'sqlite:////{SQLITE_DATABASE_FILE}',
        'postgresql': 'postgresql://{DB_USER}:{DB_PW}@{DB_HOST}/{DB_NAME}',
        'mysql': 'mysql://{DB_USER}:{DB_PW}@{DB_HOST}/{DB_NAME}'
    }

    def __init__(self):
        self.config = dict()

    def get_host_address(self, name):
        # if MYSERVICE_ADDRESS is defined, use this
        if f'{name}_ADDRESS' in os.environ:
            return os.environ.get(f'{name}_ADDRESS')
        # otherwise use the host name and resolve it
        return system.resolve_address(self.config[f'HOST_{name}'])

    def resolve_hosts(self):
        for key in ['IMAP', 'POP3', 'AUTHSMTP', 'SMTP', 'REDIS']:
            self.config[f'{key}_ADDRESS'] = self.get_host_address(key)
        if self.config['WEBMAIL'] != 'none':
            self.config['WEBMAIL_ADDRESS'] = self.get_host_address('WEBMAIL')

    def __get_env(self, key, value):
        key_file = key + "_FILE"
        if key_file in os.environ:
            with open(os.environ.get(key_file)) as file:
                value_from_file = file.read()
            return value_from_file.strip()
        else:
            return os.environ.get(key, value)

    def __coerce_value(self, value):
        if isinstance(value, str) and value.lower() in ('true','yes'):
            return True
        elif isinstance(value, str) and value.lower() in ('false', 'no'):
            return False
        return value

    def init_app(self, app):
        # get current app config
        self.config.update(app.config)
        # get environment variables
        self.config.update({
            key: self.__coerce_value(self.__get_env(key, value))
            for key, value in DEFAULT_CONFIG.items()
        })
        self.resolve_hosts()

        # automatically set the sqlalchemy string
        if self.config['DB_FLAVOR']:
            template = self.DB_TEMPLATES[self.config['DB_FLAVOR']]
            self.config['SQLALCHEMY_DATABASE_URI'] = template.format(**self.config)

        self.config['RATELIMIT_STORAGE_URL'] = f'redis://{self.config["REDIS_ADDRESS"]}/2'
        self.config['QUOTA_STORAGE_URL'] = f'redis://{self.config["REDIS_ADDRESS"]}/1'
        self.config['SESSION_STORAGE_URL'] = f'redis://{self.config["REDIS_ADDRESS"]}/3'
        self.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
        self.config['SESSION_COOKIE_HTTPONLY'] = True
        self.config['SESSION_PERMANENT'] = True
        self.config['SESSION_TIMEOUT'] = int(self.config['SESSION_TIMEOUT'])
        self.config['PERMANENT_SESSION_LIFETIME'] = int(self.config['PERMANENT_SESSION_LIFETIME'])
        self.config['AUTH_RATELIMIT_IP_V4_MASK'] = int(self.config['AUTH_RATELIMIT_IP_V4_MASK'])
        self.config['AUTH_RATELIMIT_IP_V6_MASK'] = int(self.config['AUTH_RATELIMIT_IP_V6_MASK'])
        hostnames = [host.strip() for host in self.config['HOSTNAMES'].split(',')]
        self.config['AUTH_RATELIMIT_EXEMPTION'] = set(ipaddress.ip_network(cidr, False) for cidr in (cidr.strip() for cidr in self.config['AUTH_RATELIMIT_EXEMPTION'].split(',')) if cidr)
        self.config['MESSAGE_RATELIMIT_EXEMPTION'] = set([s for s in self.config['MESSAGE_RATELIMIT_EXEMPTION'].lower().replace(' ', '').split(',') if s])
        self.config['HOSTNAMES'] = ','.join(hostnames)
        self.config['HOSTNAME'] = hostnames[0]

        # update the app config
        app.config.update(self.config)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycosystema 1: 246 (1988)

#### Original name
Cercospora costeroana Petr. & Cif.

### Remarks
null


text:
"""Supported types of operating systems that a VM may host."""

from perfkitbenchmarker import flags

DEBIAN = 'debian'
JUJU = 'juju'
RHEL = 'rhel'
UBUNTU_CONTAINER = 'ubuntu_container'
WINDOWS = 'windows'

LINUX_OS_TYPES = DEBIAN, JUJU, RHEL, UBUNTU_CONTAINER
WINDOWS_OS_TYPES = WINDOWS,
ALL = LINUX_OS_TYPES + WINDOWS_OS_TYPES

flags.DEFINE_enum(
    'os_type', DEBIAN, ALL,
    'The VM\'s OS type. Ubuntu\'s os_type is "debian" because it is largely '
    'built on Debian and uses the same package manager. Likewise, CentOS\'s '
    'os_type is "rhel". In general if two OS\'s use the same package manager, '
    'and are otherwise very similar, the same os_type should work on both of '
    'them.')


text:
package org.apache.flink.runtime.rest.handler.cluster;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.messages.webmonitor.ClusterOverview;
import org.apache.flink.runtime.rest.handler.AbstractRestHandler;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.legacy.messages.ClusterOverviewWithVersion;
import org.apache.flink.runtime.rest.messages.EmptyMessageParameters;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;

import javax.annotation.Nonnull;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/** Handler which returns the cluster overview information with version. */
public class ClusterOverviewHandler
        extends AbstractRestHandler<
                RestfulGateway,
                EmptyRequestBody,
                ClusterOverviewWithVersion,
                EmptyMessageParameters> {

    private static final String version = EnvironmentInformation.getVersion();

    private static final String commitID = EnvironmentInformation.getRevisionInformation().commitId;

    public ClusterOverviewHandler(
            GatewayRetriever<? extends RestfulGateway> leaderRetriever,
            Time timeout,
            Map<String, String> responseHeaders,
            MessageHeaders<EmptyRequestBody, ClusterOverviewWithVersion, EmptyMessageParameters>
                    messageHeaders) {
        super(leaderRetriever, timeout, responseHeaders, messageHeaders);
    }

    @Override
    public CompletableFuture<ClusterOverviewWithVersion> handleRequest(
            @Nonnull HandlerRequest<EmptyRequestBody, EmptyMessageParameters> request,
            @Nonnull RestfulGateway gateway) {
        CompletableFuture<ClusterOverview> overviewFuture = gateway.requestClusterOverview(timeout);

        return overviewFuture.thenApply(
                statusOverview ->
                        ClusterOverviewWithVersion.fromStatusOverview(
                                statusOverview, version, commitID));
    }
}


text:
require('../../modules/es.string.sub');

module.exports = require('../../internals/entry-unbind')('String', 'sub');


text:
file(REMOVE_RECURSE
  "CMakeFiles/jacobisvd_12.dir/jacobisvd.cpp.o"
  "jacobisvd_12.pdb"
  "jacobisvd_12"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/jacobisvd_12.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>included (Ponteggio::EnumeratedColumn)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/ponteggio/enumerated_column.rb, line 34
    def self.included(klass)
      klass.extend ClassMethods
    end