text:
//
//  HUDHelper.m
//  XIBConstraintTest
//
//  Created by zhangjiang on 15/11/5.
//  Copyright © 2015年 zhangjiang. All rights reserved.
//

#import "HUDHelper.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#import <AVFoundation/AVFoundation.h>/*相机*/
#import <objc/runtime.h>
#import "pop.h"
#define _IPHONE70_ 70000
#define IOS9  [[[UIDevice currentDevice] systemVersion] floatValue]>=9.0f
static const double _x_pi = 3.14159265358979324 * 3000.0 / 180.0;

@implementation WCAttachmentText

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex NS_AVAILABLE_IOS(7_0)
{
    return CGRectMake( 0 , -2 , 16 , 16 );
}
@end

@interface HUDHelper ()<POPAnimationDelegate>

@end

@implementation HUDHelper
+ (HUDHelper *) getInstance
{
    static HUDHelper *instance = nil;
    @synchronized(self) {
        if (instance == nil) {
            instance = [[HUDHelper alloc] init];
        }
    }
    return instance;
}

/* 判断手机号是否正确 */
+(BOOL)CheckPhoneNumInput:(NSString *)text{
    NSString *regex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return  [pred evaluateWithObject:text];
}

+ (BOOL) IsIdentityCard:(NSString *)IDCardNumber
{
    if (IDCardNumber.length <= 0) {
        return NO;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:IDCardNumber];
}

/**
 *  计算字符串中字符个数 一个汉字占据两个字符
 */
+ (NSUInteger)lenghtWithString:(NSString *)string chineseCharCount:(NSUInteger*)chineseCharCount
{
    NSUInteger len = string.length;
    // 汉字字符集
    NSString * pattern  = @"[\u4e00-\u9fa5]";
    NSError *error=nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    if(error)
    {
        NSLog(@"出错");
    }
    // 计算中文字符的个数
    NSUInteger numMatch = [regex numberOfMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, len)];
    *chineseCharCount=numMatch;

    return len + numMatch;
}

//计算并绘制字符串文本的高度
+(CGSize)getSuitSizeWithString:(NSString *)text fontSize:(float)fontSize bold:(BOOL)bold sizeOfX:(float)x
{
    UIFont *font ;
    if (bold) {
        font = [UIFont boldSystemFontOfSize:fontSize];
    }else{
        font = [UIFont systemFontOfSize:fontSize];
    }

    CGSize constraint = CGSizeMake(x, MAXFLOAT);
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    // 返回文本绘制所占据的矩形空间。
    CGSize contentSize = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return contentSize;
}

+(CGSize)getSuitSizeWidthWithString:(NSString *)text fontSize:(float)fontSize sizeOfY:(float)y{

    UIFont *font = [UIFont systemFontOfSize:fontSize];

    CGSize constraint = CGSizeMake(MAXFLOAT, y);
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    // 返回文本绘制所占据的矩形空间。
    CGSize contentSize = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    return contentSize;
}

//获取ip地址
+(NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

/**
 *  获取当前的显示的ViewController
 */
+ (UIViewController *)getCurrentViewController{

    UIViewController *result = nil;

    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }

    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;

    return result;
}

/*!
 @brief 空返回YES
 @string string
 */
+ (BOOL)isBlankString:(NSString *)string
{
    if (string == nil || string == NULL ||[string isEqual:@""]||[string isEqual:@"<null>"])
        return YES;

    if ([string isKindOfClass:[NSNull class]])
        return YES;
    //判断是不是空格
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
        return YES;

    return NO;
}

+(BOOL)judgeResposeIsBlank:(id )responseData
{
    if([responseData isKindOfClass:[NSString class]]){
        return ![HUDHelper isBlankString:responseData];
    }

    if([responseData isKindOfClass:[NSArray class]] && [responseData count]>0){
        return YES;
    }

    if([responseData isKindOfClass:[NSDictionary class]] && [responseData allKeys].count){
        return YES;
    }
    return NO;
}

//两个字符串是否是包含关系
+(BOOL)isContainsString:(NSString *)firstStr second:(NSString*)secondStr{

    if (IOS8_OR_LATER) {
        return [firstStr containsString:secondStr];
    }else{
        NSRange lengthRange = [firstStr rangeOfString:secondStr];
       return  lengthRange.length?YES: NO;
    }
}

//截取字符;
+(NSString *)timeString:(NSString *)timeStr range:(NSUInteger)range
{
    if (![self isBlankString:timeStr]) {
        if (timeStr.length > range) {
            return [timeStr substringToIndex:range];
        }else{
            return timeStr;
        }
    }else{
        return @"";
    }
}

#pragma mark -字典或者数组转json
+(NSString*)converseToJsonWithObject:(id)obj{
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString ;
    if ([jsonData length] > 0 && error == nil){
//        DLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);

        return jsonString;
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }

    return nil;

}

/**
 *  返回图文混排
 *
 *  @param string     字符串
 *  @param attributes 文字属性
 *  @param imageName  图片名称
 *  @param index      插入位置
 *
 *  @return 用控件的attributedText属性接收
 */
+(NSMutableAttributedString*)createTextKitWithString:(NSString*)string attributes:(NSDictionary*)attributes image:(NSString*)imageName index:(NSInteger)index{
    //图文混排
    NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc]initWithString:string attributes:attributes];
    WCAttachmentText *textAttachment = [[WCAttachmentText alloc]initWithData:nil ofType:nil];
    UIImage *showImage = [UIImage imageNamed:imageName];
    textAttachment.image = showImage;

    NSAttributedString *textAttschmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];

    [titleString insertAttributedString:textAttschmentString atIndex:index];
    return  titleString;
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return dic;
}

//  将数组重复的对象去除,只保留一个
+ (NSArray *)arrayWithMemberIsOnly:(NSArray *)array
{
    NSMutableArray *categoryArray = [NSMutableArray array];
    for (unsigned i = 0; i < [array count]; i++) {

        if ([categoryArray containsObject:[array objectAtIndex:i]] == NO) {
            [categoryArray addObject:[array objectAtIndex:i]];
        }
    }
    return categoryArray;
}

#pragma mark - 通过颜色值生成图片
+ (UIImage *)buttonImageFromColor:(UIColor *)color size:(CGSize)size{

    CGRect rect = CGRectMake(0,0,size.width,size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

#pragma mark - 裁剪图片
+ (UIImage *)clipsToRect:(CGRect)rect image:(UIImage*)orangeImage{
    CGRect maxRect = CGRectMake(0, 0, orangeImage.size.width, orangeImage.size.height);
    CGImageRef imageRef = CGImageCreateWithImageInRect(orangeImage.CGImage,maxRect);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //    CGContextTranslateCTM(ctx, 0, orangeImage.size.height);
    //    CGContextScaleCTM(ctx, 1, -1);
    CGContextDrawImage(ctx, CGRectMake(rect.origin.x, rect.origin.y, orangeImage.size.width, rect.size.height), orangeImage.CGImage);
    CGContextClipToRect(ctx, rect);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    UIGraphicsEndImageContext();
    CGImageRelease(imageRef);
    return image;
}

#pragma mark -图片压缩处理
+(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

/**
 * @brief  指定宽度压缩图片
 */
+ (UIImage *)scaleToSize:(UIImage *)img sizeW:(CGFloat)changeW{

    CGFloat imageW = img.size.width;
    CGFloat imageH = img.size.height;
    CGFloat changeH = (changeW*imageH)/imageW;
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(changeW, changeH));
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, changeW, changeH)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

+(void)setImageFitWithImageView:(UIImageView*)imageView{

    [imageView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    imageView.contentMode =  UIViewContentModeScaleAspectFill;
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    imageView.clipsToBounds  = YES;
}

+(void)makeScale:(UIView*)scaleView delegate:(id)delegate scale:(CGFloat)scale duration:(CFTimeInterval)duration
{

    scaleView.layer.transform = CATransform3DIdentity;

    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    CATransform3D tr0 = CATransform3DMakeScale(1, 1, 1);
    CATransform3D tr1 = CATransform3DMakeScale(scale, scale, 1);
    CATransform3D tr2 = CATransform3DMakeScale(1, 1, 1);
    NSArray *frameValues = [NSArray arrayWithObjects:
                            [NSValue valueWithCATransform3D:tr0],
                            [NSValue valueWithCATransform3D:tr1],
                            [NSValue valueWithCATransform3D:tr2],
                            nil];
    [animation setValues:frameValues];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = duration;
    animation.delegate = delegate;
    [scaleView.layer addAnimation:animation forKey:@"ShakedAnimation"];
}

#pragma mark -角度转弧度
double radians(float degrees) {
    return ( degrees * M_PI ) / 180.0;
}

+(void)rotationView:(UIView*)view duration:(CGFloat)duration delegate:(id)delegate
{
    view.layer.transform=CATransform3DIdentity;
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    CATransform3D tr0 = CATransform3DMakeRotation(radians(0),     0, 0,1);
    CATransform3D tr1 = CATransform3DMakeRotation(radians(90),    0, 0,1);
    CATransform3D tr2 = CATransform3DMakeRotation(radians(180.0), 0, 0,1);
    CATransform3D tr3 = CATransform3DMakeRotation(radians(270.0), 0, 0,1);
    CATransform3D tr4 = CATransform3DMakeRotation(radians(0), 0,  0,1);
    NSArray *frameValues = [NSArray arrayWithObjects:
                            [NSValue valueWithCATransform3D:tr0],
                            [NSValue valueWithCATransform3D:tr1],
                            [NSValue valueWithCATransform3D:tr2],
                            [NSValue valueWithCATransform3D:tr3],
                            [NSValue valueWithCATransform3D:tr4],
                            nil];
    [animation setValues:frameValues];
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = duration;
    animation.repeatCount=HUGE_VALF;
    animation.delegate=delegate;
    [view.layer addAnimation:animation forKey:@"RotationAnimation"];
}

#pragma mark------对动画的处理
+(void)floatAnimator:(UIView *)animator
{
    animator.layer.transform=CATransform3DIdentity;
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    CATransform3D tr0 = CATransform3DMakeTranslation(0, 0, 0);
    CATransform3D tr1 = CATransform3DMakeTranslation(-15, 0, 0);
    CATransform3D tr3 = CATransform3DMakeTranslation(0, 0, 0);
    NSArray *frameValues = [NSArray arrayWithObjects:
                            [NSValue valueWithCATransform3D:tr0],
                            [NSValue valueWithCATransform3D:tr1],
                            [NSValue valueWithCATransform3D:tr3],
                            nil];
    [animation setValues:frameValues];
    animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = 1.4;
    animation.repeatCount=10000;
    [animator.layer addAnimation:animation forKey:@"ShakedAnimation"];
}

+ (UIImage*) BgImageFromColors:(NSArray*)colors withFrame: (CGRect)frame{

    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    //开始生成
    UIGraphicsBeginImageContextWithOptions(frame.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //定义颜色空间
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    //设置起点和终点
    CGPoint start,end;;
    start = CGPointMake(0.0, frame.size.height);
    end = CGPointMake(frame.size.width, 0.0);
    //绘制图形
    CGContextDrawLinearGradient(context, gradient, start, end,kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    //生成图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    //释放
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();

    return image;

}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);

    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();

    return theImage;
}

#pragma mark -百度转火星坐标
+(CLLocation*)transformFromBaiDuToGoogle:(CLLocation*)baidu{

    double x = baidu.coordinate.longitude - 0.0065, y = baidu.coordinate.latitude - 0.006;
    double z = sqrt(x * x + y * y) - 0.00002 * sin(y * _x_pi);
    double theta = atan2(y, x) - 0.000003 * cos(x * _x_pi);
    double gg_lon = z * cos(theta);
    double gg_lat = z * sin(theta);
    return [[CLLocation alloc]initWithLatitude:gg_lat longitude:gg_lon];
}

#pragma mark -火星转百度坐标
+(CLLocation*)transformFromGoogleToBaiDu:(CLLocation*)google
{
    double x = google.coordinate.longitude, y =  google.coordinate.latitude;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * _x_pi);
    double theta = atan2(y, x) + 0.000003 * cos(x * _x_pi);

    double bd_lon=z * cos(theta) + 0.0065;
    double bd_lat = z * sin(theta) + 0.006;

    return [[CLLocation alloc]initWithLatitude:bd_lat longitude:bd_lon];
}

+(void)makeNumChangeWithView:(UILabel*)label string:(NSString*)suffix FromValue:(CGFloat)from toValue:(CGFloat)to time:(CGFloat)time{

    //此对象的属性不在Pop Property的标准属性中,要创建一个POPAnimationProperty
    POPAnimatableProperty *prop = [POPAnimatableProperty propertyWithName:@"countdown" initializer:^(POPMutableAnimatableProperty *prop) {
        prop.writeBlock = ^(id obj, const CGFloat values[]) {
            label.text = [NSString stringWithFormat:@"%d%@",(int)values[0],suffix];
        };
        prop.threshold = 0.01f;
    }];
    POPBasicAnimation *anBasic = [POPBasicAnimation linearAnimation];   //秒表当然必须是线性的时间函数
    anBasic.property = prop;    //自定义属性
    anBasic.fromValue = @(from);   //从0开始
    anBasic.toValue = @(to);  //180秒
    anBasic.duration = time;    //持续3分钟
    anBasic.beginTime = CACurrentMediaTime();    //延迟1秒开始
    [label pop_addAnimation:anBasic forKey:@"countdown"];

}

+(CALayer*)drawLineGradient:(UIColor*)topColor
                buttomColor:(UIColor*)buttomColor
                 startpoint:(CGPoint)startPoint
                   endpoint:(CGPoint)endPoint
                      frame:(CGRect)frame
{
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.colors = [NSArray arrayWithObjects:
                       (id)topColor.CGColor,
                       (id)buttomColor.CGColor,nil];
    // 起始点
    gradient.startPoint = startPoint;

    // 结束点
    gradient.endPoint = endPoint;
    gradient.frame = frame;
    return gradient;

}

+(UIView *)createFrostedglassEffectWithFrame:(CGRect)frame{
    UIBlurEffect *blurEffect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualEffectView=[[UIVisualEffectView alloc]initWithEffect:blurEffect];
    [visualEffectView setFrame:frame];
    return visualEffectView;
}

+(void)setControlView:(UIView*)view corner:(CGFloat)cornerRadius borderW:(CGFloat)borderWidth borderColor:(UIColor *)borderColor{
    view.layer.cornerRadius = cornerRadius;
    view.layer.masksToBounds = YES;
    if (borderWidth) {
        view.layer.borderColor  = borderColor.CGColor;
        view.layer.borderWidth  = borderWidth;
    }
}

#pragma mark -给UILabel设置行间距和字间距
+(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font color:(UIColor*)color space:(CGFloat)lineSpace{

    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpace; //设置行间距
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    //设置字间距 NSKernAttributeName:@1.5f
    UIColor *defaultColor = color?color:[UIColor blackColor];
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSParagraphStyleAttributeName:paraStyle,
                          NSKernAttributeName:@1.5f,
                          NSForegroundColorAttributeName:defaultColor};
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
    label.attributedText = attributeStr;
}

#pragma mark -计算UILabel的高度(带有行间距的情况)
+(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width space:(CGFloat)lineSpace{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = lineSpace;
    paraStyle.hyphenationFactor = 1.0;
    paraStyle.firstLineHeadIndent = 0.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSParagraphStyleAttributeName:paraStyle,
                          NSKernAttributeName:@1.5f};

    CGSize size = [str boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

+ (NSString *)flattenHTML:(NSString *)html {

    NSScanner *theScanner;
    NSString *text = nil;
    theScanner = [NSScanner scannerWithString:html];
    while ([theScanner isAtEnd] == NO) {
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        [theScanner scanUpToString:@">" intoString:&text] ;
        html = [html stringByReplacingOccurrencesOfString:
                [NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }
    return html;
}

//正则去除网络标签
+(NSString *)getZZwithString:(NSString *)string{
    NSRegularExpression *regularExpretion = [NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n" options:0 error:nil];
    string = [regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    return string;
}
@end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace UniHttp
{
	internal class CookieDomain : IEnumerable
	{
		readonly IFileHandler fileHandler;
		readonly string filePath;
		readonly List<Cookie> cookies;
		internal readonly string name;

		internal CookieDomain(string baseDirectory, string domain, IFileHandler fileHandler)
		{
			this.filePath = BuildPath(baseDirectory, domain);
			this.fileHandler = fileHandler;
			this.cookies = ReadFromFile();
			this.name = domain;
		}

		internal static string BuildPath(string baseDirectory, string domain)
		{
			return string.Concat(
				baseDirectory,
				Path.DirectorySeparatorChar,
				domain,
				".cookies"
			);
		}

		public IEnumerator GetEnumerator()
		{
			return cookies.GetEnumerator();
		}

		internal void AddOrReplace(Cookie cookie)
		{
			Cookie target = FindMatch(cookie);
			if(target != null) {
				cookies.Remove(target);
			}
			if(!cookie.IsExpired) {
				cookies.Add(cookie);
			}
		}

		Cookie FindMatch(Cookie matcher)
		{
			foreach(Cookie cookie in cookies) {
				if(matcher.name == cookie.name) {
					return cookie;
				}
			}
			return null;
		}

		internal void WriteToFile()
		{
			cookies.RemoveAll(c => c.IsExpired);

			List<Cookie> targets = cookies.FindAll(cookie => !cookie.IsSession);

			if(targets.Count == 0) {
				return;
			}

			using(Stream stream = fileHandler.OpenWriteStream(filePath)) {
				BinaryWriter writer = new BinaryWriter(stream);
				writer.Write(targets.Count);
				foreach(Cookie cookie in targets) {
					writer.Write(cookie.name);
					writer.Write(cookie.value);
					writer.Write(cookie.domain != null);
					if(cookie.domain != null) {
						writer.Write(cookie.domain);
					}
					writer.Write(cookie.path);
					writer.Write(cookie.expires.HasValue);
					if(cookie.expires.HasValue) {
						writer.Write(cookie.expires.Value.ToBinary());
					}
					writer.Write(cookie.secure);
					writer.Write(cookie.httpOnly);
					writer.Write(cookie.size);
				}
			}
		}

		List<Cookie> ReadFromFile()
		{
			if(!fileHandler.Exists(filePath)) {
				return new List<Cookie>();
			}
			try {
				using(Stream stream = fileHandler.OpenReadStream(filePath)) {
					BinaryReader reader = new BinaryReader(stream);
					int size = reader.ReadInt32();
					List<Cookie> readCookies = new List<Cookie>(size);
					for(int i = 0; i < size; i++) {
						readCookies.Add(new Cookie {
							name = reader.ReadString(),
							value = reader.ReadString(),
							domain = reader.ReadBoolean() ? reader.ReadString() : null,
							path = reader.ReadString(),
							expires = reader.ReadBoolean() ? (DateTime?)DateTime.FromBinary(reader.ReadInt64()) : null,
							secure = reader.ReadBoolean(),
							httpOnly = reader.ReadBoolean(),
							size = reader.ReadInt32(),
						});
					}
					return readCookies;
				}
			}
			catch(IOException exception) {
				Debug.LogWarning(exception);
				return new List<Cookie>();
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using ArgumentParser.Api;

namespace ArgumentParser.Internal
{
    internal abstract class ArgumentSpecification : IArgumentSpecification
    {
        private string _longName;
        private char _shortName;

        protected ArgumentSpecification(MemberInfo memberInfo)
        {
            MemberInfo = memberInfo;
        }

        public string LongName
        {
            get => _longName;
            set
            {
                var keyChangingEventArgs = new KeyChangingEventArgs(value);
                OnKeyChanging(keyChangingEventArgs);
                if (!keyChangingEventArgs.Cancel)
                {
                    _longName = value;
                    OnKeyChanged(new KeyChangedEventArgs(_longName, this));
                }
                else if (keyChangingEventArgs.Exception != null)
                {
                    throw keyChangingEventArgs.Exception;
                }
            }
        }

        public char ShortName
        {
            get => _shortName;
            set
            {
                var keyChangingEventArgs = new KeyChangingEventArgs(value);
                OnKeyChanging(keyChangingEventArgs);
                if (!keyChangingEventArgs.Cancel)
                {
                    _shortName = value;
                    OnKeyChanged(new KeyChangedEventArgs(_shortName, this));
                }
                else if (keyChangingEventArgs.Exception != null)
                {
                    throw keyChangingEventArgs.Exception;
                }
            }
        }

        public int Index { get; set; }

        public string Description { get; set; }
        public bool Required { get; set; }
        public object DefaultValue { get; set; }
        public virtual bool HasName => HasLongName | HasShortName;
        public bool HasLongName => !string.IsNullOrWhiteSpace(LongName);
        public bool HasShortName => ShortName != default(char);
        public bool HasDefault => DefaultValue != null;
        public MemberInfo MemberInfo { get; }

        public event EventHandler<KeyChangingEventArgs> KeyChanging;
        public event EventHandler<KeyChangedEventArgs> KeyChanged;

        private void OnKeyChanging(KeyChangingEventArgs keyChangingEventArgs)
        {
            KeyChanging?.Invoke(this, keyChangingEventArgs);
        }

        private void OnKeyChanged(KeyChangedEventArgs keyChangedEventArgs)
        {
            KeyChanged?.Invoke(this, keyChangedEventArgs);
        }
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/ui/autofill/autocheckout_bubble_controller.h"
#include "components/autofill/browser/autofill_metrics.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/rect.h"

namespace autofill {
namespace {

class TestAutofillMetrics : public AutofillMetrics {
 public:
  TestAutofillMetrics()
      : metric_(NUM_BUBBLE_METRICS) {}
  virtual ~TestAutofillMetrics() {}
  virtual void LogAutocheckoutBubbleMetric(BubbleMetric metric) const OVERRIDE {
    metric_ = metric;
  }

  AutofillMetrics::BubbleMetric metric() const { return metric_; }

 private:
  mutable AutofillMetrics::BubbleMetric metric_;

  DISALLOW_COPY_AND_ASSIGN(TestAutofillMetrics);
};

class TestCallback {
 public:
  TestCallback() : accepted_count_(0), dismissed_count_(0) {}
  ~TestCallback() {}

  void Run(bool accepted) {
    if (accepted)
      accepted_count_++;
    else
      dismissed_count_++;
  }

  int accepted_count() const {
    return accepted_count_;
  }

  int dismissed_count() const {
    return dismissed_count_;
  }

  base::Callback<void(bool)> GetCallback() {
    return base::Bind(&TestCallback::Run, base::Unretained(this));
  }

 private:
  int accepted_count_;
  int dismissed_count_;
};

class TestAutocheckoutBubbleController :
  public autofill::AutocheckoutBubbleController {
 public:
  explicit TestAutocheckoutBubbleController(
      const base::Callback<void(bool)>& callback)
      : AutocheckoutBubbleController(gfx::RectF(),
                                     gfx::NativeWindow(),
                                     true /* is_google_user */,
                                     callback) {
    set_metric_logger(new TestAutofillMetrics);
  }
  virtual ~TestAutocheckoutBubbleController() {}

  const TestAutofillMetrics* get_metric_logger() const {
    return static_cast<TestAutofillMetrics*>(const_cast<AutofillMetrics*>(
        AutocheckoutBubbleController::metric_logger()));
  }
};

}  // namespace

TEST(AutocheckoutBubbleControllerTest, BubbleCreationAndDestructionMetrics) {
  // Test bubble created metric.
  TestCallback callback;
  TestAutocheckoutBubbleController controller(callback.GetCallback());

  controller.BubbleCreated();

  EXPECT_EQ(AutofillMetrics::BUBBLE_CREATED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(0, callback.accepted_count());
  EXPECT_EQ(0, callback.dismissed_count());

  // If neither BubbleAccepted or BubbleCanceled was called the bubble was
  // ignored.
  controller.BubbleDestroyed();

  EXPECT_EQ(AutofillMetrics::BUBBLE_IGNORED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(0, callback.accepted_count());
  EXPECT_EQ(1, callback.dismissed_count());
}

TEST(AutocheckoutBubbleControllerTest, BubbleAcceptedMetric) {
  // Test bubble accepted metric.
  TestCallback callback;
  TestAutocheckoutBubbleController controller(callback.GetCallback());

  controller.BubbleAccepted();

  EXPECT_EQ(AutofillMetrics::BUBBLE_ACCEPTED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(1, callback.accepted_count());
  EXPECT_EQ(0, callback.dismissed_count());

  // Test that after a bubble is accepted it is not considered ignored.
  controller.BubbleDestroyed();

  EXPECT_EQ(AutofillMetrics::BUBBLE_ACCEPTED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(1, callback.accepted_count());
  EXPECT_EQ(0, callback.dismissed_count());
}

TEST(AutocheckoutBubbleControllerTest, BubbleCanceledMetric) {
  // Test bubble dismissed metric.
  TestCallback callback;
  TestAutocheckoutBubbleController controller(callback.GetCallback());

  controller.BubbleCanceled();

  EXPECT_EQ(AutofillMetrics::BUBBLE_DISMISSED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(0, callback.accepted_count());
  EXPECT_EQ(1, callback.dismissed_count());

  // Test that after a bubble is dismissed it is not considered ignored.
  controller.BubbleDestroyed();

  EXPECT_EQ(AutofillMetrics::BUBBLE_DISMISSED,
            controller.get_metric_logger()->metric());
  EXPECT_EQ(0, callback.accepted_count());
  EXPECT_EQ(1, callback.dismissed_count());
}

}  // namespace autofill


text: <button ng-click="showHelpBox()">?</button>


text:
package com.ruinwesen.patchmanager.swing.forms;

import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import name.cs.csutils.i18n.I18N;
import name.cs.csutils.i18n.Translation;

public class AuthenticationDialog {

    private JPanel panel;
    private JTextField txtUsername;
    private JTextField txtPassword;
    private JTextField txtConfirmedPassword;
    private boolean confirmPasswordEnabled;
    private int minUsernameLength = 3;
    private int maxUsernameLength = 32;
    private int minPasswordLength = 5;
    private int maxPasswordLength = 32;

    private static final Translation CREATE_USER_STRING = I18N.getTranslation("Create User");
    private static final Translation LOGIN_STRING = I18N.getTranslation("Login");
    private static final Translation USERNAME_STRING = I18N.getTranslation("Username");
    private static final Translation PASSWORD_STRING = I18N.getTranslation("Password");
    private static final Translation REPEAT_PASSWORD_STRING = I18N.getTranslation("Repeat Password");
    private static final Translation USERNAME_LENGTH_WARNING_STRING = I18N.getTranslation("username must have %d to %d characters");
    private static final Translation PASSWORD_LENGTH_WARNING_STRING = I18N.getTranslation("password must have %d to %d characters");

    public AuthenticationDialog(boolean confirmPasswordEnabled,
            String initialUsername,
            String initialPassword) {
        this.confirmPasswordEnabled = confirmPasswordEnabled;
        init();
        txtUsername.setText(initialUsername);
        txtPassword.setText(initialPassword);
        txtConfirmedPassword.setText(initialPassword);
    }

    public int showCreateUserDialog(Component parentComponent) {
        return showDialog(parentComponent, CREATE_USER_STRING.value());
    }

    public int showLoginDialog(Component parentComponent) {
        return showDialog(parentComponent, LOGIN_STRING.value());
    }

    public int showDialog(Component parentComponent, String title) {
        int result = JOptionPane.CANCEL_OPTION;
        for(;;) {
            result = JOptionPane.showConfirmDialog(parentComponent,
                panel,
                title,
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.CANCEL_OPTION) {
                break;
            }

            String warning = null;
            if (txtUsername.getText().length()<minUsernameLength
                    || txtUsername.getText().length()>maxUsernameLength) {
                warning =  USERNAME_LENGTH_WARNING_STRING.format(minUsernameLength, maxUsernameLength);
            } else if (txtPassword.getText().length()<minPasswordLength
                    || txtPassword.getText().length()>maxPasswordLength) {
                warning =  PASSWORD_LENGTH_WARNING_STRING.format(minPasswordLength, maxPasswordLength);
            } else if (confirmPasswordEnabled && !txtConfirmedPassword.getText().equals(txtPassword.getText())) {
                warning = "password and password confirmation are not equal";
            }
            if (warning == null) {
                break; // input is valid
            }
            JOptionPane.showMessageDialog(parentComponent,
                    warning,
                    "input error",
                    JOptionPane.WARNING_MESSAGE);
        }
        return result;
    }

    public JComponent getComponent() {
        return panel;
    }

    private void init() {
        txtUsername = new JTextField();
        txtPassword = new JPasswordField();
        txtConfirmedPassword = new JPasswordField();

        panel = new JPanel();
        panel.setLayout(new GridLayout(0,2,2,2));
        panel.add(new JLabel(USERNAME_STRING.value()));
        panel.add(txtUsername);
        panel.add(new JLabel(PASSWORD_STRING.value()));
        panel.add(txtPassword);
        if (confirmPasswordEnabled) {
            panel.add(new JLabel(REPEAT_PASSWORD_STRING.value()));
            panel.add(txtConfirmedPassword);
        }
    }

    public void setUsername(String value) {
        txtUsername.setText(value);
    }

    public void setPassword(String value) {
        txtPassword.setText(value);
    }

    public void setConfirmedPassword(String value) {
        txtConfirmedPassword.setText(value);
    }

    public String getUsername() {
        return txtUsername.getText();
    }

    public String getPassword() {
        return txtPassword.getText();
    }

    public String getConfirmedPassword() {
        return txtConfirmedPassword.getText();
    }

    public static void main(String[] args) {
        AuthenticationDialog af = new AuthenticationDialog(false, null, null);
        af.setUsername("hugo");
        af.setPassword("bimmelbert");
        af.showLoginDialog(null);
        /*
        JFrame fr = new JFrame();
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.getContentPane().add(af.getComponent());
        fr.pack();
        fr.setLocationByPlatform(true);
        fr.setVisible(true);
        */
    }

}


text:
Template.reg.onCreated(function(){
	console.log('reg created');
	Meteor.subscribe('alldeparts');
});
Template.reg.helpers({
	departlist:function(){
		return cdepart.find({}).fetch();
	}
})
Template.login.events({
'submit form'(event){
	event.preventDefault();
	var username=event.target.username.value;
	password = event.target.password.value;
	console.log(username,password);
	Meteor.apply('users.login',[username,password],function(err,res){
		if(err){
			sAlert.error("登陆失败",{position:'bottom-left'});
		}else{
			if(res){
				Meteor.loginWithPassword(username,password,function(error){
					console.log(error)
					if(error){
						if(error.reason == 'Incorrect password'){
							message = "密码错误";
						}else if(error.reason == 'User not found'){
							message = "用户不存在"
						}else if(error.reason == 'User has no password set'){
							message = "用户未设置密码"
						}else{
							message = "用户名或密码错误";
						}
						sAlert.error(message,{position:'bottom-left'});
					}else{
						console.log(Meteor.user())
						//Router.go('home');
					}
				})
			}else{
				sAlert.error("用户不存在或者已删除",{position:'bottom-left'});
			}

		}

	})

}
});
Template.reg.events({
'submit form'(event){
	event.preventDefault();
	username = $.trim(event.target.username.value);
	passowrd = $.trim(event.target.password.value);
	repassowrd = $.trim(event.target.repassword.value);
	nickname = $.trim(event.target.nickname.value);
	depart = $.trim(event.target.depart.value);
	if(username == ""){
		sAlert.error('用户名不能为空',{position:"bottom-left"});
		return false;
	}
	if(password == ""){
		sAlert.error('密码不能为空',{position:"bottom-left"});
		return false;
	}
	if(repassowrd == ""){
		sAlert.error('确认密码不能为空',{position:"bottom-left"});
		return false;
	}
	if(passowrd.length <6){
		sAlert.error('密码至少6位',{position:"bottom-left"});
		return false;
	}
	if(passowrd !=repassowrd){
		sAlert.error('两次密码输入不一致',{position:"bottom-left"});
		return false;
	}
	info = {};
	info['username'] = event.target.username.value;
	info['password'] = event.target.password.value;
	info['profile'] = {};
	info['profile']['nickname'] = event.target.nickname.value;
	info['profile']['depart'] = event.target.depart.value;
	Meteor.apply('useres.create',[info],function(err,res){
		if(err){
			sAlert.error('注册失败',{position:'bottom-left'});
		}else{
			if(_.has(res,'error') && res.error){
				sAlert.error('注册失败',{position:'bottom-left'});
			}else{
				Router.go('home');
			}

		}
	})
}
})


text:
require 'spec_helper'
describe User do
  reader = User.create(name: "Atom Smasher")
  feed = AtomSmasher::Feed.create(url: "#{File.dirname(__FILE__)}/../fixtures/previous_episodes.xml")
  reader.feeds << feed

  it "should subscribe to feeds" do
    reader.should have(1).feeds
  end
end


text:
<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="resources/file-drag-common.js"></script>
</head>
<body>
<input type="file" name="file1" id="file1">
<input type="file" name="file2" id="file2">
<script>
description("This tests the files attribute in file input forms");

if (window.testRunner) {
    var file1 = document.getElementById("file1");
    var file2 = document.getElementById("file2");
    dragFilesOntoInput(file1, ["foo.txt"]);
    dragFilesOntoInput(file2, ["bar.txt"]);

    file1.files = "foo";
    shouldBe("file1.files.length", "1");
    shouldBeEqualToString("file1.files.item(0).name", "foo.txt");

    file1.files = null;
    shouldBe("file1.files.length", "1");
    shouldBeEqualToString("file1.files.item(0).name", "foo.txt");

    // From current W3C spec, files attribute should be read only,
    // but WebKit implement it to be writable intentionally.
    // See: https://bugs.webkit.org/show_bug.cgi?id=87154#c15
    file1.files = file2.files;
    shouldBe("file1.files.length", "1");
    shouldBeEqualToString("file1.files.item(0).name", "bar.txt");
}
</script>
</body>
</html>


text:
"""
Stack class.

@author: Gautham Ganapathy
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: gautham@lisphacker.org
"""

from lems.base.base import LEMSBase
from lems.base.errors import StackError

class Stack(LEMSBase):
    """
    Basic stack implementation.
    """

    def __init__(self):
        """
        Constructor.
        """

        self.stack = []
        """ List used to store the stack contents.
        @type: list """

    def push(self, val):
        """
        Pushed a value onto the stack.

        @param val: Value to be pushed.
        @type val: *
        """

        self.stack = [val] + self.stack

    def pop(self):
        """
        Pops a value off the top of the stack.

        @return: Value popped off the stack.
        @rtype: *

        @raise StackError: Raised when there is a stack underflow.
        """

        if self.stack:
            val = self.stack[0]
            self.stack = self.stack[1:]
            return val
        else:
            raise StackError('Stack empty')

    def top(self):
        """
        Returns the value off the top of the stack without popping.

        @return: Value on the top of the stack.
        @rtype: *

        @raise StackError: Raised when there is a stack underflow.
        """

        if self.stack:
            return self.stack[0]
        else:
            raise StackError('Stack empty')

    def is_empty(self):
        """
        Checks if the stack is empty.

        @return: True if the stack is empty, otherwise False.
        @rtype: Boolean
        """

        return self.stack == []

    def __str__(self):
        """
        Returns a string representation of the stack.

        @note: This assumes that the stack contents are capable of generating
        string representations.
        """

        if len(self.stack) == 0:
            s = '[]'
        else:
            s = '[' + str(self.stack[0])
            for i in range(1, len(self.stack)):
                s += ', ' + str(self.stack[i])
            s += ']'
        return s

    def __repr__(self):
        return self.__str__()


text:
#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"

namespace cvtest {
namespace ocl {

///////////// equalizeHist ////////////////////////

typedef TestBaseWithParam<Size> EqualizeHistFixture;

OCL_PERF_TEST_P(EqualizeHistFixture, EqualizeHist, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();
    const double eps = 1;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::equalizeHist(src, dst);

    SANITY_CHECK(dst, eps);
}

///////////// calcHist ////////////////////////

typedef TestBaseWithParam<Size> CalcHistFixture;

OCL_PERF_TEST_P(CalcHistFixture, CalcHist, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();

    const std::vector<int> channels(1, 0);
    std::vector<float> ranges(2);
    std::vector<int> histSize(1, 256);
    ranges[0] = 0;
    ranges[1] = 256;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), hist(256, 1, CV_32FC1);
    declare.in(src, WARMUP_RNG).out(hist);

    OCL_TEST_CYCLE() cv::calcHist(std::vector<UMat>(1, src), channels, noArray(), hist, histSize, ranges, false);

    SANITY_CHECK(hist);
}

///////////// calcHist ////////////////////////

typedef TestBaseWithParam<Size> CalcBackProjFixture;

OCL_PERF_TEST_P(CalcBackProjFixture, CalcBackProj, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();

    const std::vector<int> channels(1, 0);
    std::vector<float> ranges(2);
    std::vector<int> histSize(1, 256);
    ranges[0] = 0;
    ranges[1] = 256;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), hist(256, 1, CV_32FC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(hist);

    cv::calcHist(std::vector<UMat>(1, src), channels, noArray(), hist, histSize, ranges, false);

    declare.in(src, WARMUP_RNG).out(dst);
    OCL_TEST_CYCLE() cv::calcBackProject(std::vector<UMat>(1,src), channels, hist, dst, ranges, 1);

    SANITY_CHECK_NOTHING();
}

/////////// CopyMakeBorder //////////////////////

CV_ENUM(Border, BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_REFLECT_101)

typedef tuple<Size, MatType, Border> CopyMakeBorderParamType;
typedef TestBaseWithParam<CopyMakeBorderParamType> CopyMakeBorderFixture;

OCL_PERF_TEST_P(CopyMakeBorderFixture, CopyMakeBorder,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES_134, Border::all()))
{
    const CopyMakeBorderParamType params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), borderType = get<2>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst;
    const Size dstSize = srcSize + Size(12, 12);
    dst.create(dstSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::copyMakeBorder(src, dst, 7, 5, 5, 7, borderType, cv::Scalar(1.0));

    SANITY_CHECK(dst);
}

///////////// CornerMinEigenVal ////////////////////////

typedef Size_MatType CornerMinEigenValFixture;

OCL_PERF_TEST_P(CornerMinEigenValFixture, CornerMinEigenVal,
            ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_32FC1)))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), borderType = BORDER_REFLECT;
    const int blockSize = 7, apertureSize = 1 + 2 * 3;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, CV_32FC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::cornerMinEigenVal(src, dst, blockSize, apertureSize, borderType);

    SANITY_CHECK(dst, 1e-6, ERROR_RELATIVE);
}

///////////// CornerHarris ////////////////////////

typedef Size_MatType CornerHarrisFixture;

OCL_PERF_TEST_P(CornerHarrisFixture, CornerHarris,
            ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_32FC1)))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), borderType = BORDER_REFLECT;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, CV_32FC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::cornerHarris(src, dst, 5, 7, 0.1, borderType);

    SANITY_CHECK(dst, 5e-6, ERROR_RELATIVE);
}

///////////// PreCornerDetect ////////////////////////

typedef Size_MatType PreCornerDetectFixture;

OCL_PERF_TEST_P(PreCornerDetectFixture, PreCornerDetect,
            ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_32FC1)))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), borderType = BORDER_REFLECT;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, CV_32FC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::preCornerDetect(src, dst, 3, borderType);

    SANITY_CHECK(dst, 1e-6, ERROR_RELATIVE);
}

///////////// Integral ////////////////////////

typedef tuple<Size, MatDepth> IntegralParams;
typedef TestBaseWithParam<IntegralParams> IntegralFixture;

OCL_PERF_TEST_P(IntegralFixture, Integral1, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_32S, CV_32F)))
{
    const IntegralParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int ddepth = get<1>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, ddepth);

    UMat src(srcSize, CV_8UC1), dst(srcSize + Size(1, 1), ddepth);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::integral(src, dst, ddepth);

    SANITY_CHECK(dst, 2e-6, ERROR_RELATIVE);
}

OCL_PERF_TEST_P(IntegralFixture, Integral2, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_32S, CV_32F)))
{
    const IntegralParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int ddepth = get<1>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, ddepth);

    UMat src(srcSize, CV_8UC1), sum(srcSize + Size(1, 1), ddepth), sqsum(srcSize + Size(1, 1), CV_32F);
    declare.in(src, WARMUP_RNG).out(sum, sqsum);

    OCL_TEST_CYCLE() cv::integral(src, sum, sqsum, ddepth, CV_32F);

    SANITY_CHECK(sum, 2e-4, ERROR_RELATIVE);
    SANITY_CHECK(sqsum, 5e-5, ERROR_RELATIVE);
}

///////////// Threshold ////////////////////////

CV_ENUM(ThreshType, THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO_INV)

typedef tuple<Size, MatType, ThreshType> ThreshParams;
typedef TestBaseWithParam<ThreshParams> ThreshFixture;

OCL_PERF_TEST_P(ThreshFixture, Threshold,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, ThreshType::all()))
{
    const ThreshParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int srcType = get<1>(params);
    const int threshType = get<2>(params);
    const double maxValue = 220.0, threshold = 50;

    checkDeviceMaxMemoryAllocSize(srcSize, srcType);

    UMat src(srcSize, srcType), dst(srcSize, srcType);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::threshold(src, dst, threshold, maxValue, threshType);

    SANITY_CHECK(dst);
}

///////////// CLAHE ////////////////////////

typedef TestBaseWithParam<Size> CLAHEFixture;

OCL_PERF_TEST_P(CLAHEFixture, CLAHE, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    const double clipLimit = 40.0;
    declare.in(src, WARMUP_RNG).out(dst);

    cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(clipLimit);
    OCL_TEST_CYCLE() clahe->apply(src, dst);

    SANITY_CHECK(dst);
}

///////////// Canny ////////////////////////

typedef tuple<Size, int, bool> CannyParams;
typedef TestBaseWithParam<CannyParams> CannyFixture;

OCL_PERF_TEST_P(CannyFixture, Canny, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(3, 5), Bool()))
{
    const CannyParams& params = GetParam();
    cv::Size imgSize = get<0>(params);
    int apertureSize = get<1>(params);
    bool L2Grad = get<2>(params);

    Mat _img = imread(getDataPath("gpu/stereobm/aloe-L.png"), cv::IMREAD_GRAYSCALE);
    ASSERT_TRUE(!_img.empty()) << "can't open aloe-L.png";

    UMat img;
    cv::resize(_img, img, imgSize);
    UMat edges(img.size(), CV_8UC1);

    declare.in(img).out(edges);

    PERF_SAMPLE_BEGIN();
        cv::Canny(img, edges, 50.0, 100.0, apertureSize, L2Grad);
    PERF_SAMPLE_END();

    SANITY_CHECK_NOTHING();
}

} } // namespace cvtest::ocl


text:
package cn.edu.ruc.iir.rainbow.web.hive.util;

import java.sql.*;

/**
 * rainbow
 *
 * @author guodong
 */
public class HiveClient {
    private final String driverName = "org.apache.hive.jdbc.HiveDriver";
    private Connection conn;

    private static HiveClient instance = null;

    private HiveClient(String hostUrl, String userName, String passWord) {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            // todo exception handler
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection(hostUrl, userName, passWord);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static HiveClient Instance(String hostUrl, String userName, String passWord) {
        if (instance == null) {
            instance = new HiveClient(hostUrl, userName, passWord);
        }
        return instance;
    }

    public void execute(String statement) {
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            stmt.execute(statement);
        } catch (SQLException e) {
            // todo exception handler
            e.printStackTrace();
        }
    }

    public ResultSet select(String statement) {
        ResultSet res = null;
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            res = stmt.executeQuery(statement);
        } catch (SQLException e) {
            // todo exception handler
            e.printStackTrace();
        }
        return res;
    }

    public int IsTableExist(String table) {
        int num = -1;
        ResultSet res = null;
        try {
            res = instance.select("select count(*) from " + table);
            if (res != null)
                while (res.next()) {
                    num = Integer.valueOf(res.getString(1));
                }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    public void drop(String table) {
        execute("DROP TABLE IF EXISTS " + table);
    }
}


text:
    <item>{{ $show := index (where (where .Site.Pages "Type" "show") "Slug" .Params.show) 0 }}{{ $hosts := where (where .Site.Pages "Type" "person") "Slug" "in" .Params.hosts }}
      <title>{{ .Params.number }}: {{ .Title }}</title>
      <description>{{ "<![CDATA[" | safeHTML }}
{{ .Content | chomp | safeHTML }}
{{ "]]>" | safeHTML }}</description>
      <pubDate>{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 -0700" | safeHTML }}</pubDate>
      <enclosure url="{{ .Params.enclosureurl }}" length="{{ .Params.enclosurelength }}" type="{{ if isset .Params "enclosuretype" }}{{ .Params.enclosuretype }}{{ else }}audio/mp3{{ end }}"/>
      <link>{{ .Permalink }}</link>
      <guid isPermaLink="false">{{ .Params.guid }}</guid>
      <itunes:author>{{ if isset .Params "author" }}{{ .Params.author }}{{ else }}{{ $show.Params.author }}{{ end }}</itunes:author>
      <itunes:subtitle>{{ if isset .Params "subtitle" }}{{ .Params.subtitle }}{{ else }}{{ .Description }}{{ end }}</itunes:subtitle>
      <itunes:summary>{{ .Description }}</itunes:summary>
      <itunes:explicit>{{ if isset .Params "explicit" }}{{ .Params.explicit }}{{ else }}{{ $.Param "explicit" }}{{ end }}</itunes:explicit>
      <itunes:duration>{{ .Params.duration }}</itunes:duration>
      <content:encoded>{{ .Content | chomp | html }}</content:encoded>
      <itunes:image href="{{ if isset .Params "itunescover" }}{{ .Params.itunescover }}{{ else }}{{ if isset $show.Params "itunescover" }}{{ $show.Params.itunescover }}{{ else }}{{ $.Site.BaseURL }}images/shows/{{ $show.Slug }}-itunes.jpg{{ end }}{{ end }}"/>
    </item>


text:
from itertools import product
from stripstream.pddl.logic.predicates import Predicate
from stripstream.pddl.objects import Type, Constant, Parameter as SSParameter

class VariableType(Type):
    num = 0
    prefix = '_vtype%s'

    def __init__(self, name=None, domain=None):
        if name is None:
            name = self.prefix % VariableType.num
            VariableType.num += 1
        self.value_to_const = {}
        self.const_to_value = {}
        self.domain = domain
        super(VariableType, self).__init__(name, parent=None)

    def __call__(self, value):
        if value not in self.value_to_const:
            if self.domain is not None and value not in self.domain:
                raise ValueError('%s not in the domain of %s' % (value, self))
            name = '%s_%s' % (self.name, len(self.value_to_const))
            const = Constant(name, self)
            self.value_to_const[value] = const
            self.const_to_value[const] = value
        return self.value_to_const[value]

    def get_value(self, const):
        return self.const_to_value[const]

    def param(self, name):
        return FreeParameter(name, self)

VarType = VariableType

def get_value(const):
    return const.type.get_value(const)

class FreeParameter(SSParameter):
    num = 0
    prefix = '_param%s'

    def __init__(self, name, type=None):
        if type is None:
            type = name
            assert isinstance(type, VarType)
            name = self.prefix % FreeParameter.num
            FreeParameter.num += 1
        super(FreeParameter, self).__init__(name, type)

Par = FreeParameter

def var_name(var):
    return var[0]

def var_args(var):
    return var[1:]

def split_var(var):
    return var_name(var), var_args(var)

class Variable(object):

    def __init__(self, name, dtype, args=[]):
        self.name = name
        self.dtype = dtype
        self.args = args
        assert all(arg.domain is not None for arg in args)
        self.predicate = Predicate('%s_at' % name, args + [dtype])

    def __repr__(self):
        if not self.args:
            return self.name
        return '%s(%s)' % (self.name, ','.join(map(repr, self.args)))

Var = Variable

class VariableSet(object):

    def __init__(self, name):
        self.name = name

    def __getitem__(self, var):
        if not isinstance(var, tuple):
            var = (var,)
        return VarMember(self, var)

    def __call__(self, *args):
        return self.__getitem__(args)

    def __repr__(self):
        return self.name

X = VariableSet('x')
U = VariableSet('u')
nX = VariableSet('nx')

class VariableMember(object):

    def __init__(self, temp, var):
        self.temp = temp
        self.var = var

    def __eq__(self, other):
        return type(self) == type(other) and self.temp == other.temp and self.var == other.var

    def __ne__(self, other):
        return not(self == other)

    def __hash__(self):
        return hash((self.__class__, self.temp, self.var))

    def __repr__(self):
        return '%s[%s]' % (self.temp, ','.join(repr(item) for item in self.var))

VarMember = VariableMember

def is_parameter(v):
    return isinstance(v, FreeParameter) or isinstance(v, VarMember)

def is_constant(v):
    return not is_parameter(v)

def expand_variables(vars):
    expanded_vars = set()
    for var in vars:
        values = [[var.name]] + [arg.domain for arg in var.args]
        for combo in product(*values):
            assert var not in expanded_vars
            expanded_vars.add(combo)
    return expanded_vars

def make_var_constants(var, var_map):
    name, args = split_var(var)
    assert len(args) == len(var_map[name].args)
    return [ty(arg) if not isinstance(arg, FreeParameter) else arg for ty, arg in zip(var_map[name].args, args)]


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface net.sf.jasperreports.engine.JRRenderable (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sf.jasperreports.engine.JRRenderable

Packages that use JRRenderable

Package
Description

net.sf.jasperreports.charts.util

Contains utility classes for complex chart customization.

net.sf.jasperreports.components.barbecue

Contains classes for the built-in Barbecue component.

net.sf.jasperreports.components.list

Contains classes for the built-in List component.

net.sf.jasperreports.components.spiderchart

Contains classes for the built-in Spider Chart component.

net.sf.jasperreports.engine

Provides access to the library's main functionality through facade classes for compiling, filling
 and exporting reports and also publishes the library's main interfaces and classes.

net.sf.jasperreports.engine.base

Contains base implementations for the library's main interfaces.

net.sf.jasperreports.engine.fill

Contains fill time implementations for the library's main interfaces and the entire
 engine used in the filling process (the actual core of JasperReports).

net.sf.jasperreports.engine.util

Contains utility classes for the core library.

net.sf.jasperreports.renderers

Contains image renderer implementations.

Uses of JRRenderable in net.sf.jasperreports.charts.util

Classes in net.sf.jasperreports.charts.util that implement JRRenderable

Modifier and Type
Class and Description

class
DrawChartRenderer

Methods in net.sf.jasperreports.charts.util that return JRRenderable

Modifier and Type
Method and Description

JRRenderable
AbstractChartRenderableFactory.getRenderer(org.jfree.chart.JFreeChart chart,
           ChartHyperlinkProvider chartHyperlinkProvider,
           java.awt.geom.Rectangle2D rectangle)

Deprecated.

Replaced by ChartRenderableFactory.getRenderable(JasperReportsContext, JFreeChart, ChartHyperlinkProvider, Rectangle2D).

JRRenderable
ChartUtil.WrappingChartRenderableFactory.getRenderer(org.jfree.chart.JFreeChart chart,
           ChartHyperlinkProvider chartHyperlinkProvider,
           java.awt.geom.Rectangle2D rectangle)

Deprecated.

JRRenderable
ChartRendererFactory.getRenderer(org.jfree.chart.JFreeChart chart,
           ChartHyperlinkProvider chartHyperlinkProvider,
           java.awt.geom.Rectangle2D rectangle)

Deprecated.

Replaced by ChartRendererFactory.getRenderer(JFreeChart, ChartHyperlinkProvider, Rectangle2D).

Uses of JRRenderable in net.sf.jasperreports.components.barbecue

Classes in net.sf.jasperreports.components.barbecue that implement JRRenderable

Modifier and Type
Class and Description

class
BarbecueRenderer

Uses of JRRenderable in net.sf.jasperreports.components.list

Classes in net.sf.jasperreports.components.list that implement JRRenderable

Modifier and Type
Class and Description

class
UnusedSpaceImageRenderer

Am image renderer used to mark the unused vertical space in a list
 component preview.

Uses of JRRenderable in net.sf.jasperreports.components.spiderchart

Methods in net.sf.jasperreports.components.spiderchart that return JRRenderable

Modifier and Type
Method and Description

static JRRenderable
SpiderChartRendererEvaluator.evaluateRenderer(JRComponentElement element,
                SpiderChartSharedBean spiderchartBean,
                ChartCustomizer chartCustomizer,
                java.lang.String defaultRenderType,
                java.lang.String datasetType)

Deprecated.

Replaced by SpiderChartRendererEvaluator.evaluateRenderable(JasperReportsContext, JRComponentElement, SpiderChartSharedBean, ChartCustomizer, String, String).

Uses of JRRenderable in net.sf.jasperreports.engine

Subinterfaces of JRRenderable in net.sf.jasperreports.engine

Modifier and Type
Interface and Description

interface
ImageMapRenderable

Image renderer able to produce image maps.

interface
JRImageMapRenderer

Deprecated.

Replaced by ImageMapRenderable.

interface
Renderable

Classes in net.sf.jasperreports.engine that implement JRRenderable

Modifier and Type
Class and Description

class
JRAbstractRenderer

class
JRAbstractSvgRenderer

class
JRImageRenderer

Provides functionality for image rendering.

class
JRWrappingSvgRenderer

Methods in net.sf.jasperreports.engine that return JRRenderable

Modifier and Type
Method and Description

static JRRenderable
JRImageRenderer.getInstance(java.io.File file,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(File, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getInstance(java.awt.Image image,
           byte imageType,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(Image, ImageTypeEnum, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getInstance(java.awt.Image img,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(Image, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getInstance(java.io.InputStream is,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(InputStream, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getInstance(java.lang.String imageLocation)

Deprecated.

Replaced by RenderableUtil.getRenderable(String).

static JRRenderable
JRImageRenderer.getInstance(java.lang.String imageLocation,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(String, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getInstance(java.lang.String imageLocation,
           OnErrorTypeEnum onErrorType,
           boolean isLazy)

Deprecated.

Replaced by RenderableUtil.getRenderable(String, OnErrorTypeEnum, boolean).

static JRRenderable
JRImageRenderer.getInstance(java.net.URL url,
           OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getRenderable(URL, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getOnErrorRendererForDimension(JRRenderable renderer,
                              OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getOnErrorRendererForDimension(Renderable, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getOnErrorRendererForImageData(JRRenderable renderer,
                              OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getOnErrorRendererForImageData(Renderable, OnErrorTypeEnum).

JRRenderable
JRPrintImage.getRenderer()

Deprecated.

Replaced by JRPrintImage.getRenderable().

Methods in net.sf.jasperreports.engine with parameters of type JRRenderable

Modifier and Type
Method and Description

static JRRenderable
JRImageRenderer.getOnErrorRendererForDimension(JRRenderable renderer,
                              OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getOnErrorRendererForDimension(Renderable, OnErrorTypeEnum).

static JRRenderable
JRImageRenderer.getOnErrorRendererForImageData(JRRenderable renderer,
                              OnErrorTypeEnum onErrorType)

Deprecated.

Replaced by RenderableUtil.getOnErrorRendererForImageData(Renderable, OnErrorTypeEnum).

static Renderable
RenderableUtil.getWrappingRenderable(JRRenderable deprecatedRenderer)

Deprecated.

To be removed.

void
JRPrintImage.setRenderer(JRRenderable renderer)

Deprecated.

Replaced by JRPrintImage.setRenderable(Renderable).

Constructors in net.sf.jasperreports.engine with parameters of type JRRenderable

Constructor and Description

JRWrappingSvgRenderer(JRRenderable renderer,
                     java.awt.geom.Dimension2D elementDimension,
                     java.awt.Color backcolor)

Deprecated.

Replaced by JRWrappingSvgRenderer.JRWrappingSvgRenderer(Renderable, Dimension2D, Color).

Uses of JRRenderable in net.sf.jasperreports.engine.base

Classes in net.sf.jasperreports.engine.base that implement JRRenderable

Modifier and Type
Class and Description

static class
JRVirtualPrintPage.JRIdHolderRenderer

Dummy image renderer that only stores the ID of a cached renderer.

Methods in net.sf.jasperreports.engine.base that return JRRenderable

Modifier and Type
Method and Description

JRRenderable
JRBasePrintImage.getRenderer()

Deprecated.

Replaced by JRBasePrintImage.getRenderable().

Methods in net.sf.jasperreports.engine.base with parameters of type JRRenderable

Modifier and Type
Method and Description

void
JRBasePrintImage.setRenderer(JRRenderable renderer)

Deprecated.

Replaced by JRBasePrintImage.setRenderable(Renderable).

Uses of JRRenderable in net.sf.jasperreports.engine.fill

Methods in net.sf.jasperreports.engine.fill that return JRRenderable

Modifier and Type
Method and Description

JRRenderable
JRTemplatePrintImage.getRenderer()

Deprecated.

Replaced by JRTemplatePrintImage.getRenderable().

Methods in net.sf.jasperreports.engine.fill with parameters of type JRRenderable

Modifier and Type
Method and Description

void
JRTemplatePrintImage.setRenderer(JRRenderable renderer)

Deprecated.

Replaced by JRTemplatePrintImage.setRenderable(Renderable).

Uses of JRRenderable in net.sf.jasperreports.engine.util

Classes in net.sf.jasperreports.engine.util that implement JRRenderable

Modifier and Type
Class and Description

class
WrappingImageMapRenderable

Deprecated.

To be removed.

class
WrappingRenderable

Deprecated.

To be removed.

Constructors in net.sf.jasperreports.engine.util with parameters of type JRRenderable

Constructor and Description

WrappingRenderable(JRRenderable renderable)

Deprecated.

Uses of JRRenderable in net.sf.jasperreports.renderers

Classes in net.sf.jasperreports.renderers that implement JRRenderable

Modifier and Type
Class and Description

class
AwtComponentRenderer

class
BatikRenderer

SVG renderer implementation based on Batik.

class
JCommonDrawableRenderer

A wrapper for the Drawable interface in the JCommon library: you will need the
 JCommon classes in your classpath to compile this class.

class
JFreeChartRenderer

Deprecated.

class
JRSimpleImageMapRenderer

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
var React = require('react');

var TextArea = React.createClass({
  render: function() {
    return (
      <textarea
        className="form-control"
        style={{resize: "none", width: "600px", maxWidth: "600px", height: "300px", maxHeight: "300px"}}
      >
      </textarea>
    )
  }
});

module.exports = TextArea;


text:
namespace Ui {
class SamplingWithFrameTrackInputWidget;
}

Q_DECLARE_METATYPE(::orbit_mizar_base::TID);

namespace orbit_mizar_widgets {

class SamplingWithFrameTrackInputWidgetBase : public QWidget {
  Q_OBJECT
  using TID = ::orbit_mizar_base::TID;
  using FrameTrackId = ::orbit_mizar_data::FrameTrackId;
  using RelativeTimeNs = ::orbit_mizar_base::RelativeTimeNs;

 public:
  ~SamplingWithFrameTrackInputWidgetBase() override;

  [[nodiscard]] orbit_mizar_data::HalfOfSamplingWithFrameTrackReportConfig MakeConfig() const;

 public slots:
  void OnThreadSelectionChanged();
  void OnFrameTrackSelectionChanged(int index);
  void OnStartMsChanged(const QString& time_ms);

 private:
  std::unique_ptr<Ui::SamplingWithFrameTrackInputWidget> ui_;

 protected:
  static int constexpr kTidRole = Qt::UserRole + 1;

  explicit SamplingWithFrameTrackInputWidgetBase(QWidget* parent = nullptr);

  [[nodiscard]] QLabel* GetTitle() const;
  [[nodiscard]] QLabel* GetFileName() const;
  [[nodiscard]] QListWidget* GetThreadList() const;
  [[nodiscard]] QComboBox* GetFrameTrackList() const;
  [[nodiscard]] QLineEdit* GetStartMs() const;

  absl::flat_hash_set<TID> selected_tids_;

  // std::numeric_limits<uint64_t>::max() ns corresponds to malformed input
  RelativeTimeNs start_timestamp_{0};

 private:
  FrameTrackId frame_track_id_{};
};

template <typename PairedData, typename FrameTrackListModel>
class SamplingWithFrameTrackInputWidgetTmpl : public SamplingWithFrameTrackInputWidgetBase {
  using TID = ::orbit_mizar_base::TID;
  using FrameTrackId = ::orbit_mizar_data::FrameTrackId;
  using FrameTrackInfo = ::orbit_mizar_data::FrameTrackInfo;
  using PresentEvent = ::orbit_grpc_protos::PresentEvent;
  using ScopeInfo = ::orbit_client_data::ScopeInfo;

 public:
  SamplingWithFrameTrackInputWidgetTmpl() = delete;
  explicit SamplingWithFrameTrackInputWidgetTmpl(QWidget* parent)
      : SamplingWithFrameTrackInputWidgetBase(parent) {}
  ~SamplingWithFrameTrackInputWidgetTmpl() override = default;

  void Init(const PairedData& data, const QString& title, const QString& file_name) {
    InitTitle(title);
    InitFileName(file_name);
    InitThreadList(data);
    InitFrameTrackList(data);
    InitStartMs();
  }

 private:
  void InitTitle(const QString& title) { GetTitle()->setText(title); }

  void InitFileName(const QString& file_name) { GetFileName()->setText(file_name); }

  void InitThreadList(const PairedData& data) {
    QListWidget* list = GetThreadList();
    list->setSelectionMode(QAbstractItemView::ExtendedSelection);

    const absl::flat_hash_map<TID, std::string>& tid_to_name = data.TidToNames();
    const absl::flat_hash_map<TID, uint64_t>& counts = data.TidToCallstackSampleCounts();

    std::vector<std::pair<TID, uint64_t>> counts_sorted(std::begin(counts), std::end(counts));

    orbit_base::sort(std::begin(counts_sorted), std::end(counts_sorted),
                     &std::pair<TID, uint64_t>::second, std::greater<>{});
    for (const auto& [tid, unused_count] : counts_sorted) {
      auto item = std::make_unique<QListWidgetItem>(
          QString::fromStdString(absl::StrFormat("[%u] %s", *tid, tid_to_name.at(tid))));
      item->setData(kTidRole, QVariant::fromValue(tid));
      list->addItem(item.release());
    }
  }

  void InitFrameTrackList(const PairedData& data) {
    auto model =
        std::make_unique<FrameTrackListModel>(&data, &selected_tids_, &start_timestamp_, parent());

    GetFrameTrackList()->setModel(model.release());
    OnFrameTrackSelectionChanged(0);
  }

  void InitStartMs() {
    GetStartMs()->setValidator(new QIntValidator(0, std::numeric_limits<int>::max(), this));
    GetStartMs()->setText("0");
  }
};

using SamplingWithFrameTrackInputWidget =
    SamplingWithFrameTrackInputWidgetTmpl<orbit_mizar_data::MizarPairedData,
                                          orbit_mizar_models::FrameTrackListModel>;

}  // namespace orbit_mizar_widgets

#endif  // MIZAR_WIDGETS_SAMPLING_WITH_FRAME_TRACK_INPUT_WIDGET_H_


text:
import { ApproxStructure, Keys } from '@ephox/agar';
import { describe, it } from '@ephox/bedrock-client';
import { Unicode } from '@ephox/katamari';
import { TinyAssertions, TinyContentActions, TinyHooks, TinySelections } from '@ephox/wrap-mcagar';

import Editor from 'tinymce/core/api/Editor';
import * as Zwsp from 'tinymce/core/text/Zwsp';

import * as KeyUtils from '../../module/test/KeyUtils';

describe('browser.tinymce.core.delete.CaretBoundaryDeleteTest', () => {
  const hook = TinyHooks.bddSetupLight<Editor>({
    base_url: '/project/tinymce/js/tinymce'
  }, [], true);

  const cefStruct = (text: string) => ApproxStructure.build((s, str) => s.element('span', {
    attrs: {
      contenteditable: str.is('false')
    },
    children: [
      s.text(str.is(text))
    ]
  }));

  const videoStruct = ApproxStructure.build((s, str) => s.element('video', {
    attrs: {
      controls: str.is('controls')
    },
    children: [
      s.element('source', {
        attrs: {
          src: str.is('custom/video.mp4')
        }
      })
    ]
  }));

  it('TINY-2998: Should delete single space between cef elements', () => {
    const editor = hook.editor();
    editor.setContent('
a b
');
    TinySelections.setSelection(editor, [ 0, 2 ], 1, [ 0, 2 ], 1);
    TinyContentActions.keystroke(editor, Keys.backspace());
    TinyAssertions.assertSelection(editor, [ 0, 1 ], 1, [ 0, 1 ], 1);
    TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) =>
      s.element('body', {
        children: [
          s.element('p', {
            children: [
              cefStruct('a'),
              s.text(str.is(Zwsp.ZWSP)),
              cefStruct('b'),
              s.text(str.is(Unicode.nbsp))
            ]
          })
        ]
      })
    ));
  });

  it('TINY-2998: Should add fake caret if we delete content beside cef elements', () => {
    const editor = hook.editor();
    editor.setContent('
a
');
    TinySelections.setSelection(editor, [ 0, 2 ], 1, [ 0, 2 ], 1);
    TinyContentActions.keystroke(editor, Keys.backspace());
    TinyAssertions.assertSelection(editor, [ 0, 1 ], 1, [ 0, 1 ], 1);
    TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) =>
      s.element('body', {
        children: [
          s.element('p', {
            children: [
              cefStruct('a'),
              s.text(str.is(Zwsp.ZWSP))
            ]
          })
        ]
      })
    ));
  });

  it('TINY-2998: Should add fake caret if we delete range beside cef', () => {
    const editor = hook.editor();
    editor.setContent('
a abc
');
    TinySelections.setSelection(editor, [ 0, 2 ], 0, [ 0, 2 ], 4);
    TinyContentActions.keystroke(editor, Keys.backspace());
    TinyAssertions.assertSelection(editor, [ 0, 1 ], 1, [ 0, 1 ], 1);
    TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) =>
      s.element('body', {
        children: [
          s.element('p', {
            children: [
              cefStruct('a'),
              s.text(str.is(Zwsp.ZWSP))
            ]
          })
        ]
      })
    ));
  });

  it('TINY-4211: Should add fake caret if we type and then delete content beside media elements', () => {
    const editor = hook.editor();
    editor.setContent('
<video controls="controls"><source src="custom/video.mp4" /></video>
');
    TinySelections.select(editor, 'video', []);
    // Pressing right will add a fake caret, which will be removed when we press backspace
    TinyContentActions.keystroke(editor, Keys.right());
    KeyUtils.type(editor, 'a');
    TinyAssertions.assertSelection(editor, [ 0, 1 ], 2, [ 0, 1 ], 2);
    TinyContentActions.keystroke(editor, Keys.backspace());
    TinyAssertions.assertSelection(editor, [ 0, 1 ], 1, [ 0, 1 ], 1);
    TinyAssertions.assertContentStructure(editor, ApproxStructure.build((s, str) =>
      s.element('body', {
        children: [
          s.element('p', {
            children: [
              videoStruct,
              s.text(str.is(Zwsp.ZWSP))
            ]
          })
        ]
      })
    ));
  });
});


text:
package io.github.miracelwhipp.net.cs.plugin.compile;

import io.github.miracelwhipp.net.common.DependencyProvider;
import io.github.miracelwhipp.net.provider.CSharpCompilerProvider;
import io.github.miracelwhipp.net.provider.NetFrameworkProvider;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;

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

/**
 * This class interfaces the command line to invoke the c# compiler.
 *
 * @author miracelwhipp
 */
public class CSharpCompiler {

	private final File runtimeWrapper;
	private final SourceFiles sourceFiles;
	private final CSharpCompilerOptions compilerOptions;
	private final AssemblyFileProperties assemblyFileProperties;

	private final Log logger;
	private final NetFrameworkProvider frameworkProvider;
	private final CSharpCompilerProvider compilerProvider;

	public CSharpCompiler(
			File runtimeWrapper,
			SourceFiles sourceFiles,
			CSharpCompilerOptions compilerOptions,
			AssemblyFileProperties assemblyFileProperties,
			Log logger,
			NetFrameworkProvider frameworkProvider,
			CSharpCompilerProvider compilerProvider
	) {
		this.runtimeWrapper = runtimeWrapper;
		this.sourceFiles = sourceFiles;
		this.compilerOptions = compilerOptions;
		this.assemblyFileProperties = assemblyFileProperties;
		this.logger = logger;
		this.frameworkProvider = frameworkProvider;
		this.compilerProvider = compilerProvider;
	}

	public File compile() throws MojoFailureException {

		try {

			File compilerExecutable = compilerProvider.getCSharpCompiler();

			ProcessBuilder processBuilder = runtimeWrapper == null ?
					new ProcessBuilder() :
					new ProcessBuilder(runtimeWrapper.getAbsolutePath());

			processBuilder.command().add(compilerExecutable.getPath());

			processBuilder.command().add("/nostdlib");
			processBuilder.command().add("/noconfig");
			processBuilder.command().add("/utf8output");

			if (compilerOptions.isUnsafe()) {
				processBuilder.command().add("/unsafe");
			}

			for (String define : compilerOptions.getDefines()) {
				processBuilder.command().add("/define:" + define);
			}

			if (assemblyFileProperties.getPlatform() != null) {
				processBuilder.command().add("/platform:" + assemblyFileProperties.getPlatform());
			}

			processBuilder.command().add("/target:" + assemblyFileProperties.getTargetType().getArgumentId());

			String outFileName = assemblyFileProperties.getTargetFileName() + "." +
					assemblyFileProperties.getTargetType().getFileSuffix();

			File targetFile = new File(sourceFiles.getWorkingDirectory(), outFileName).getAbsoluteFile();

			processBuilder.command().add("/out:" + outFileName);

			boolean sourceFilesExistent = false;

			for (File csSourceDirectory : sourceFiles.getCsSourceDirectories()) {

				if (!csSourceDirectory.exists()) {

					continue;
				}

				Collection<File> files = FileUtils.listFiles(csSourceDirectory, new String[]{"cs"}, true);

				for (File file : files) {

					processBuilder.command().add(file.getAbsolutePath());
					sourceFilesExistent = true;
				}
			}

			if (!sourceFilesExistent) {

				return null;
			}

			List<String> frameworkLibraries = new ArrayList<>();

			if (sourceFiles.getFrameworkReferences() != null) {
				frameworkLibraries.addAll(sourceFiles.getFrameworkReferences());
			}

			for (String frameworkLibrary : frameworkLibraries) {

				File library = frameworkProvider.getFrameworkLibrary(frameworkLibrary);

				if (library == null) {

					throw new MojoFailureException("cannot find framework library " + frameworkLibrary);
				}

				library = DependencyProvider.provideFile(library, null, sourceFiles.getWorkingDirectory());

				processBuilder.command().add("/reference:" + library.getAbsolutePath());
			}

			for (File referenceFile : sourceFiles.getReferenceFiles()) {

				if (referenceFile.getName().endsWith(".netmodule") || referenceFile.getName().endsWith(".obj")) {

					processBuilder.command().add("/addmodule:" + referenceFile.getAbsolutePath());

				} else {

					processBuilder.command().add("/reference:" + referenceFile.getAbsolutePath());
				}
			}

			for (String resource : sourceFiles.getResources()) {
				processBuilder.command().add("/resource:" + resource);
			}

			if (sourceFiles.getKeyFile() != null) {

				processBuilder.command().add("/keyfile:" + sourceFiles.getKeyFile().getAbsolutePath());
			}

			logger.debug("executing csc:");
			for (String arg : processBuilder.command()) {
				logger.debug(arg);
			}

			processBuilder.directory(sourceFiles.getWorkingDirectory());
			processBuilder.inheritIO();

			Process process = processBuilder.start();

			process.waitFor();

			int exitValue = process.exitValue();

			if (exitValue != 0) {

				throw new MojoFailureException("c# compiler finished with exit value " + exitValue);
			}

			return targetFile;

		} catch (IOException | InterruptedException e) {

			throw new MojoFailureException(e.getMessage(), e);
		}
	}
}


text:
module ui {

    export class CheckButton extends View {
        static UI: ui.UIDefinition = {
            id: "container",
            tag: "button",
            attributes: {"class": "btn-check"},
            events: {"click": "doSelect"},
        };

        container: HTMLButtonElement;
        click(e: Event) {};

        private icon: HTMLElement;
        private selected: boolean;
        private disabled: boolean;

        initialize (): void {
            this.selected = false;
            this.disabled = false;

            this.icon = document.createElement("i");
            this.container.innerHTML = "";
            this.container.appendChild(this.icon);

            this.render();
        }

        doSelect(e: Event): any {
            this.setSelected(!this.isSelected());
            this.click(e);
        }

        isSelected(): boolean {
            return this.selected;
        }

        setSelected(value: boolean) {
            this.selected = value;
            this.render();
        }

        isDisabled(): boolean {
            return this.disabled;
        }

        setDisabled(value: boolean) {
            this.disabled = value;
            this.render();
        }

        private render(): void {
			this.icon.setAttribute("class", this.selected ? "fa fa-check-square-o" : "fa fa-square-o");
            this.container.disabled = this.disabled;
        }
    }
}


text:
module.exports = {run: function(state, config) {
  return new Promise(function(resolve, reject) {
    const Statement = require('./../../lib/Statement');

    const confirmation = 'Sure thing!';
    const numberOfWords = state.getField('payload').split(' ').length;

    // process the statement
    const statement = new Statement(state.getField('payload'), false);
    const intent = statement.getImpliedIntent();
    const context = statement.getImpliedContext();
    // get the action
    let actionStatement = 'The implied intent is ' + intent + '.\n';
    if (intent === undefined) {
      actionStatement = 'The statement has no implied intent.\n';
    }

    // get the context
    let contextStatement = 'It has an implied context of ' + context + '.\n';
    if (typeof (context) === 'undefined') {
      contextStatement = 'The statement has no implied context.\n';
    }

    // break down each word in the sentence
    let wordTypes = '';
    for (let i = 0; i < statement.wordListLC.length; i++) {
      if (statement.wordListLC[i] === '\'') {
        wordTypes += 'Then an apostrophe.\n';
      } else if (statement.wordListLC[i].length === 1
          && statement.wordListLC[i] !== 's') {
        wordTypes += 'Then the letter "' + statement.wordListLC[i] + '".\n';
      } else {
        wordTypes += 'The word "' + statement.wordListLC[i];
        wordTypes += '" is a ' + statement.wordTypeNames[i] + '.\n';
      }
    }

    state.setFinal(
      confirmation + ' There is ' +
      numberOfWords + ' words in the sentence.\n' +
      actionStatement + contextStatement + wordTypes
    );
    return resolve(state);
  });
}};