text:
//
//  LJMeViewController.m
//  meishimeike
//
//  Created by zhenglong duan on 11/02/2017.
//  Copyright © 2017 zhenglong duan. All rights reserved.
//

#import "LJMeViewController.h"
#import "LJOrderStatusTableViewCell.h"
#import "LJOrderBaseViewController.h"
@interface LJMeViewController ()
/*** 背景视图 ***/
@property (nonatomic,strong) UIView *backgroundView;
/*** 背景图片 ***/
@property (nonatomic,strong) UIImageView *backgroundImageView;
/*** 用户头像 ***/
@property (nonatomic,strong) UIImageView *headerImageView;
/*** 用户昵称 ***/
@property (nonatomic,strong) UILabel *userNameLabel;
/*** 消息button ***/
@property (nonatomic,strong) UIButton *messageBtn;
@end
/*** 声明cell  ***/
static NSString *const LJOrderStatusCellID = @"LJOrderStatusCell";

@implementation LJMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
    [self setLayoutHeaderImageView];
    [self publicComment];
}

#pragma mark --懒加载
- (UIView *)backgroundView {
    if (!_backgroundView){
        _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, spaceEdgeH(240))];
    }
    return _backgroundView;
}

- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, spaceEdgeH(240))];
        _backgroundImageView.image = [UIImage imageNamed:@"me_background_icon"];
        _backgroundImageView.userInteractionEnabled = self;
        [self.backgroundView addSubview:_backgroundImageView];
    }
    return _backgroundImageView;
}

- (UILabel *)userNameLabel {
    if (!_userNameLabel) {
        _userNameLabel = [[UILabel alloc] init];
        _userNameLabel.textAlignment = NSTextAlignmentCenter;
        _userNameLabel.font = [UIFont systemFontOfSize:15];
        _userNameLabel.text = @"点击头像登陆";
        [_userNameLabel sizeToFit];
        _userNameLabel.textColor = [UIColor whiteColor];
        [self.backgroundImageView addSubview:_userNameLabel];
    }
    return _userNameLabel;
}

- (UIImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc ] init];
        _headerImageView.contentMode = UIViewContentModeScaleAspectFit;
        _headerImageView.backgroundColor = LJRandomColor;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(personInfoSetting)];
        [_headerImageView addGestureRecognizer:tap];
        _headerImageView.userInteractionEnabled = YES;
        [self.backgroundImageView addSubview:_headerImageView];
    }
    return _headerImageView;
}

#pragma mark --个人信息设置
- (void)personInfoSetting {
    if (USERDEFINE.currentUser) {      //用户已登陆,进行个人信息设置
        UIViewController * Vc =[NSClassFromString(@"LJUserInfoViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }else{  //进入登陆界面LJLoginViewController
        UIViewController * Vc =[NSClassFromString(@"LJLoginViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }
}

#pragma mark --设置背景头像位置
- (void)setLayoutHeaderImageView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.backgroundView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    /*** 注册自定义cell ***/
    [self.tableView registerClass:[LJOrderStatusTableViewCell class] forCellReuseIdentifier:LJOrderStatusCellID];

    [self.headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(70);
        make.centerX.mas_equalTo(self.backgroundView.mas_centerX);
        make.centerY.mas_equalTo(self.backgroundView.mas_centerY).offset(18);
    }];
    self.headerImageView.layer.masksToBounds = YES; //没这句话它圆不起来
    self.headerImageView.layer.cornerRadius = 70 / 2;

    [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headerImageView.mas_bottom).offset(5);
        make.centerX.mas_equalTo(self.headerImageView.mas_centerX);
        make.height.mas_equalTo(25);
    }];
}

#pragma mark --发表
- (void)publicComment {
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem initWithImage:@"设置" highImage:nil target:self action:@selector(settingBtnClick)];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem initWithImage:@"消息" highImage:nil target:self action:@selector(messageBtnClick)];
}

#pragma mark --消息触发
- (void)messageBtnClick {
    UIViewController * Vc =[NSClassFromString(@"LJNewsCenterViewController") new];
    [self.navigationController pushViewController:Vc animated:YES];
}

#pragma mark --设置触发
- (void)settingBtnClick {
    UIViewController * Vc =[NSClassFromString(@"LJSettingViewController") new];
    [self.navigationController pushViewController:Vc animated:YES];
}

/*** tableView代理方法 ***/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return 3;
            break;
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return spaceEdgeH(45);
        }else{
            return spaceEdgeH(67);
        }
    }else{
        return spaceEdgeH(45);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 &&indexPath.row ==1) {
        /*** 自定义订单cell ***/
        LJOrderStatusTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LJOrderStatusCellID];
        __weak LJMeViewController* weakSelf = self;
        cell.myOrderBlock = ^(NSInteger tag){
            [weakSelf MyOrderStatusClick:tag];
        };
        return cell;
    }else{
        static NSString* cellId = @"cellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell.textLabel setFont:LJFontSize15];
        /*** 分割线 ***/
        UIView *CutLine = [[UIView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 0.5)];
        CutLine.backgroundColor = LJCutLineColor;
        [cell addSubview:CutLine];

        if (indexPath.section ==0) {
            if (indexPath.row == 0) {
                cell.textLabel.text = @"我的订单";
                cell.detailTextLabel.text = @"查看全部订单";
                [cell.detailTextLabel setTextColor:LJFontColor39];
                [cell.detailTextLabel setFont:[UIFont systemFontOfSize:14 weight:UIFontWeightLight]];
            }
        }else {
            switch (indexPath.row) {
                case 0:
                    cell.imageView.image = [UIImage imageNamed:@"me_shoucang_icon"];
                    cell.textLabel.text = @"我的收藏";
                    break;
                case 1:
                    cell.imageView.image = [UIImage imageNamed:@"me_tv_icon"];
                    cell.textLabel.text = @"我的教程";
                    break;
                case 2:
                    cell.imageView.image = [UIImage imageNamed:@"me_contant_icon"];
                    cell.textLabel.text = @"我的关注";
                    break;
                default:
                    break;
            }
        }
        return cell;
    }
}

#pragma mark --查看我的订单状态
- (void)MyOrderStatusClick:(NSInteger)tag {
    if (tag == 0) { //待付款
        UIViewController *Vc = [NSClassFromString(@"LJPayOrderViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }else if (tag == 1){ //待配送
        UIViewController *Vc = [NSClassFromString(@"LJDeliverOreViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }else if (tag == 2){ //待收货
        UIViewController *Vc = [NSClassFromString(@"LJReceiveOrderViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }else if (tag == 3){//退换货
        UIViewController *Vc = [NSClassFromString(@"LJReturnGoodsOrderViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }else if (tag == 4){ //待评价
        UIViewController *Vc = [NSClassFromString(@"LJEvaluateOrderViewController") new];
        [self.navigationController pushViewController:Vc animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section ==0) {
        if (indexPath.row == 0) {//全部订单
            UIViewController *Vc = [NSClassFromString(@"LJAllOrderViewController") new];
            [self.navigationController pushViewController:Vc animated:YES];
        }
    }else {
        if (indexPath.row == 0){
            UIViewController *Vc = [NSClassFromString(@"LJMyCollectDetailViewController") new];
            [self.navigationController pushViewController:Vc animated:YES];
        }else if (indexPath.row == 1){  //教程
            UIViewController *Vc = [NSClassFromString(@"LJMyCollectDetailViewController") new];
            [self.navigationController pushViewController:Vc animated:YES];
        }else if (indexPath.row == 2){  //关注
            UIViewController *Vc = [NSClassFromString(@"LJMyCollectDetailViewController") new];  //关于我们
            [self.navigationController pushViewController:Vc animated:YES];
        }
    }
}

#pragma mark --ScrollView 代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offset_Y = scrollView.contentOffset.y;
        /*** 图片放大 ***/
    CGFloat imageH = self.backgroundView.lj_height;
    CGFloat imageW = SCREEN_WIDTH;
    if (offset_Y < 0) {
        CGFloat totalOffset = imageH + ABS(offset_Y);  //ABS 是整数绝对值
        self.backgroundImageView.frame = CGRectMake(0, offset_Y, imageW, totalOffset);
    }else{
        self.backgroundImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.backgroundView.lj_height);
        }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    /*** 将tableView恢复到初始位置 ***/
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];

    if (USERDEFINE.currentUser) {
        self.userNameLabel.text = USERDEFINE.currentUser.user_name;
        NSString *url = [NSString stringWithFormat:@"%@%@",headerUrl,USERDEFINE.currentUser.user_headimage];
        [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:url]];
    }else {
        self.userNameLabel.text = @"点击头像登陆";
        self.headerImageView.image = nil;
    }
}
@end


text:
<?php

Route::resource('lessons', '\Lesson\Controllers\LessonController');

redpajama_set_name: RedPajamaGithub


text:
#include "pg_upgrade.h"
#include "pqexpbuffer.h"

#include "catalog/pg_namespace.h"
#include "catalog/pg_magic_oid.h"

static char *simple_escape_literal(migratorContext *ctx, PGconn *conn, const char *s);

static void dump_rows(migratorContext *ctx, PQExpBuffer buf, FILE *file, PGconn *conn, const char *sql, const char *funcname);

/*
 * Read all pg_type and pg_class OIDs from old cluster, into the DbInfo structs.
 *
 * The OIDs of types and relations need to be preserved from the old cluster.
 * In the upstream, we use a different mechanism, integrated into pg_dump, for
 * this, but things are a bit more complicated in GPDB, because of partitions,
 * auxiliary AO segment tables, and bitmap index LOV tables. So we use a
 * different strategy.
 */
void
get_old_oids(migratorContext *ctx)
{
	int			dbnum;

	prep_status(ctx, "Exporting object OIDs from the old cluster");

	for (dbnum = 0; dbnum < ctx->old.dbarr.ndbs; dbnum++)
	{
		DbInfo	   *olddb = &ctx->old.dbarr.dbs[dbnum];
		PGconn	   *conn;
		PQExpBuffer	buf = createPQExpBuffer();

		conn = connectToServer(ctx, olddb->db_name, CLUSTER_OLD);
		PQclear(executeQueryOrDie(ctx, conn, "set search_path='pg_catalog';"));

		dump_rows(ctx, buf, NULL, conn,
				  "SELECT oid, nspname FROM pg_namespace",
				  "preassign_namespace_oid");
		dump_rows(ctx, buf, NULL, conn,
				  "SELECT oid, typname, typnamespace FROM pg_type",
				  "preassign_type_oid");

		/*
		 * A table's TOAST table might not be named the usual way in the old
		 * cluster, so dump it according to the way it will be named when created
		 * in the new cluster, instead of the current name.
		 *
		 * For example, "alter_distpol_g_char_11_false_false", in the regression
		 * database. FIXME: I don't quite understand how that happens.
		 *
		 * We don't preserve the OIDs of AO segment tables.
		 */
		dump_rows(ctx, buf, NULL, conn,
				  "SELECT oid, relname, relnamespace FROM pg_class "
				  " WHERE relnamespace NOT IN "
				  "   ( " CppAsString2(PG_TOAST_NAMESPACE) ", "
				  "" CppAsString2(PG_AOSEGMENT_NAMESPACE) ") "
				  " AND oid >= " CppAsString2(FirstNormalObjectId) " "
				  "UNION ALL "
				  "SELECT reltoastrelid, 'pg_toast_' || oid, " CppAsString2(PG_TOAST_NAMESPACE) " FROM pg_class WHERE reltoastrelid <> 0 AND oid >= " CppAsString2(FirstNormalObjectId) " ",
				  "preassign_relation_oid");

		PQfinish(conn);

		olddb->reserved_oids = buf->data;
	}

	check_ok(ctx);
}

/*
 * Dump OIDs of all objects, after upgrading the QD cluster.
 */
void
dump_new_oids(migratorContext *ctx)
{
	PGconn	   *conn;
	char		filename[MAXPGPATH];
	FILE	   *oid_dump;
	int			dbnum;

	prep_status(ctx, "Exporting object OIDs from the new cluster");

	/* Dump OIDs of global objects */
	snprintf(filename, sizeof(filename), "%s/%s", ctx->cwd, GLOBAL_OIDS_DUMP_FILE);
	oid_dump = fopen(filename, "w");
	if (!oid_dump)
		pg_log(ctx, PG_FATAL, "Could not create necessary file:  %s\n", filename);

	conn = connectToServer(ctx, "template1", CLUSTER_NEW);
	PQclear(executeQueryOrDie(ctx, conn, "set search_path='pg_catalog';"));

	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, fsname FROM pg_filespace", "preassign_filespace_oid");
	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, spcname FROM pg_tablespace", "preassign_tablespace_oid");
	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, rsqname FROM pg_resqueue", "preassign_resqueue_oid");
	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, resqueueid, restypid FROM pg_resqueuecapability", "preassign_resqueuecb_oid");
	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, rolname FROM pg_authid", "preassign_authid_oid");
	dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, datname FROM pg_database", "preassign_database_oid");

	PQfinish(conn);
	fclose(oid_dump);

	/*
	 * We use the old database OIDs, because we won't have convenient access
	 * to the new OIDs when we read these back in. It doesn't really matter
	 * which ones we use, as long as we're consistent.
	 */
	for (dbnum = 0; dbnum < ctx->old.dbarr.ndbs; dbnum++)
	{
		DbInfo	   *olddb = &ctx->old.dbarr.dbs[dbnum];

		snprintf(filename, sizeof(filename), "%s/" DB_OIDS_DUMP_FILE_MASK, ctx->cwd, olddb->db_oid);
		oid_dump = fopen(filename, "w");
		if (!oid_dump)
			pg_log(ctx, PG_FATAL, "Could not create necessary file:  %s\n", filename);

		conn = connectToServer(ctx, olddb->db_name, CLUSTER_NEW);

		PQclear(executeQueryOrDie(ctx, conn, "set search_path='pg_catalog';"));

		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, typname, typnamespace FROM pg_type", "preassign_type_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, oprnamespace, oprname FROM pg_operator", "preassign_operator_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, nspname FROM pg_namespace", "preassign_namespace_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, lanname FROM pg_language", "preassign_language_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, castsource, casttarget FROM pg_cast", "preassign_cast_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, connamespace, conname FROM pg_conversion", "preassign_conversion_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, ev_class, rulename FROM pg_rewrite", "preassign_rule_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, opfname, opfnamespace FROM pg_opfamily", "preassign_opfam_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, opcname, opcnamespace FROM pg_opclass", "preassign_opclass_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, prsnamespace, prsname FROM pg_ts_parser", "preassign_tsparser_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, dictnamespace, dictname FROM pg_ts_dict", "preassign_tsdict_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, tmplnamespace, tmplname FROM pg_ts_template", "preassign_tstemplate_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, cfgnamespace, cfgname FROM pg_ts_config", "preassign_tsconfig_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, extname FROM pg_extension", "preassign_extension_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, enumtypid, enumlabel FROM pg_enum", "preassign_enum_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, connamespace, conname, conrelid, contypid FROM pg_constraint", "preassign_constraint_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, ptcname FROM pg_extprotocol", "preassign_extprotocol_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, adrelid, adnum FROM pg_attrdef", "preassign_attrdef_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, relname, relnamespace FROM pg_class", "preassign_relation_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, proname, pronamespace FROM pg_proc", "preassign_procedure_oid");
		dump_rows(ctx, NULL, oid_dump, conn, "SELECT oid, amopmethod FROM pg_amop", "preassign_amop_oid");

		PQfinish(conn);

		fclose(oid_dump);
	}

	check_ok(ctx);
}

/*
 * Read all OID dump files into memory.
 */
void
slurp_oid_files(migratorContext *ctx)
{
	int			dbnum;
	char		filename[MAXPGPATH];
	FILE	   *oid_dump;
	struct stat st;
	char	   *reserved_oids;

	/* Read the Oids of global objects */
	oid_dump = fopen(GLOBAL_OIDS_DUMP_FILE, "r");
	if (!oid_dump)
		pg_log(ctx, PG_FATAL, "Could not open necessary file:  %s\n", GLOBAL_OIDS_DUMP_FILE);

	fstat(fileno(oid_dump), &st);

	reserved_oids = pg_malloc(ctx, st.st_size + 1);
	fread(reserved_oids, st.st_size, 1, oid_dump);
	reserved_oids[st.st_size] = '\0';

	ctx->old.global_reserved_oids = reserved_oids;

	/* Read per-DB Oids */
	for (dbnum = 0; dbnum < ctx->old.dbarr.ndbs; dbnum++)
	{
		DbInfo	   *olddb = &ctx->old.dbarr.dbs[dbnum];

		snprintf(filename, sizeof(filename), "%s/" DB_OIDS_DUMP_FILE_MASK, ctx->cwd, olddb->db_oid);
		oid_dump = fopen(filename, "r");
		if (!oid_dump)
			pg_log(ctx, PG_FATAL, "Could not open necessary file:  %s\n", filename);

		fstat(fileno(oid_dump), &st);

		reserved_oids = pg_malloc(ctx, st.st_size + 1);
		fread(reserved_oids, st.st_size, 1, oid_dump);
		reserved_oids[st.st_size] = '\0';

		olddb->reserved_oids = reserved_oids;
	}
}

/*
 * A helper function around PQescapeStringConn. Returns a statically
 * allocated buffer, so the returned value is only valid until the
 * next call.
 */
static char *
simple_escape_literal(migratorContext *ctx, PGconn *conn, const char *s)
{
	static char *buf = NULL;
	static int	buf_size = 0;
	int			input_len;
	int			req_size;

	input_len = strlen(s);

	req_size = input_len * 2 + 1;
	if (req_size > buf_size)
	{
		if (buf)
			pg_free(buf);

		if (req_size < NAMEDATALEN * 2 + 1)
			req_size = NAMEDATALEN * 2 + 1;

		buf = pg_malloc(ctx, req_size);
		buf_size = req_size;
	}

	PQescapeStringConn(conn, buf, s, input_len, NULL);

	return buf;
}

/*
 * Issue a query on a catalog table, and produce calls to a preassign support
 * function from the result set.
 *
 * The output is a string, containing SQL calls like:
 *
 * SELECT binary_upgrade.preassign_*_oid(<oid>, <other args);
 *
 * 'funcname' is the "preassign_*_oid" function to use.
 * 'sql' is the query to issue. The columns of the result set are passed as
 * arguments to the preassign-support function.
 *
 */
static void
dump_rows(migratorContext *ctx, PQExpBuffer buf, FILE *file, PGconn *conn,
		  const char *sql, const char *funcname)
{
	int			ntups;
	int			ncols;
	int			row;
	int			col;
	PGresult   *res;

	if (file != NULL)
		buf = createPQExpBuffer();

	/*
	 * Add a WHERE or AND clause to filter out built-in objects.
	 *
	 * If the query contains "UNION ALL", then it's the caller's
	 * responsibility to do the filtering. This special case is for the
	 * one more complicated query in get_old_oids() function; all the
	 * other queries are very simple ones.
	 */
	if (strstr(sql, "WHERE ") == NULL)
		res = executeQueryOrDie(ctx, conn, "%s WHERE oid >= %u", sql, FirstNormalObjectId);
	else if (strstr(sql, "UNION ALL") == NULL)
		res = executeQueryOrDie(ctx, conn, "%s AND oid >= %u", sql, FirstNormalObjectId);
	else
		res = executeQueryOrDie(ctx, conn, "%s", sql);

	ntups = PQntuples(res);
	ncols = PQnfields(res);

	for (row = 0; row < ntups; row++)
	{
		appendPQExpBuffer(buf, "SELECT binary_upgrade.%s('%s'",
						  funcname,
						  simple_escape_literal(ctx, conn, PQgetvalue(res, row, 0)));

		for (col = 1; col < ncols; col++)
			appendPQExpBuffer(buf, ", '%s'",
							  simple_escape_literal(ctx, conn, PQgetvalue(res, row, col)));
		appendPQExpBuffer(buf, ");\n");

		if (file)
		{
			fwrite(buf->data, buf->len, 1, file);
			resetPQExpBuffer(buf);
		}
	}
	PQclear(res);

	if (file != NULL)
		destroyPQExpBuffer(buf);
}


text:
import numpy as np
from mayavi import mlab
from BDSpace.Curve import ParametricCurve

from BDSpaceVis.space import SpaceView

class CurveView(SpaceView):

    def __init__(self, fig, curve, scale=1, color=None, opacity=None, edge_visible=False,
                 cs_visible=True, surface_visible=True, wireframe=False, resolution=20, thickness=None):
        assert isinstance(curve, ParametricCurve)
        self.resolution = resolution
        self.edge_visible = edge_visible
        self.thickness = None
        points, dims = generate_points(curve, self.resolution)
        super(CurveView, self).__init__(fig, curve, scale=scale, color=color, opacity=opacity,
                                        points=points, dims=dims,
                                        cs_visible=cs_visible, surface_visible=surface_visible, wireframe=wireframe)

    def set_resolution(self, resolution):
        self.resolution = resolution
        points, dims = generate_points(self.space, resolution)
        self.set_points(points, dims)
        self.draw()

    def get_thickness(self):
        if self.surface is not None:
            return self.surface.parent.parent.filter.radius

    def set_thickness(self, thickness):
        """
        Sets the thickness of the curve line changing mayavi tube radius
        :param thickness: float number between 0.0 and 1e299
        """
        if isinstance(thickness, (float, int)):
            self.thickness = float(thickness)
            try:
                self.surface.parent.parent.filter.radius = self.thickness
                self.draw()
            except AttributeError:
                pass

    def set_edge_visible(self, edge_visible=True):
        self.edge_visible = edge_visible
        self.draw()

    def draw_surface(self):
        if self.surface_visible:
            if self.points is not None:
                coordinate_system = self.space.basis_in_global_coordinate_system()
                curve_points = np.asarray(coordinate_system.to_parent(self.points))
                if self.surface is None:
                    mlab.figure(self.fig, bgcolor=self.fig.scene.background)
                    if self.thickness is None:
                        self.surface = mlab.plot3d(curve_points[:, 0], curve_points[:, 1], curve_points[:, 2],
                                                   color=self.color)
                        self.thickness = self.get_thickness()
                    else:
                        self.surface = mlab.plot3d(curve_points[:, 0], curve_points[:, 1], curve_points[:, 2],
                                                   color=self.color, tube_radius=self.thickness)
                else:
                    n_pts = len(curve_points) - 1
                    lines = np.zeros((n_pts, 2), 'l')
                    lines[:, 0] = np.arange(0, n_pts - 0.5, 1, 'l')
                    lines[:, 1] = np.arange(1, n_pts + 0.5, 1, 'l')
                    data = self.surface.parent.parent.parent.parent.data
                    data.set(lines=None)
                    data.set(points=curve_points)
                    data.set(lines=lines)
                self.surface.parent.parent.parent.parent.name = self.space.name
                self.surface.parent.parent.filter.radius = self.thickness
                self.surface.actor.property.color = self.color
                self.surface.actor.property.edge_visibility = self.edge_visible
                self.surface.actor.property.edge_color = self.color
                if self.wireframe:
                    self.surface.actor.property.representation = 'wireframe'
                else:
                    self.surface.actor.property.representation = 'surface'
                if self.opacity is not None:
                    self.surface.actor.property.opacity = self.opacity
        else:
            if self.surface is not None:
                self.surface.remove()
            self.surface = None

def generate_points(curve, resolution=20):
    assert isinstance(curve, ParametricCurve)
    dims = None
    num_points = angular_resolution(abs(curve.stop - curve.start), resolution)
    t = np.linspace(curve.start, curve.stop, num=num_points, endpoint=True, dtype=np.float)
    points = curve.generate_points(t)
    return points, dims

def angular_resolution(angle, resolution):
    points_num = int(angle / np.pi * resolution)
    if points_num < 2:
        points_num = 2
    return points_num


text:
/**
 * Created by Mauriel on 5/10/2018.
 */
$(document).ready(function () {
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        startDate: '0d'
    });

    // Validation for placement date
    $('#id_placement_date, #id_retrieval_date').change(function () {
        var placement = $('#id_placement_date').val();
        var retrieval = $('#id_retrieval_date').val();
        if (placement && retrieval) {
            var placementDate = new Date(placement);
            var retrievalDate = new Date(retrieval);
            if (placementDate > retrievalDate) {
                $('#id_placement_date')[0].setCustomValidity('Placement date has to be before the retrieval date.');
            }
            else {
                $('#id_placement_date')[0].setCustomValidity('');
                $('#id_retrieval_date')[0].setCustomValidity('');
            }
        }
        else if (!$(this).val()) {
            this.setCustomValidity('Please fill out this field.');
        }
    });

    $("#id_had_storm").change(function () {
        var val = parseInt($(this).val());
        var collapse = $("#storm-additional");
        var items = collapse.find("input");
        if (val == 2) {
            items.each(function () {
                if ($(this).attr("data-name")) {
                    $(this).attr("name", $(this).attr("data-name"));
                    $(this).removeAttr("data-name");
                }
                $(this).prop('required', true);
            });
            $("#storm-additional").collapse('show');
        }
        else {
            items.each(function () {
                if ($(this).attr("name")) {
                    $(this).attr("data-name", $(this).attr("name"));
                    $(this).removeAttr("name");
                }
                $(this).prop('required', false);
            });
            $("#storm-additional").collapse('hide');
        }
    });

    // Trigger on page load to set properties
    $("#id_had_storm").trigger("change");
    $('#d_placement_date, #id_retrieval_date').trigger("change");

    $(".bug-count").change(function() {
        var items = $(this).closest(".mdl-card").find(".bug-count");
        var count = 0;
        var total = $(this).closest(".mdl-card").find(".bug-total-count");

        items.each(function () {
            var val = $(this).val();
            if (val) {
                count += parseInt(val);
            }
        });

        total.val(Math.max(total.val(), count));
    });

    $(".bug-total-count").change(function() {
        var items = $(this).closest(".mdl-card").find(".bug-count");
        var count = 0;
        var total = $(this).closest(".mdl-card").find(".bug-total-count");

        items.each(function () {
            var val = $(this).val();
            if (val) {
                count += parseInt(val);
            }
        });

        if (count > total.val()) {
            $(items).val("");
        }
    });
});


text:
package edu.isi.pegasus.planner.catalog.transformation.impl;

import static org.junit.Assert.*;

import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.catalog.classes.SysInfo;
import edu.isi.pegasus.planner.catalog.classes.SysInfo.*;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.catalog.transformation.TransformationFactory;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.classes.Profile;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.test.DefaultTestSetup;
import edu.isi.pegasus.planner.test.EnvSetup;
import edu.isi.pegasus.planner.test.TestSetup;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * A Test class to test the Textual format of the Transformation Catalog
 *
 * @author Karan Vahi
 */
public class TextTest {
    /** The properties used for this test. */
    private static final String PROPERTIES_BASENAME = "properties";

    private static final String EXPANDED_SITE = "bamboo";
    private static final String EXPANDED_NAMESPACE = "pegasus";
    private static final String EXPANDED_NAME = "keg";
    private static final String EXPANDED_VERSION = "version";
    private static final String EXPANDED_ARCH = "x86_64";
    private static final String EXPANDED_OS = "linux";
    private static final String EXPANDED_KEG_PATH = "file:///usr/bin/pegasus-keg";

    private PegasusBag mBag;

    private PegasusProperties mProps;

    private LogManager mLogger;

    private TestSetup mTestSetup;

    private static int mTestNumber = 1;
    private Text mCatalog;

    @BeforeClass
    public static void setUpClass() {
        Map<String, String> testEnvVariables = new HashMap();
        testEnvVariables.put("SITE", EXPANDED_SITE);
        testEnvVariables.put("NAMESPACE", EXPANDED_NAMESPACE);
        testEnvVariables.put("NAME", EXPANDED_NAME);
        testEnvVariables.put("VERSION", EXPANDED_VERSION);
        testEnvVariables.put("ARCH", EXPANDED_ARCH);
        testEnvVariables.put("OS", EXPANDED_OS);
        testEnvVariables.put("KEGPATH", EXPANDED_KEG_PATH);
        EnvSetup.setEnvironmentVariables(testEnvVariables);
    }

    @AfterClass
    public static void tearDownClass() {}

    public TextTest() {}

    /** Setup the logger and properties that all test functions require */
    @Before
    public final void setUp() {
        mTestSetup = new DefaultTestSetup();
        mBag = new PegasusBag();
        mTestSetup.setInputDirectory(this.getClass());
        System.out.println("Input Test Dir is " + mTestSetup.getInputDirectory());

        mProps = mTestSetup.loadPropertiesFromFile(PROPERTIES_BASENAME, new LinkedList());

        mLogger = mTestSetup.loadLogger(mProps);
        mLogger.setLevel(LogManager.INFO_MESSAGE_LEVEL);
        mLogger.logEventStart("test.catalog.transformation.impl.Text", "setup", "0");
        mBag.add(PegasusBag.PEGASUS_LOGMANAGER, mLogger);
        mBag.add(PegasusBag.PEGASUS_PROPERTIES, mProps);
        // mBag.add( PegasusBag.PLANNER_OPTIONS, mTestSetup.loadPlannerOptions() );

        // load the transformation catalog backend
        mProps.setProperty(
                PegasusProperties.PEGASUS_TRANSFORMATION_CATALOG_FILE_PROPERTY,
                new File(mTestSetup.getInputDirectory(), "tc.text").getAbsolutePath());
        mProps.setProperty(
                PegasusProperties.PEGASUS_TRANSFORMATION_CATALOG_PROPERTY,
                TransformationFactory.TEXT_CATALOG_IMPLEMENTOR);
        mCatalog = (Text) TransformationFactory.loadInstance(mBag);
        mLogger.logEventCompletion();
    }

    @Test
    public void testWholeCount() throws Exception {
        mLogger.logEventStart(
                "test.catalog.transformation.impl.Text",
                "whole-count-test",
                Integer.toString(mTestNumber++));
        List<TransformationCatalogEntry> entries = mCatalog.getContents();
        assertEquals("Expected total number of entries", 4, entries.size());
        List<TransformationCatalogEntry> kegEntries =
                mCatalog.lookup("example", "keg", "1.0", (String) null, null);
        assertEquals("Expected total number of keg entries", 2, kegEntries.size());
        mLogger.logEventCompletion();
    }

    @Test
    public void testKegCount() throws Exception {
        mLogger.logEventStart(
                "test.catalog.transformation.impl.Text",
                "keg-count-test",
                Integer.toString(mTestNumber++));
        List<TransformationCatalogEntry> kegEntries =
                mCatalog.lookup("example", "keg", "1.0", (String) null, null);
        assertEquals("Expected total number of keg entries", 2, kegEntries.size());
        mLogger.logEventCompletion();
    }

    @Test
    public void testParameterExpansionCount() throws Exception {
        mLogger.logEventStart(
                "test.catalog.transformation.impl.Text",
                "parameter-expansion-test",
                Integer.toString(mTestNumber++));
        List<TransformationCatalogEntry> kegEntries =
                mCatalog.lookup(
                        TextTest.EXPANDED_NAMESPACE,
                        TextTest.EXPANDED_NAME,
                        TextTest.EXPANDED_VERSION,
                        TextTest.EXPANDED_SITE,
                        null);
        assertEquals("Expected total number of keg entries", 1, kegEntries.size());
        mLogger.logEventCompletion();
    }

    @Test
    public void testParameterExpansionContents() throws Exception {
        mLogger.logEventStart(
                "test.catalog.transformation.impl.Text",
                "parameter-expansion-contents",
                Integer.toString(mTestNumber++));
        List<TransformationCatalogEntry> kegEntries =
                mCatalog.lookup(
                        TextTest.EXPANDED_NAMESPACE,
                        TextTest.EXPANDED_NAME,
                        TextTest.EXPANDED_VERSION,
                        TextTest.EXPANDED_SITE,
                        null);
        TransformationCatalogEntry expanded = kegEntries.get(0);
        SysInfo info = expanded.getSysInfo();
        assertEquals("Expected attribute ", EXPANDED_NAMESPACE, expanded.getLogicalNamespace());
        assertEquals("Expected attribute ", EXPANDED_NAME, expanded.getLogicalName());
        assertEquals("Expected attribute ", EXPANDED_VERSION, expanded.getLogicalVersion());
        assertEquals("Expected attribute ", EXPANDED_SITE, expanded.getResourceId());
        assertEquals(
                "Expected attribute ", EXPANDED_KEG_PATH, expanded.getPhysicalTransformation());
        assertEquals("Expected attribute ", EXPANDED_ARCH, info.getArchitecture().name());
        assertEquals("Expected attribute ", EXPANDED_OS, info.getOS().name());

        mLogger.logEventCompletion();
    }

    @Test
    public void testMetadataKeyword() throws Exception {
        mLogger.logEventStart(
                "test.catalog.transformation.impl.Text",
                "metadata-keyword",
                Integer.toString(mTestNumber++));
        List<TransformationCatalogEntry> entries =
                mCatalog.lookup(null, "myxform", null, "condorpool", null);
        TransformationCatalogEntry entry = entries.get(0);
        SysInfo info = entry.getSysInfo();
        assertEquals("Expected attribute ", null, entry.getLogicalNamespace());
        assertEquals("Expected attribute ", "myxform", entry.getLogicalName());
        assertEquals("Expected attribute ", null, entry.getLogicalVersion());
        assertEquals("Expected attribute ", "condorpool", entry.getResourceId());
        assertEquals("Expected attribute ", "/usr/bin/true", entry.getPhysicalTransformation());
        assertEquals(
                "Expected attribute ",
                Architecture.x86_64.toString(),
                info.getArchitecture().name());
        assertEquals("Expected attribute ", OS.linux.toString(), info.getOS().name());
        testProfile(entry, Profile.METADATA, "key", "value");
        testProfile(entry, Profile.METADATA, "appmodel", "myxform.aspen");
        testProfile(entry, Profile.METADATA, "version", "3.0");

        mLogger.logEventCompletion();
    }

    private void testProfile(
            TransformationCatalogEntry entry, String namespace, String key, String value) {
        Profile p = new Profile(namespace, key, value);
        List profiles = entry.getProfiles(namespace);
        assertTrue("Entry " + entry, profiles.contains(p));
    }
}


text:
<?php

namespace Api\Bus\Hotels;

use Api\Bus\AbstractBus;

class Detail extends AbstractBus {

    protected $_required = array(
        'hotel_id'
    );

    protected $_number_format = array(
        'hotel_id'
    );

    protected $_length = array(
        'hotel_id' => array(1, 11)
    );

    public function operateDB($model, $param) {
        try {
            $this->_response = $model->getDetail($param);
            return $this->result($model->error());
        } catch (\Exception $e) {
            $this->_exception = $e;
        }
        return false;
    }

}


text:
from setuptools import setup, find_packages

install_requires = [
    'thriftpy',
    'packtools<=2.5.3',
    'requests',
    'lxml',
    'doaj_client',
    'scieloh5m5',
    'xylose',
    'articlemetaapi<=1.26.5',
    'publicationstatsapi>=1.2.1',
    'accessstatsapi>=1.2.1',
    'citedbyapi>=1.11.3',
    'legendarium>=2.0.2',
]

tests_require = []

setup(
    name="processing",
    version="1.32.5",
    description="SciELO processing modules for analytics, access statistics, etc",
    author="SciELO",
    author_email="scielo-dev@googlegroups.com",
    url="http://github.com/scieloorg/processing",
    packages=find_packages(),
    include_package_data=True,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 2.7",
    ],
    dependency_links=[
        "git+https://github.com/fabiobatalha/doaj_client@0.2#egg=doaj_client",
        "git+https://github.com/scieloorg/xylose@1.35.8#egg=xylose",
    ],
    tests_require=tests_require,
    test_suite='tests',
    install_requires=install_requires,
    entry_points="""
    [console_scripts]
    processing_accesses_dumpdata=accesses.dumpdata:main
    processing_accesses_documents_by_journals=accesses.documents_by_journals:main
    processing_publication_documents_languages=publication.documents_languages:main
    processing_publication_documents_affiliations=publication.documents_affiliations:main
    processing_publication_documents_affiliations_nationality=publication.documents_affiliations_nationality:main
    processing_publication_documents_authors=publication.documents_authors:main
    processing_publication_documents_counts=publication.documents_counts:main
    processing_publication_documents_licenses=publication.documents_licenses:main
    processing_publication_documents_dates=publication.documents_dates:main
    processing_publication_journals=publication.journals:main
    processing_publication_journals_status_changes=publication.journals_status_changes:main
    processing_publication_journals_indicators=publication.journals_indicators:main
    processing_publication_all=publication.dumper:main
    processing_evaluation_altmetrics=evaluation.altmetrics:main
    processing_export_xmlrsps=export.xml_rsps:main
    processing_export_normalize_affiliations=export.normalize_affiliations:main
    processing_export_natural_keys=export.natural_keys:main
    processing_export_crossref=export.crossref:main
    processing_export_doaj=export.exdoaj:main
    processing_export_doaj_journals=export.doaj_journals:main
    processing_export_kbart=export.kbart:main
    processing_export_dumparticles=export.dump_articles:main
    processing_export_search_update_indicators=export.search_update_indicators:main
    processing_bibliometric_citedby_document=bibliometric.citedby_document:main
    processing_bibliometric_citedby_journal=bibliometric.citedby_journal:main
    processing_bibliometric_impact_factor=bibliometric.impact_factor:main
    """
)


text:
require "time_track/version"
require "chronic"
require "thor"
require "dbus"
require "time"

module TimeTrack

  class CLI < Thor

    desc "resume", "list time per project during the given"
    method_option :from, :type => :string, :desc => "begining of the report period", :required => true
    method_option :to, :type  => :string, :desc => "end of the report period"
    def resume
      from_date = Chronic.parse(options[:from])
      to_date = Chronic.parse(options[:to]) || Time.now
      facts = get_facts(from_date, to_date)
      data = facts.inject({}) do |acc, fact|
        acc[fact[:project]] ||= 0
        acc[fact[:project]] += fact[:elapsed]
        acc
      end
      puts "Report or period #{from_date.strftime("%d/%m/%Y")} -> #{to_date.strftime("%d/%m/%Y")}"
      data.each do |project, elapsed|
        puts "#{project} = #{Time.at(elapsed).strftime("%H:%M")}"
      end
    end

    private

    def get_facts(from_date, to_date)
      setup unless @hamster
      facts = @hamster.GetFacts(from_date.to_i, to_date.to_i, '')[0]
      facts.map { |f| parse_facts f}
    end

    def setup
      bus = DBus::SessionBus.instance

      hamster_service = bus.service("org.gnome.Hamster")
      @hamster = hamster_service.object('/org/gnome/Hamster')
      @hamster.introspect
      @hamster.default_iface = 'org.gnome.Hamster'
    end

    # Return a hash containing all fact data in a better ruby form
    # [131, 1360752720, 1360757835, "", "FIX homepage et porduit coup de coeur", 45, "Cherriz", ["bugs"], 1360713600, 5115]
    #
    def parse_facts(fact_data)
      fact = {}
      fact[:hamster_id] = fact_data[0]
      fact[:start_time] = Time.at(fact_data[1])
      fact[:end_time] = Time.at(fact_data[2])
      fact[:description] = fact_data[3]
      fact[:name] = fact_data[4]
      fact[:project] = fact_data[6]
      fact[:tags] = fact_data[7]
      fact[:date] = Time.at(fact_data[8])
      fact[:elapsed] = fact[:end_time] - fact[:start_time]
      fact
    end

  end

end


text:
package org.drools.guvnor.server.util;

import java.util.Calendar;

public class TestBean {

    private String publisher = "42";
    private String creator = "42";
    private Calendar created = Calendar.getInstance();

    public String getPublisher() {
        return publisher;
    }

    public String getCreator() {
        return creator;
    }

    /** this should be ignored */
    public void getCoverage() {

    }

    public void updatePublisher(String pub) {
        this.publisher = pub;
    }

    public void updateCreator(String c) {
        this.creator = c;
    }

    public Calendar getCreatedDate() {
        return created ;
    }

}


text:
@interface OSPMapCSSTag : NSObject <CPParseResult>

@property (readwrite, assign, getter = isPseudoTag) BOOL pseudoTag;
@property (readwrite, copy) NSString *tagName;

@end


text:
file = File.join(Rails.root, 'config', 'config.yml')

begin
  CONFIG = (YAML.load_file(file)[Rails.env]).with_indifferent_access
rescue
  raise "Error when loading configuration file"
end
WebMock.allow_net_connect! if Rails.env.test?


text:
package pointers

import "time"

// NewBoolPtr ...
func NewBoolPtr(val bool) *bool {
	ptrValue := new(bool)
	*ptrValue = val
	return ptrValue
}

// NewStringPtr ...
func NewStringPtr(val string) *string {
	ptrValue := new(string)
	*ptrValue = val
	return ptrValue
}

// NewTimePtr ...
func NewTimePtr(val time.Time) *time.Time {
	ptrValue := new(time.Time)
	*ptrValue = val
	return ptrValue
}


text:
/**
 *
 */
package org.jasig.resource.aggr;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.resourceserver.aggr.AggregationException;
import org.jasig.resourceserver.aggr.ResourcesDao;
import org.jasig.resourceserver.aggr.ResourcesDaoImpl;
import org.jasig.resourceserver.aggr.om.BasicInclude;
import org.jasig.resourceserver.aggr.om.Css;
import org.jasig.resourceserver.aggr.om.Included;
import org.jasig.resourceserver.aggr.om.Js;
import org.jasig.resourceserver.aggr.om.Resources;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

/**
 * {@link ResourcesAggregator} implementation.
 *
 * @author Nicholas Blair, npblair@wisc.edu
 *
 */
public class ResourcesAggregatorImpl implements ResourcesAggregator {
	protected final Log logger;

	private final static String CSS = ".aggr.min.css";
	private final static String JS = ".aggr.min.js";

	private final ErrorReporter errorReporter;
	private final ResourcesDao resourcesDao;
    private final String encoding;

	private int cssLineBreakColumnNumber = 10000;
	private int jsLineBreakColumnNumber = 10000;

	private boolean obfuscateJs = true;
	private boolean displayJsWarnings = true;
	private boolean preserveAllSemiColons = true;
	private boolean disableJsOptimizations = false;

	private String digestAlgorithm = "MD5";

	public ResourcesAggregatorImpl(Log logger, String encoding) {
	    this.logger = logger != null ? logger : LogFactory.getLog(this.getClass());
	    this.encoding = encoding;
	    this.resourcesDao = new ResourcesDaoImpl(this.logger, this.encoding);
	    this.errorReporter = new CommonsLogErrorReporter(this.logger);
    }

	public ResourcesAggregatorImpl() {
	    this(null, "UTF-8");
	}

    public String getDigestAlgorithm() {
        return this.digestAlgorithm;
    }
    /**
     * The algorithm to use when creating the hashed file name for aggregated resources
     */
    public void setDigestAlgorithm(String digestAlgorithm) {
        this.digestAlgorithm = digestAlgorithm;
    }

    public int getCssLineBreakColumnNumber() {
		return cssLineBreakColumnNumber;
	}
	/**
	 * Maximum line length for minified CSS files, will wrap at this length, defaults to 10000
	 * @see CssCompressor#compress(java.io.Writer, int)
	 */
	public void setCssLineBreakColumnNumber(int cssLineBreakColumnNumber) {
		this.cssLineBreakColumnNumber = cssLineBreakColumnNumber;
	}

	public int getJsLineBreakColumnNumber() {
		return jsLineBreakColumnNumber;
	}
	/**
	 * Maximum line length for minified JS files, will wrap at this length, defaults to 10000
	 * @see JavaScriptCompressor#compress(java.io.Writer, int, boolean, boolean, boolean, boolean)
	 */
	public void setJsLineBreakColumnNumber(int jsLineBreakColumnNumber) {
		this.jsLineBreakColumnNumber = jsLineBreakColumnNumber;
	}

	public boolean isObfuscateJs() {
		return obfuscateJs;
	}
	/**
	 * If the JavaScript should be munged, obfuscating local symbols, defaults to true
	 */
	public void setObfuscateJs(boolean obfuscateJs) {
		this.obfuscateJs = obfuscateJs;
	}

	public boolean isDisplayJsWarnings() {
		return displayJsWarnings;
	}
	/**
	 * If JS syntax warnings should be displayed, defaults to true
	 */
	public void setDisplayJsWarnings(boolean displayJsWarnings) {
		this.displayJsWarnings = displayJsWarnings;
	}

	public boolean isPreserveAllSemiColons() {
		return preserveAllSemiColons;
	}
	/**
	 * If unnecessary semicolons should be preserved, defaults to true
	 */
	public void setPreserveAllSemiColons(boolean preserveAllSemiColons) {
		this.preserveAllSemiColons = preserveAllSemiColons;
	}

	public boolean isDisableJsOptimizations() {
		return disableJsOptimizations;
	}
	/**
	 * Disable micro-optimizations, defaults to false
	 */
	public void setDisableJsOptimizations(boolean disableJsOptimizations) {
		this.disableJsOptimizations = disableJsOptimizations;
	}

	@Override
    public void aggregate(File resourcesXml, File outputBaseDirectory) throws IOException, AggregationException {
	    this.aggregate(new AggregationRequest()
	        .setResourcesXml(resourcesXml)
	        .setOutputBaseDirectory(outputBaseDirectory));
    }

    @Override
	public void aggregate(File resourcesXml, File outputBaseDirectory, File sharedJavaScriptDirectory) throws IOException, AggregationException {
        this.aggregate(new AggregationRequest()
            .setResourcesXml(resourcesXml)
            .setOutputBaseDirectory(outputBaseDirectory)
            .setSharedJavaScriptDirectory(sharedJavaScriptDirectory));
    }

    @Override
    public void aggregate(AggregationRequest aggregationRequest) throws IOException, AggregationException {
        final File outputBaseDirectory = aggregationRequest.getOutputBaseDirectory();
	    if (outputBaseDirectory != null) {
	        outputBaseDirectory.mkdirs();
	    }
        if (null == outputBaseDirectory || !outputBaseDirectory.isDirectory() || !outputBaseDirectory.canWrite()) {
            throw new IllegalArgumentException("outputBaseDirectory (" + (null == outputBaseDirectory ? null : outputBaseDirectory.getAbsolutePath()) + ") must be a directory AND writable");
        }

        final MessageDigest digest;
        try {
            digest = MessageDigest.getInstance(this.digestAlgorithm);
        }
        catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Failed to create MessageDigest for algorithm '" + this.digestAlgorithm, e);
        }

		// parse the resourcesXml input
        final File resourcesXml = aggregationRequest.getResourcesXml();
		final Resources original = this.resourcesDao.readResources(resourcesXml, Included.AGGREGATED);
		final File resourcesParentDir = resourcesXml.getParentFile();

		//Build list of source directories for resource files
		final List<File> additionalSourceDirectories = aggregationRequest.getAdditionalSourceDirectories();
		final List<File> sourceDirectories = new ArrayList<File>(1 + additionalSourceDirectories.size());
		sourceDirectories.add(resourcesParentDir);
		sourceDirectories.addAll(additionalSourceDirectories);

		// aggregate CSS elements
		final CssCallback cssCallback = new CssCallback(digest, sourceDirectories, outputBaseDirectory);
		final List<Css> cssResult = this.aggregateBasicIncludes(original.getCss(), cssCallback);

		// aggregate JS elements
		final File sharedJavaScriptDirectory = aggregationRequest.getSharedJavaScriptDirectory();
		final JsCallback jsCallback = new JsCallback(digest, sourceDirectories, outputBaseDirectory, sharedJavaScriptDirectory);
        final List<Js> jsResult = this.aggregateBasicIncludes(original.getJs(), jsCallback);

		// build aggregated form result
		final Resources aggregatedForm = new Resources();
		aggregatedForm.getCss().addAll(cssResult);
		aggregatedForm.getJs().addAll(jsResult);
		aggregatedForm.getParameter().addAll(original.getParameter());

		// dump aggregated form out to output directory
		final String aggregatedFormOutputFileName = this.resourcesDao.getAggregatedSkinName(resourcesXml.getName());

        final File aggregatedOutputFile = new File(outputBaseDirectory, aggregatedFormOutputFileName);
        this.resourcesDao.writeResources(aggregatedForm, aggregatedOutputFile);

		this.logger.info("Aggregated " + original.getJs().size() +
		        " JavaScript files down to " + aggregatedForm.getJs().size() +
		        " and " + original.getCss().size() +
		        " CSS files down to " + aggregatedForm.getCss().size() +
		        " for: " + resourcesXml);
	}

	/**
	 * Iterate over the list of {@link BasicInclude} sub-classes using the {@link AggregatorCallback#willAggregate(BasicInclude, BasicInclude)}
	 * and {@link AggregatorCallback#aggregate(Deque)} to generate an aggregated list of {@link BasicInclude} sub-classes.
	 */
	protected <T extends BasicInclude> List<T> aggregateBasicIncludes(List<T> original, AggregatorCallback<T> callback) throws IOException {
        final List<T> result = new LinkedList<T>();
        final Deque<T> currentAggregateList = new LinkedList<T>();
        for (final T originalElement : original) {
            // handle first loop iteration
            if (currentAggregateList.isEmpty()) {
                currentAggregateList.add(originalElement);
            }
            else {
                // test if 'originalElement' will aggregate with head element in currentAggregate
                final T baseElement = currentAggregateList.getFirst();
                if (callback.willAggregate(originalElement, baseElement)) {
                    // matches current criteria, add to currentAggregate
                    currentAggregateList.add(originalElement);
                }
                else {
                    // doesn't match criteria
                    // generate new single aggregate from currentAggregateList
                    final T aggregate = callback.aggregate(currentAggregateList);
                    if (null != aggregate) {
                        // push result
                        result.add(aggregate);
                    }
                    else {
                        this.logger.warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
                    }

                    // zero out currentAggregateList
                    currentAggregateList.clear();

                    // add originalElement to empty list
                    currentAggregateList.add(originalElement);
                }
            }
        }

        // flush the currentAggregateList
        if (currentAggregateList.size() > 0) {
            final T aggregate = callback.aggregate(currentAggregateList);
            if (null != aggregate) {
                result.add(aggregate);
            }
            else {
                this.logger.warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
            }
        }

        return result;
	}

	/**
	 * Find the File for the resource file in the various source directories.
	 *
	 * @param sourceDirectories List of directories to scan
	 * @param resourceFileName File name of resource file
	 * @return The resolved File
	 * @throws IOException If the File cannot be found
	 */
	protected File findFile(final List<File> sourceDirectories, String resourceFileName) throws IOException {
	    for (final File sourceDirectory : sourceDirectories) {
	        final File resourceFile = new File(sourceDirectory, resourceFileName);
	        if (resourceFile.exists()) {
	            return resourceFile;
	        }
	    }

	    throw new IOException("Failed to find resource " + resourceFileName + " in any of the source directories: " + sourceDirectories);
	}

	/**
	 * Aggregate the specified Deque of elements into a single element. The provided MessageDigest is used for
	 * building the file name based on the hash of the file contents. The callback is used for type specific
	 * operations.
	 */
	protected <T extends BasicInclude> T aggregateList(final MessageDigest digest, final Deque<T> elements,
	        final List<File> skinDirectories, final File outputRoot, final File alternateOutput,
	        final String extension, final AggregatorCallback<T> callback) throws IOException {

        if (null == elements || elements.size() == 0) {
            return null;
        }

		// reference to the head of the list
        final T headElement = elements.getFirst();
        if (elements.size() == 1 && this.resourcesDao.isAbsolute(headElement)) {
            return headElement;
        }

        final File tempFile = File.createTempFile("working.", extension);
        final File aggregateOutputFile;
        try {
            //Make sure we're working with a clean MessageDigest
            digest.reset();
            TrimmingWriter trimmingWriter = null;
            try {
                final BufferedOutputStream bufferedFileStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                final MessageDigestOutputStream digestStream = new MessageDigestOutputStream(bufferedFileStream, digest);
                final OutputStreamWriter aggregateWriter = new OutputStreamWriter(digestStream, this.encoding);
                trimmingWriter = new TrimmingWriter(aggregateWriter);

                for (final T element: elements) {
                    final File resourceFile = this.findFile(skinDirectories, element.getValue());

                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(resourceFile);
                        final BOMInputStream bomIs = new BOMInputStream(new BufferedInputStream(fis));
                        if (bomIs.hasBOM()) {
                            logger.debug("Stripping UTF-8 BOM from: " + resourceFile);
                        }
                        final Reader resourceIn = new InputStreamReader(bomIs, this.encoding);
                        if (element.isCompressed()) {
                            IOUtils.copy(resourceIn, trimmingWriter);
                        }
                        else {
                            callback.compress(resourceIn, trimmingWriter);
                        }
                    }
                    catch (IOException e) {
                        throw new IOException("Failed to read '" + resourceFile + "' for skin: " + skinDirectories.get(0), e);
                    }
                    finally {
                        IOUtils.closeQuietly(fis);
                    }
                    trimmingWriter.write(SystemUtils.LINE_SEPARATOR);
                }
    		}
            finally {
                IOUtils.closeQuietly(trimmingWriter);
            }

            if (trimmingWriter.getCharCount() == 0) {
                return null;
            }

    		// temp file is created, get checksum
    		final String checksum = Base64.encodeBase64URLSafeString(digest.digest());
    		digest.reset();

    		// create a new file name
    		final String newFileName = checksum + extension;

    		// Build the new file name and path
    		if (alternateOutput == null) {
    		    final String elementRelativePath = FilenameUtils.getFullPath(headElement.getValue());
    	        final File directoryInOutputRoot = new File(outputRoot, elementRelativePath);
    	        // create the same directory structure in the output root
    	        directoryInOutputRoot.mkdirs();

    	        aggregateOutputFile = new File(directoryInOutputRoot, newFileName).getCanonicalFile();
    		}
    		else {
    		    aggregateOutputFile = new File(alternateOutput, newFileName).getCanonicalFile();
    		}

    		//Move the aggregate file into the correct location
    		FileUtils.deleteQuietly(aggregateOutputFile);
            FileUtils.moveFile(tempFile, aggregateOutputFile);
        }
        finally {
            //Make sure the temp file gets deleted
            FileUtils.deleteQuietly(tempFile);
        }

		final String newResultValue = RelativePath.getRelativePath(outputRoot, aggregateOutputFile);

		this.logAggregation(elements, newResultValue);

		return callback.getAggregateElement(newResultValue, elements);
	}

    /**
     * Log the result of an aggregation
     */
    protected void logAggregation(final Deque<? extends BasicInclude> elements, final String fileName) {
        if (this.logger.isDebugEnabled()) {
            final StringBuilder msg = new StringBuilder("Aggregated ")
                .append(fileName)
                .append(" from ")
                .append(generatePathList(elements));

            this.logger.debug(msg);
        }
    }

    /**
     * Build a string from the values of a Collection of {@link BasicInclude} elements
     */
    protected String generatePathList(final Collection<? extends BasicInclude> elements) {
        final StringBuilder msg = new StringBuilder();
        msg.append("[");
        for (final Iterator<? extends BasicInclude> elementItr = elements.iterator(); elementItr.hasNext();) {
            msg.append(elementItr.next().getValue());
            if (elementItr.hasNext()) {
                msg.append(", ");
            }
        }
        msg.append("]");

        return msg.toString();
    }

    /**
     * Similar to the {@link #equals(Object)} method, this will return
     * true if this object and the argument are "aggregatable".
     *
     * 2 {@link Css} objects are aggregatable if and only if:
     *

     *
Neither object returns true for {@link #isAbsolute()}

     *
The values of their "conditional" properties are equivalent

     *
The values of their "media" properties are equivalent

     *
The "paths" of their values are equivalent

     *

     *
     * The last rule mentioned above uses {@link FilenameUtils#getFullPath(String)}
     * to compare each object's value. In short, the final file name in the value's path
     * need not be equal, but the rest of the path in the value must be equal.
     *
     * @param second
     * @return
     */
    protected boolean willAggregateWith(Css first, Css second) {
        Validate.notNull(first, "Css argument cannot be null");
        Validate.notNull(second, "Css argument cannot be null");

        // never can aggregate absolute Css values
        if (this.resourcesDao.isAbsolute(first) || this.resourcesDao.isAbsolute(second)) {
            return false;
        }

        final String firstFullPath = FilenameUtils.getFullPath(first.getValue());
        final String secondFullPath = FilenameUtils.getFullPath(second.getValue());

        return new EqualsBuilder()
            .append(first.getConditional(), second.getConditional())
            .append(first.getMedia(), second.getMedia())
            .append(firstFullPath, secondFullPath)
            .isEquals();
    }

    /**
     * Similar to the {@link #equals(Object)} method, this will return
     * true if this object and the argument are "aggregatable".
     *
     * 2 {@link Js} objects are aggregatable if and only if:
     *

     *
Neither object returns true for {@link #isAbsolute()}

     *
The values of their "conditional" properties are equivalent

     *

     *
     * The last rule mentioned above uses {@link FilenameUtils#getFullPath(String)}
     * to compare each object's value. In short, the final file name in the value's path
     * need not be equal, but the rest of the path in the value must be equal.
     *
     * @param other
     * @return
     */
    protected boolean willAggregateWith(Js first, Js second) {
        Validate.notNull(first, "Js cannot be null");
        Validate.notNull(second, "Js cannot be null");

        // never aggregate absolutes
        if(this.resourcesDao.isAbsolute(first) || this.resourcesDao.isAbsolute(second)) {
            return false;
        }

        return new EqualsBuilder()
            .append(first.getConditional(), second.getConditional())
            .isEquals();
    }

    public interface AggregatorCallback<T extends BasicInclude> {
        public void compress(Reader reader, Writer writer) throws EvaluatorException, IOException;
        public T getAggregateElement(String location, final Deque<T> elements);
        public T aggregate(Deque<T> list) throws IOException;
        public boolean willAggregate(T first, T second);
    }

    private class JsCallback implements AggregatorCallback<Js> {
        private final MessageDigest digest;
        private final List<File> sourceDirectories;
        private final File outputBaseDirectory;
        private final File sharedJavaScriptDirectory;

        public JsCallback(MessageDigest digest, List<File> sourceDirectories, File outputBaseDirectory, File sharedJavaScriptDirectory) {
            this.digest = digest;
            this.sourceDirectories = sourceDirectories;
            this.outputBaseDirectory = outputBaseDirectory;
            this.sharedJavaScriptDirectory = sharedJavaScriptDirectory;
        }

        @Override
        public void compress(Reader reader, Writer writer) throws EvaluatorException, IOException {
            final JavaScriptCompressor jsCompressor = new JavaScriptCompressor(reader, errorReporter);
            jsCompressor.compress(writer, jsLineBreakColumnNumber, obfuscateJs, displayJsWarnings, preserveAllSemiColons, disableJsOptimizations);
        }

        @Override
        public Js getAggregateElement(String location, Deque<Js> elements) {
            final Js baseElement = elements.getFirst();

            final Js aggregate = new Js();
            aggregate.setValue(location);
            aggregate.setConditional(baseElement.getConditional());
            aggregate.setCompressed(true);

            return aggregate;
        }

        @Override
        public Js aggregate(Deque<Js> list) throws IOException {
            final File alternateOutput;
            if (sharedJavaScriptDirectory == null) {
                alternateOutput = outputBaseDirectory;
            }
            else {
                alternateOutput = sharedJavaScriptDirectory;
            }

            return aggregateList(digest, list, sourceDirectories, outputBaseDirectory, alternateOutput, JS, this);
        }

        @Override
        public boolean willAggregate(Js first, Js second) {
            return willAggregateWith(first, second);
        }
    }

    private class CssCallback implements AggregatorCallback<Css> {
        private final MessageDigest digest;
        private final List<File> sourceDirectories;
        private final File outputBaseDirectory;

        public CssCallback(MessageDigest digest, List<File> sourceDirectories, File outputBaseDirectory) {
            this.digest = digest;
            this.sourceDirectories = sourceDirectories;
            this.outputBaseDirectory = outputBaseDirectory;
        }

        @Override
        public void compress(Reader reader, Writer writer) throws EvaluatorException, IOException {
            final CssCompressor jsCompressor = new CssCompressor(reader);
            jsCompressor.compress(writer, cssLineBreakColumnNumber);
        }

        @Override
        public Css getAggregateElement(String location, Deque<Css> elements) {
            final Css baseElement = elements.getFirst();

            final Css aggregate = new Css();
            aggregate.setValue(location);
            aggregate.setConditional(baseElement.getConditional());
            aggregate.setMedia(baseElement.getMedia());
            aggregate.setCompressed(true);

            return aggregate;
        }

        @Override
        public Css aggregate(Deque<Css> list) throws IOException {
            return aggregateList(digest, list, sourceDirectories, outputBaseDirectory, null, CSS, this);
        }

        @Override
        public boolean willAggregate(Css first, Css second) {
            return willAggregateWith(first, second);
        }
    }
}


text:
**coming soon**

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. **coming soon**

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details


text:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

class RemountOnNavigate extends React.Component {
	static propTypes = {
		matchedLocation: PropTypes.object.isRequired,
		previousLocation: PropTypes.object.isRequired,
		children: PropTypes.node.isRequired
	}

	render() {
		const {
			loading,
			matchedLocation,
			previousLocation,
			children
		} = this.props

		const location = loading ? previousLocation : matchedLocation

		return (
			<div
				key={`${location.pathname}${location.search}`}
				className="remount-container">
				{children}
			</div>
		)
	}
}

export default connect(({ preload, found }) => ({
	loading: preload.pending,
	matchedLocation: found.match.location,
	previousLocation: found.resolvedMatch.location
}))(RemountOnNavigate)