text:
//
//  STAppDelegate.h
//  SSuggestText
//
//  Created by CocoaPods on 08/17/2014.
//  Copyright (c) 2014 saulogt. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "SSuggestText.h"
#import "SSuggestCell.h"
#import "SSuggestTextDelegate.h"

#ifdef DEBUG
#   define NSLogD(...) NSLog(__VA_ARGS__)
#else
#   define NSLogD(...)
#endif
#undef NSLogD
#define NSLogD(...)

@interface SSuggestText()<UITableViewDelegate, UITableViewDataSource, UIPopoverControllerDelegate>

@property (nonatomic) NSMutableArray *tagViews;

@property (readonly,nonatomic) UITableViewController* tableVC;
@property (nonatomic) UIPopoverController* poc;

@property (nonatomic) NSArray* filteredTags;

//@property (nonatomic) NSString* searchText;

@property (nonatomic) SSuggestTextDelegate* textViewDelegate;

@property (nonatomic) NSString* partialSeach;

@property (nonatomic) BOOL hasWindow;

@end

static NSString* const dataKeySuggest = @"suggestDataKey";

@implementation SSuggestText

@synthesize tableVC = _tableVC;
@synthesize possibleTags = _possibleTags;

#pragma mark - popup

- (void)matchStrings:(NSString *)letters {
    if (self.possibleTags.count > 0) {
        if (self.keepSuggestPopoverOpen && [letters isEqualToString:@""])
        {
            self.filteredTags = [self.possibleTags copy];
        }
        else
        {
            self.filteredTags = [self.possibleTags
                             filteredArrayUsingPredicate:
                             [NSPredicate predicateWithFormat:@"tagDesc contains[cd] %@", letters]];
        }
        [self.tableVC.tableView reloadData];
    }

    NSLogD(@"letters: '%@', filteredCount: %d", letters, self.filteredTags.count);
}

- (void)showPopOverList {
    if (!self.hasWindow)
        return;

    if (self.filteredTags.count == 0 && !self.enableTagCreation){
        if(self.keepSuggestPopoverOpen)
        {
            ////////////////////////////////////////////
            [_poc presentPopoverFromRect:self.frame
                                  inView:self.superview
                permittedArrowDirections:UIPopoverArrowDirectionUp
                                animated:YES];
        }
        else
        {
            [_poc dismissPopoverAnimated:YES];
        }
    } else if (!_poc.isPopoverVisible) {
        [_poc presentPopoverFromRect:self.frame
                              inView:self.superview
            permittedArrowDirections:UIPopoverArrowDirectionUp
                            animated:YES];
    }
}

-(void)didMoveToWindow
{
    [super didMoveToWindow];
    self.hasWindow = YES;
}

#pragma mark - getter n setters

-(UITableViewController *)tableVC
{
    if (_tableVC == nil)
    {
        _tableVC = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
        _tableVC.tableView.delegate = self;
        _tableVC.tableView.dataSource = self;
        [_tableVC.tableView registerClass:[SSuggestCell class] forCellReuseIdentifier:@"Cell Red"];
        [_tableVC.tableView registerClass:[SSuggestCell class] forCellReuseIdentifier:@"Cell Use"];
    }
    return _tableVC;
}

-(void)setPossibleTags:(NSArray *)possibleTags
{
    NSMutableArray* larray;
    _possibleTags = larray = [[NSMutableArray alloc] init];
    for (id obj in possibleTags) {
        if ([obj isKindOfClass:[SSuggestTag class]]) {
            [larray addObject: obj];
        }
        else
        {
            [larray addObject: [SSuggestTag tagDataWithDictionary: obj]];
        }
    }
}

-(NSArray *)possibleTags
{
    if (_possibleTags == nil)
    {
        _possibleTags = [[NSMutableArray alloc] init];
    }
    return _possibleTags;
}

-(void)setTagList:(NSMutableArray *)tagList
{
    _tagList = tagList;

    [self recreateAttributedStringByTags];
    [self setNeedsDisplay];

    // Pass Delegate
    /*
    if (self.delegate && [self.delegate respondsToSelector:@selector(textViewDidChange:)])
        [self.delegate textViewDidChange:self];
    */

    if (self.suggestDelegate)
        [self.suggestDelegate suggestText: self newTagList: tagList];
}

//
//-(NSString *)searchText
//{
//    if (_searchText == nil)
//    {
//        _searchText = [[NSMutableString alloc] init];
//    }
//    return _searchText;
//}

#pragma mark - setup

-(void) setup{

    self.contentMode = UIViewContentModeRedraw;
    self.tagList = [[NSMutableArray alloc] init];

    self.delegate = self.textViewDelegate = [[SSuggestTextDelegate alloc] init];
    self.autocorrectionType = UITextAutocorrectionTypeNo;
    self.poc =
    [[UIPopoverController alloc] initWithContentViewController:self.tableVC];
    self.poc.delegate = self;

    // Some custom apperances
    self.nameTagImage = [[UIImage imageNamed:@"tagImage"] stretchableImageWithLeftCapWidth:4 topCapHeight:4];
    self.nameTagColor = [UIColor colorWithRed:0.00 green:0.54 blue:0.50 alpha:1.0];

}

#pragma mark - initializer

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}

#pragma mark - tableview delegate & datasource

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1){
        static NSString* CellIdentifier = @"Cell Use";
        SSuggestCell* cell = (SSuggestCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] ;

        NSAssert([cell isKindOfClass:[SSuggestCell class]], @"invalid cell type");

        if (cell == nil) {
            cell = [[SSuggestCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier];
        }

        SSuggestTag* tagData  = [self.filteredTags objectAtIndex: indexPath.row];

        cell.textLabel.text = tagData.tagDesc;
        cell.tagData = tagData;

        return cell;
    }
    else if (indexPath.section == 0)
    {
        static NSString* CellIdentifier = @"Cell Red";
        SSuggestCell* cell = (SSuggestCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] ;

        NSAssert([cell isKindOfClass:[SSuggestCell class]], @"invalid cell type");

        if (cell == nil) {
            cell = [[SSuggestCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier];
        }

        //SSuggestTag* tagData  = [self.filteredTags objectAtIndex: indexPath.row];

        cell.textLabel.text = [NSString stringWithFormat: @"+\"%@\"", self.partialSeach];
        cell.textLabel.textColor = [UIColor redColor];
        cell.tagData = nil;

        return cell;

    }
    else if (indexPath.section == 2)
    {
        static NSString* CellIdentifier = @"Cell Red";
        SSuggestCell* cell = (SSuggestCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath] ;

        NSAssert([cell isKindOfClass:[SSuggestCell class]], @"invalid cell type");

        if (cell == nil) {
            cell = [[SSuggestCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier];
        }

        //SSuggestTag* tagData  = [self.filteredTags objectAtIndex: indexPath.row];

        cell.textLabel.text = [NSString stringWithFormat: @"Opção inexistente!"];//, self.partialSeach];
        cell.textLabel.textColor = [UIColor redColor];
        cell.tagData = nil;

        return cell;

    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2){
        if (self.filteredTags.count == 0)
            return (self.keepSuggestPopoverOpen && self.partialSeach.length > 0 ? 1 : 0);
    }
    else if (section == 1)
        return self.filteredTags.count;
    else if (section == 0)
        return (self.enableTagCreation && self.partialSeach.length > 2 ? 1 : 0);

    return 0;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1){
        SSuggestTag* tagSelected = [self.filteredTags objectAtIndex: indexPath.row];

        NSAssert([tagSelected isKindOfClass:[SSuggestTag class]], @"invalid tag type");

        [self addTag: tagSelected];

        [self.poc dismissPopoverAnimated:YES];

    }
    else if(indexPath.section == 0)
    {
        //Request to add a custom tag
        NSString* partial = self.partialSeach;

        if (partial.length > 2){
            NSArray* filtered = [self.possibleTags
                                 filteredArrayUsingPredicate:
                                 [NSPredicate predicateWithFormat:@"tagDesc = %@", partial]];
            if (filtered.count == 0)
            {
                CFUUIDRef theUUID = CFUUIDCreate(NULL);
                CFStringRef string = CFUUIDCreateString(NULL, theUUID);
                CFRelease(theUUID);
                NSString* ident = (__bridge NSString *)string;

                [self addTag:[SSuggestTag tagDataWithDesc: partial AndId:[NSString stringWithFormat: @"Custom:%@", ident]]];
                [self.poc dismissPopoverAnimated:YES];
            }
        }
    }
    else if (indexPath.section == 2)
    {
        [self endEditing:NO];
    }
}

#pragma mark - paint

- (void)drawRect:(CGRect)rect
{

    [super drawRect:rect];

    for (UIView *tagView in self.tagViews) {
        [tagView removeFromSuperview];
    }

    if (self.tagList == nil || self.attributedText.length  < 1) return;

    // 3. Find and draw

    [self.attributedText enumerateAttribute:dataKeySuggest inRange:NSMakeRange(0, self.attributedText.length)
                                    options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {

                                        if ([self tagForId:value]){
                                            //                                            NSLog(@"%d, %d",range.location, range.length);
                                            CFRange cfRange = CFRangeMake(range.location, range.length);
                                            [self calculatingTagRectAndDraw:cfRange];

                                        }

                                    }];

}

- (void) calculatingTagRectAndDraw:(CFRange) tagStringRange
{
    /*
     Caclulating Rect and Draw
     */

    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();

    UITextView *textView = self;

    // 4) Find rect
    CFRange stringRange = tagStringRange;
    UITextPosition *begin = [textView positionFromPosition:textView.beginningOfDocument offset:stringRange.location];
    UITextPosition *end = [textView positionFromPosition:begin offset:stringRange.length];
    UITextRange *textRange = [textView textRangeFromPosition:begin toPosition:end];

    // 5) Need 2line?
    CGPoint firstCharPosition = [textView caretRectForPosition:begin].origin;
    CGPoint lastCharPosition = [textView caretRectForPosition:end].origin;

    if (firstCharPosition.y < lastCharPosition.y){

        // Finf pos of first line
        float secondY = firstCharPosition.y;
        CFRange secondStrRange = CFRangeMake(stringRange.location, 1); // first time is just init, not have mean of value
        NSInteger secondPos = stringRange.location;
        NSInteger cnt = 0;

        while (secondY < lastCharPosition.y) {

            secondPos++;
            cnt++;

            secondStrRange = CFRangeMake(secondPos, stringRange.length - cnt);
            UITextPosition *secondBegin = [textView positionFromPosition:textView.beginningOfDocument offset:secondStrRange.location];
            CGPoint secondPosition = [textView caretRectForPosition:secondBegin].origin;
            secondY = secondPosition.y;

        }

        // Calculate rect
        UITextPosition *secondBegin = [textView positionFromPosition:textView.beginningOfDocument offset:secondStrRange.location];
        UITextPosition *secondEnd = [textView positionFromPosition:secondBegin offset:secondStrRange.length];
        UITextRange *secondTextRange = [textView textRangeFromPosition:secondBegin toPosition:secondEnd];

        // 1st line
        [self drawTag:context Rect:[textView firstRectForRange:textRange]
                 name:[self textInRange:[textView textRangeFromPosition:textRange.start toPosition:secondBegin]]];

        // 2nd Line
        [self drawTag:context Rect:[textView firstRectForRange:secondTextRange]
                 name:[self textInRange:secondTextRange]];
    }
    else{
        // Draw rect first line
        [self drawTag:context Rect:[textView firstRectForRange:textRange] name:[self textInRange:textRange]];
    }
}

#pragma mark - Draw Tag graphics

- (void) drawTag: (CGContextRef) context Rect:(CGRect) rect name:(NSString*)nameText
{
    if(self.nameTagImage)
        [self drawTagImageInRect:rect name:nameText];
    else
        [self drawRectangle:context Rect:rect];
}

- (void) drawRectangle: (CGContextRef) context Rect:(CGRect) rect
{
    rect.size.width+=1;
    rect.size.height-=2;
    rect.origin.y+=1;

    if (_nameTagColor == nil)
        self.nameTagColor = [UIColor colorWithRed:0.98 green:1.00 blue:0.71 alpha:0.5];
    if (_nameTagLineColor == nil)
        self.nameTagLineColor = [UIColor colorWithRed:1.00 green:0.81 blue:0.35 alpha:0.6];

    CGContextSetFillColorWithColor(context, _nameTagColor.CGColor);
    CGContextSetStrokeColorWithColor(context, _nameTagLineColor.CGColor);

    // Draw line
    CGContextAddRect(context, rect);
    CGContextStrokePath(context);

    // Fill
    CGContextFillRect(context, rect);
    CGContextStrokeRectWithWidth(context, rect, 0.5);
}

- (void) drawTagImageInRect:(CGRect) rect name:(NSString*)nameText
{
    self.nameTagColor = self.nameTagColor;

    UIButton *tagButton = [UIButton buttonWithType:UIButtonTypeCustom];
    tagButton.frame = CGRectMake(rect.origin.x,
                                 rect.origin.y+1,
                                 rect.size.width,
                                 rect.size.height);

    [tagButton setBackgroundImage:self.nameTagImage forState:UIControlStateNormal];
    [tagButton setTitle:nameText forState:UIControlStateNormal];
    [tagButton setTitleColor:self.nameTagColor forState:UIControlStateNormal];
    tagButton.titleLabel.font = [UIFont systemFontOfSize:self.font.pointSize-4];

    if (!self.tagViews)
        self.tagViews = [[NSMutableArray alloc] init];

    [self.tagViews addObject:tagButton];
    [self addSubview:tagButton];
}

-(void) recreateAttributedStringByTags
{
    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] init];

    NSMutableAttributedString *space = [[NSMutableAttributedString alloc]
                                        initWithString: @" "
                                        attributes:[self defaultAttributedString]];

    for (SSuggestTag* tag in self.tagList) {
        NSMutableDictionary *attr = [[NSMutableDictionary alloc] initWithDictionary:[self defaultAttributedString]];
        [attr setObject: tag.tagId forKey:dataKeySuggest];
        NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc]
                                                 initWithString:[NSString stringWithFormat:@"%@", tag.tagDesc]
                                                 attributes:attr];
        [nameString appendAttributedString: space];

        [attrString appendAttributedString: nameString];
    }
    self.attributedText = attrString;
}

#pragma mark - adding Tag

- (void)addTag:(SSuggestTag *)newtag
{
    // Check aleady imported
    for (SSuggestTag *tag in self.tagList) {

        if ([tag.tagId isEqualToString:newtag.tagId])
        {

            return;
        }
    }

    // Add
    if (!self.tagList) self.tagList = [[NSMutableArray alloc] init];
    [self.tagList addObject:newtag];

    [self recreateAttributedStringByTags];

    //self.searchText = nil;

    /*
     // Insert Plain user name text
     NSMutableDictionary *attr = [[NSMutableDictionary alloc] initWithDictionary:[self defaultAttributedString]];
     [attr setObject:newtag.tagId forKey:dataKeySuggest];
     NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc]
     initWithString:[NSString stringWithFormat:@"%@", newtag.tagDesc]
     attributes:attr];

     NSMutableAttributedString *spaceStringPefix = nil;
     NSString *tempCommentWriting = self.text;

     //    NSLog(@"nameString:%@",nameString);

     NSInteger cursor = self.selectedRange.location;
     // display name

     // Add Last
     //    NSLog(@"self.attributedText.string.length:%d",self.attributedText.string.length);
     if (cursor >= self.attributedText.string.length-1)
     {
     // Add Space
     if (tempCommentWriting.length > 0){

     NSString *prevString = [tempCommentWriting substringFromIndex:tempCommentWriting.length-1];

     if (![prevString isEqualToString:@"\n"])
     {
     spaceStringPefix = [[NSMutableAttributedString alloc] initWithString:@" " attributes:[self defaultAttributedString]];
     }
     }

     NSMutableAttributedString *conts = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
     if (spaceStringPefix)
     [conts appendAttributedString:spaceStringPefix];
     [conts appendAttributedString:nameString];
     NSMutableAttributedString *afterBlank = [[NSMutableAttributedString alloc] initWithString:@" "
     attributes:[self defaultAttributedString]];
     [conts appendAttributedString:afterBlank];

     //        NSLog(@"conts:%@",conts);

     self.attributedText = conts;
     //        NSLog(@"\n\nself.attributedText:%@",self.attributedText);

     }
     // Insert in text
     else
     {
     self.attributedText = [self attributedStringInsertString:nameString at:cursor];
     }
     */

    [self setNeedsDisplay];

    // Pass Delegate
    if (self.delegate && [self.delegate respondsToSelector:@selector(textViewDidChange:)])
        [self.delegate textViewDidChange:self];

    if (self.suggestDelegate != nil)
    {
        [self.suggestDelegate suggestText:self tagSelected:newtag];
    }
}

-(void)addPossibleTagsObject:(SSuggestTag *)possibleTag
{
    NSArray* a = self.possibleTags;
    NSMutableArray* larray = (NSMutableArray*) a;
    NSAssert([larray isKindOfClass:[NSMutableArray class]], @"invalid type");

    NSPredicate* pred = [NSPredicate predicateWithFormat:@"tagId == %@", possibleTag.tagId];

    for (id object in larray) {
        if ([pred evaluateWithObject:object]) {
            return; //Do nothing if the id was found
        }
    }

    [larray addObject: possibleTag];

}

- (NSRange) findTagPosition:(SSuggestTag*)tag
{

    __block NSRange stringRange = NSMakeRange(0, 0);
    [self.attributedText enumerateAttribute:dataKeySuggest inRange:NSMakeRange(0, self.attributedText.length-1)
                                    options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {

                                        if ([value isEqualToString:tag.tagId])
                                        {
                                            stringRange = range;
                                            //                                            stringRange = CFRangeMake(range.location, range.location + range.length);
                                        }

                                    }];

    return stringRange;

}

- (SSuggestTag *) tagForId:(NSString*)tagId
{
    for (SSuggestTag *tag in self.tagList) {

        if ([tag.tagId isEqualToString:tagId])
            return tag;
    }

    return nil;
}

-(NSString*) getSearch
{

    NSMutableString* search = [[NSMutableString alloc] init];
    NSAttributedString* str = self.attributedText;
    [str enumerateAttributesInRange: NSMakeRange(0, str.length) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {

        if ([attrs objectForKey:dataKeySuggest] == nil)
        {
            NSString* substring = [str.string substringWithRange: range];
            ;
            if ([[search stringByTrimmingCharactersInSet:
                  [NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""] &&
                [[substring stringByTrimmingCharactersInSet:
                  [NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]
                )
            {
                //
            }
            else
            {
                [search appendString: substring];
            }
        }

    }];
    return [search stringByTrimmingCharactersInSet:
            [NSCharacterSet whitespaceCharacterSet]] ;
}

#pragma mark - UITextviewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    [self setNeedsDisplay];

    NSLogD(@"textViewDidChange... attributtedString: %@", self.attributedText.string);
    // length = 0, but attributed have id
    if (self.attributedText.string.length == 0)
    {
        [self clearAllAttributedStrings];
    }

    ///TODO: determine when it should appear

    self.partialSeach = [self getSearch];
    [self matchStrings: self.partialSeach];
    [self showPopOverList];

    return;

}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self recreateAttributedStringByTags];
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if (textView != self)
        return;

    if (self.keepSuggestPopoverOpen)
    {
        [self matchStrings: @""];
        [self showPopOverList];
    }
}

- (BOOL) shouldChangeTextInRange:(NSRange)editingRange replacementText:(NSString *)text
{

    __block BOOL result = YES;

    //NSString* textContent = [self.searchText stringByReplacingCharactersInRange:editingRange withString:text];

    if (!self.enableMultipleTags && self.tagList.count > 0)
    {
        //Cannot create tag anymore. limit reached
        if (editingRange.length == 1 && [text isEqualToString:@""]) {
            //It is deleting. Deleting is ok
        }
        else
        {
            return NO;
        }
    }

    NSLogD(@"shdChgTxtInRng '%@' text:%@ , loc:%d , len:%d", self.text , text , editingRange.location , editingRange.length);

    // ALl clear
    if (editingRange.location == 0 && editingRange.length == self.attributedText.string.length)
    {

        [self clearAll];

        return YES;
    }

    // Checking to insert within tag
    if (text.length > 0)
    {
        NSRange rangeOfCheckingEditingInTag = editingRange;
        if (rangeOfCheckingEditingInTag.location + rangeOfCheckingEditingInTag.length <= self.attributedText.length)
        {
            rangeOfCheckingEditingInTag.length = 1;
            rangeOfCheckingEditingInTag.location-=1;

            //            NSLog(@"<<<<< ----------- 1");

            NSInteger totalLength = rangeOfCheckingEditingInTag.location + rangeOfCheckingEditingInTag.length;
            if (totalLength > self.attributedText.length)
            {
                rangeOfCheckingEditingInTag = NSMakeRange(0, 0);
                //                NSLog(@"<<<<< ----------- 2");
            }
            else if (totalLength < 1)
            {
                rangeOfCheckingEditingInTag = NSMakeRange(0, 0);
                //                NSLog(@"<<<<< -------------3");
            }
        }

        [self.attributedText enumerateAttributesInRange:rangeOfCheckingEditingInTag options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {

            if ([attrs objectForKey:dataKeySuggest] && [self tagForId:[attrs objectForKey:dataKeySuggest]])
            {
                NSLog(@"------- Editing In Tag");
                result = NO;
            }

        }];

        return result;
    }
    // Deleting
    else
    {

        editingRange.location-=1;
        if (editingRange.location == -1)
            editingRange.location = 0;

        if (editingRange.length == 0)
        {
            //            NSLog(@"location >>>> 0");

            if (self.attributedText.length == 0)
            {
                [self clearAllAttributedStrings];
            }

            return YES;

        }

        __block BOOL tagRemoved = NO;

        [self.attributedText enumerateAttributesInRange:editingRange options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {

            if ([attrs objectForKey:dataKeySuggest] && [self tagForId:[attrs objectForKey:dataKeySuggest]])
            {

                NSRange tagRange = [self findTagPosition:[self tagForId:[attrs objectForKey:dataKeySuggest]]];

                //                NSLog(@"Deleted tag tag >>>>> id(%@):range(%d,%d)",[attrs objectForKey:dataKeySuggest], tagRange.location, tagRange.length);

                self.attributedText = [self attributedStringWithCutOutOfRange:tagRange];
                self.selectedRange = NSMakeRange(tagRange.location, 0);

                SSuggestTag* tagToBeRemoved = [self tagForId:[attrs objectForKey:dataKeySuggest]];

                [self.tagList removeObject: tagToBeRemoved];
                tagRemoved = YES;
                [self setNeedsDisplay];

                if (self.suggestDelegate != nil){
                    [self.suggestDelegate suggestText: self tagDeleted: tagToBeRemoved];
                                    }
            }
        }];

        if (tagRemoved){
            [self recreateAttributedStringByTags];
            return NO;
        }
        else {
            return YES;
        }
    }

}

#pragma mark - UIPopoverControllerDelegate

-(void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    //[self recreateAttributedStringByTags];
    [self endEditing: NO];
}

#pragma mark - AttributedStrings
- (NSAttributedString *) attributedStringWithCutOutOfRange:(NSRange)cuttingRange
{
    /*
     Cut out string of range on full string
     to get head + tail without middle
     */

    // Cutting Heads
    NSAttributedString *head = nil;
    if (cuttingRange.location > 0 && cuttingRange.length > 0)
        head = [self.attributedText attributedSubstringFromRange:NSMakeRange(0, cuttingRange.location-1)];
    else
        head = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[self defaultAttributedString]];

    // Cutting Tail

    NSAttributedString *tail = nil;
    if (cuttingRange.location + cuttingRange.length <= self.attributedText.string.length)
        tail = [self.attributedText attributedSubstringFromRange:NSMakeRange(cuttingRange.location + cuttingRange.length,
                                                                             self.attributedText.length - 1 - cuttingRange.location - cuttingRange.length)];

    NSMutableAttributedString *conts = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[self defaultAttributedString]];
    if (head)
        [conts appendAttributedString:head];
    if (tail)
        [conts appendAttributedString:tail];

    return conts;
}

- (NSAttributedString *) attributedStringInsertString:(NSAttributedString*)insertingStr at:(NSInteger)position
{
    /*
     Insert str within text at position
     with blank
     -> head + blank + insertingStr + blank + tail
     */

    // Cutting Heads
    NSAttributedString *head = nil;
    if (position > 0 && self.attributedText.string.length > 0)
        head = [self.attributedText attributedSubstringFromRange:NSMakeRange(0, position)];
    else if (position > 0)
        head = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[self defaultAttributedString]];

    // Cutting Tail
    NSAttributedString *tail = nil;
    if (position + 1 < self.attributedText.string.length)
        tail = [self.attributedText attributedSubstringFromRange:NSMakeRange(position,
                                                                             self.attributedText.length - position)];
    else{
        tail = [[NSMutableAttributedString alloc] initWithString:@" " attributes:[self defaultAttributedString]];
    }

    NSMutableAttributedString *conts = [[NSMutableAttributedString alloc] initWithString:@"" attributes:[self defaultAttributedString]];

    if (head)
    {
        [conts appendAttributedString:head];
        [conts appendAttributedString:[[NSAttributedString alloc] initWithString:@" " attributes:[self defaultAttributedString]]];
    }

    [conts appendAttributedString:insertingStr];

    if (tail)
    {
        [conts appendAttributedString:[[NSAttributedString alloc] initWithString:@" " attributes:[self defaultAttributedString]]];
        [conts appendAttributedString:tail];
    }

    return conts;
}

- (NSDictionary*) defaultAttributedString
{
    return @{NSFontAttributeName : self.font};
}

#pragma mark -ETC

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    /*
     Couldn't Cut, Copy, Past
     */
    return NO;
}

- (void) clearAllAttributedStrings
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedString removeAttribute: dataKeySuggest range: NSMakeRange(0, self.text.length)];
    [self.tagList removeAllObjects];
    [self setNeedsDisplay];
    //    NSLog(@"cleared attributes!");
}

- (void)clearAll
{

    [self clearAllAttributedStrings];
    self.attributedText = [[NSAttributedString alloc]initWithString:@"" attributes:[self defaultAttributedString]];
    [self setNeedsDisplay];

    if (self.suggestDelegate != nil)
    {
        [self.suggestDelegate suggestTextClearAllTags: self];
    }
}
@end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>ajah-servlet</artifactId>
	<name>Ajah Servlet Library</name>
	<description>The Ajah Servlet Library serves to provide a place for utilities that are specific to a servlet environment, but not specific to any particular product (Struts, Spring MVC, etc).</description>

	<parent>
		<groupId>com.ajah</groupId>
		<artifactId>ajah-base</artifactId>
		<version>2.0.0-SNAPSHOT</version>
		<relativePath>../ajah-base/pom.xml</relativePath>
	</parent>

	<dependencies>

		<dependency>
			<groupId>com.ajah</groupId>
			<artifactId>ajah-util</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.ajah</groupId>
			<artifactId>ajah-html</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>com.ajah</groupId>
			<artifactId>ajah-http</artifactId>
			<version>${project.version}</version>
		</dependency>

	</dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
<ng-form name="historyForm">

History

                <ccdb-form-textarea label="Past medical history"
                                    value="patient.admission.pastMedicalHistory"></ccdb-form-textarea>
                <ccdb-form-textarea label="Past surgical history"
                                    value="patient.admission.pastSurgicalHistory"></ccdb-form-textarea>

                <ccdb-form-textarea label="Chronic medications" value="patient.admission.medications"></ccdb-form-textarea>

</ng-form>


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

<project name="introspector" default="jar">

  <property file="build.properties"/>

  <path id="classpath">
    <fileset dir="${libraries}">
      <include name="*.jar" />
    </fileset>
  </path>

  <path id="classpath.test">
    <pathelement location="${target.classes}"/>
    <pathelement location="${target.classes.test}"/>
    <path refid="classpath"/>
  </path>

  <target name="clean">
    <delete dir="${target}"/>
  </target>

  <target name="init" depends="clean">
    <mkdir dir="${target.classes}"/>
    <mkdir dir="${target.classes.test}"/>
    <mkdir dir="${target.test.temp}"/>
  </target>

  <target name="compile" depends="init">
    <javac srcdir="${source}" destdir="${target.classes}" classpathref="classpath"/>
    <javac srcdir="${source.test}" destdir="${target.classes.test}" classpathref="classpath.test"/>
  </target>

  <target name="test" depends="compile">
    <junit printsummary="yes" haltonfailure="no" tempdir="${target.test.temp}">
      <formatter type="xml"/>
      <classpath refid="classpath.test"/>
      <batchtest fork="yes" todir="${target.test.temp}">
        <fileset dir="${target.classes.test}">
          <include name="**/*Spec.class"/>
        </fileset>
      </batchtest>
    </junit>
    <junitreport todir="${target.test.temp}">
      <fileset dir="${target.test.temp}">
        <include name="TEST-*.xml"/>
      </fileset>
      <report format="frames" todir="${target.test.report}"/>
    </junitreport>
    <delete dir="${target.test.temp}"/>
  </target>

  <target name="jar" depends="test">
    <jar destfile="${target}/${project}-${version}.jar" basedir="${target.classes}"/>
  </target>

</project>


text:
package Google::Ads::GoogleAds::V10::Common::AppAdInfo;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    descriptions      => $args->{descriptions},
    headlines         => $args->{headlines},
    html5MediaBundles => $args->{html5MediaBundles},
    images            => $args->{images},
    mandatoryAdText   => $args->{mandatoryAdText},
    youtubeVideos     => $args->{youtubeVideos}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
require 'unit_spec_helper'

describe Shoulda::Matchers::ActiveModel::ValidateAbsenceOfMatcher do
  if active_model_4_0?
    def self.available_column_types
      [
        :string,
        :text,
        :integer,
        :float,
        :decimal,
        :datetime,
        :timestamp,
        :time,
        :date,
        :binary
      ]
    end

    context 'a model with an absence validation' do
      it 'accepts' do
        expect(validating_absence_of(:attr)).to validate_absence_of(:attr)
      end

      it 'does not override the default message with a present' do
        expect(validating_absence_of(:attr)).to validate_absence_of(:attr).with_message(nil)
      end

      available_column_types.each do |type|
        context "when column is of type #{type}" do
          it "accepts" do
            expect(validating_absence_of(:attr, {}, type: type)).
              to validate_absence_of(:attr)
          end
        end
      end
    end

    context 'a model without an absence validation' do
      it 'rejects' do
        model = define_model(:example, attr: :string).new
        expect(model).not_to validate_absence_of(:attr)
      end
    end

    context 'an ActiveModel class with an absence validation' do
      it 'accepts' do
        expect(active_model_validating_absence_of(:attr)).to validate_absence_of(:attr)
      end

      it 'does not override the default message with a blank' do
        expect(active_model_validating_absence_of(:attr)).to validate_absence_of(:attr).with_message(nil)
      end
    end

    context 'an ActiveModel class without an absence validation' do
      it 'rejects' do
        expect(active_model_with(:attr)).not_to validate_absence_of(:attr)
      end

      it 'provides the correct failure message' do
        message = %{Expected errors to include "must be blank" when attr is set to "an arbitrary value",\ngot no errors}

        expect { expect(active_model_with(:attr)).to validate_absence_of(:attr) }.to fail_with_message(message)
      end
    end

    context 'a has_many association with an absence validation' do
      it 'requires the attribute to not be set' do
        expect(having_many(:children, absence: true)).to validate_absence_of(:children)
      end
    end

    context 'a has_many association without an absence validation' do
      it 'does not require the attribute to not be set' do
        expect(having_many(:children, absence: false)).
          not_to validate_absence_of(:children)
      end
    end

    context 'an absent has_and_belongs_to_many association' do
      it 'accepts' do
        model = having_and_belonging_to_many(:children, absence: true)
        expect(model).to validate_absence_of(:children)
      end
    end

    context 'a non-absent has_and_belongs_to_many association' do
      it 'rejects' do
        model = having_and_belonging_to_many(:children, absence: false)
        expect(model).not_to validate_absence_of(:children)
      end
    end

    context "an i18n translation containing %{attribute} and %{model}" do
      after { I18n.backend.reload! }

      it "does not raise an exception" do
        stub_translation("activerecord.errors.messages.present",
                         "%{attribute} must be blank in a %{model}")

        expect {
          expect(validating_absence_of(:attr)).to validate_absence_of(:attr)
        }.to_not raise_exception
      end
    end

    context "an attribute with a context-dependent validation" do
      context "without the validation context" do
        it "does not match" do
          expect(validating_absence_of(:attr, on: :customisable)).not_to validate_absence_of(:attr)
        end
      end

      context "with the validation context" do
        it "matches" do
          expect(validating_absence_of(:attr, on: :customisable)).to validate_absence_of(:attr).on(:customisable)
        end
      end
    end

    def validating_absence_of(attr, validation_options = {}, given_column_options = {})
      default_column_options = { type: :string, options: {} }
      column_options = default_column_options.merge(given_column_options)

      define_model :example, attr => column_options do
        validates_absence_of attr, validation_options
      end.new
    end

    def active_model_with(attr, &block)
      define_active_model_class('Example', accessors: [attr], &block).new
    end

    def active_model_validating_absence_of(attr)
      active_model_with(attr) do
        validates_absence_of attr
      end
    end

    def having_many(plural_name, options = {})
      define_model plural_name.to_s.singularize
      define_model :parent do
        has_many plural_name
        if options[:absence]
          validates_absence_of plural_name
        end
      end.new
    end

    def having_and_belonging_to_many(plural_name, options = {})
      create_table 'children_parents', id: false do |t|
        t.integer "#{plural_name.to_s.singularize}_id"
        t.integer :parent_id
      end

      define_model plural_name.to_s.singularize
      define_model :parent do
        has_and_belongs_to_many plural_name
        if options[:absence]
          validates_absence_of plural_name
        end
      end.new
    end
  end
end


text:
using System;
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EPiServer CMS AlloyTech Sample Templates")]
[assembly: AssemblyDescription("Sample Templates for EPiServer CMS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EPiServer AB")]
[assembly: AssemblyProduct("EPiServer CMS")]
[assembly: AssemblyCopyright("© 2007-2011 by EPiServer AB. All rights reserved")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.1.0.0")]


text:
'use strict';

//Setting up route
angular.module('mycrudmodules').config(['$stateProvider',
	function($stateProvider) {
		// Mycrudmodules state routing
		$stateProvider.
		state('listMycrudmodules', {
			url: '/mycrudmodules',
			templateUrl: 'modules/mycrudmodules/views/list-mycrudmodules.client.view.html'
		}).
		state('createMycrudmodule', {
			url: '/mycrudmodules/create',
			templateUrl: 'modules/mycrudmodules/views/create-mycrudmodule.client.view.html'
		}).
		state('viewMycrudmodule', {
			url: '/mycrudmodules/:mycrudmoduleId',
			templateUrl: 'modules/mycrudmodules/views/view-mycrudmodule.client.view.html'
		}).
		state('editMycrudmodule', {
			url: '/mycrudmodules/:mycrudmoduleId/edit',
			templateUrl: 'modules/mycrudmodules/views/edit-mycrudmodule.client.view.html'
		});
	}
]);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `get_param` fn in crate `rustc`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, get_param">

    <title>rustc::llvm::get_param - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc::<wbr>llvm

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function rustc::<wbr>llvm::<wbr>get_param<wbr>Unstable
            [-] [+]
        [src]

pub fn get_param(llfn: *mut Value_opaque, index: u32) -> *mut Value_opaque

Safe wrapper around LLVMGetParam, because segfaults are no fun.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
import { Pipe, PipeTransform } from '@angular/core';
import { default as Web3 } from 'web3';

@Pipe({
  name: 'wei'
})
export class WeiPipe implements PipeTransform {

  transform(value: any, unit: string): any {
    if (value) {
      return Web3.utils.fromWei(value, unit);
    } else {
      return 0;
    }
  }
}


text:
#ifndef GDCMTERMINAL_H
#define GDCMTERMINAL_H

#include "gdcmTypes.h"

namespace gdcm
{
/**
 * \brief Class for Terminal
 * Allow one to print in color in a shell
 * - support VT100 compatible shell
 * - win32 console
 */
//-----------------------------------------------------------------------------

namespace terminal
{
  typedef enum
    {
    CONSOLE = 0,
    VT100
    } Mode;
  typedef enum
    {
    black = 0,
    red,
    green,
    yellow, // brown ??
    blue,
    magenta,
    cyan,
    white
    } Color;
  typedef enum
    {
    reset     = 0,
    bright    = 1, // bold
    dim       = 2,
    underline = 3,
    blink     = 5,
    reverse   = 7,
    hidden    = 8
    } Attribute;
  GDCM_EXPORT std::string setattribute( Attribute att );
  GDCM_EXPORT std::string setfgcolor( Color c );
  GDCM_EXPORT std::string setbgcolor( Color c );
  GDCM_EXPORT void setmode( Mode m);
}

} // end namespace gdcm
//-----------------------------------------------------------------------------
#endif //GDCMTERMINAL_H


text:
package org.nd4j.codegen.impl.java;

import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.nd4j.codegen.api.*;
import org.nd4j.codegen.api.doc.DocSection;
import org.nd4j.codegen.api.doc.DocTokens;
import org.nd4j.codegen.util.GenUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static org.nd4j.codegen.impl.java.Nd4jNamespaceGenerator.exactlyOne;

public class DocsGenerator {

    // Markdown marker for start-end of code section
    private static final String MD_CODE = "```";
    // Javadoc constants which should be dropped or replaced for markdown generation
    private static final String JD_CODE = "{@code ";
    private static final String JD_CODE_END = "}";
    private static final String JD_INPUT_TYPE = "%INPUT_TYPE%";

    public static class JavaDocToMDAdapter {
        private String current;

        public JavaDocToMDAdapter(String original) {
            this.current = original;
        }

        public JavaDocToMDAdapter filter(String pattern, String replaceWith) {
            String result =  StringUtils.replace(current, pattern, replaceWith);
            this.current = result;
            return this;
        }

        @Override
        public String toString() {
            return current;
        }
    }

    private static String generateMethodText(Op op, Signature s, boolean isSameDiff, boolean isLoss, boolean withName) {
        StringBuilder sb = new StringBuilder();
        MethodSpec.Builder c = MethodSpec.methodBuilder(GenUtil.ensureFirstIsNotCap(op.getOpName()));
        List<Parameter> params = s.getParameters();
        List<Output> outs = op.getOutputs();
        String retType = "void";

        if (outs.size() == 1) {
            retType = isSameDiff ? "SDVariable" : "INDArray";
        }
        else if (outs.size() >= 1) {
            retType = isSameDiff ? "SDVariable[]" : "INDArray[]";
        }
        sb.append(retType).append(" ").append(op.getOpName()).append("(");
        boolean first = true;
        for (Parameter param : params) {
            if (param instanceof Arg) {
                Arg arg = (Arg) param;
                if (!first)
                    sb.append(", ");
                else if (withName)
                    sb.append("String name, ");
                String className;
                if(arg.getType() == DataType.ENUM) {
                    className = GenUtil.ensureFirstIsCap(arg.name());
                } else {
                    TypeName tu = Nd4jNamespaceGenerator.getArgType(arg);
                    className = tu.toString();
                }
                if(className.contains(".")){
                    className = className.substring(className.lastIndexOf('.')+1);
                }
                sb.append(className).append(" ").append(arg.name());
                first = false;
            }
            else if (param instanceof Input) {
                Input arg = (Input) param;
                if (!first)
                    sb.append(", ");
                else if (withName)
                    sb.append("String name, ");
                sb.append(isSameDiff ? "SDVariable " : "INDArray ").append(arg.name());
                first = false;
            } else if(param instanceof Config){
                if(!first)
                    sb.append(", ");
                Config conf = (Config)param;
                String name = conf.getName();
                sb.append(name).append(" ").append(GenUtil.ensureFirstIsNotCap(name));
            }
        }
        sb.append(")");
        return sb.toString();
    }

    private static StringBuilder buildDocSectionText(List<DocSection> docSections) {
        StringBuilder sb = new StringBuilder();
        for (DocSection ds : docSections) {
            //if(ds.applies(Language.JAVA, CodeComponent.OP_CREATOR)){
            String text = ds.getText();
            String[] lines = text.split("\n");
            for (int i = 0; i < lines.length; i++) {
                if (!lines[i].endsWith("<br>")) {
                    String filteredLine = new JavaDocToMDAdapter(lines[i])
                            .filter(JD_CODE, "`")
                            .filter(JD_CODE_END, "`")
                            .filter(JD_INPUT_TYPE, "INDArray").toString();

                    lines[i] = filteredLine + System.lineSeparator();
                }
            }
            text = String.join("\n", lines);
            sb.append(text).append(System.lineSeparator());
            //}
        }
        return sb;
    }

    public static void generateDocs(int namespaceNum, NamespaceOps namespace, String docsDirectory, String basePackage) throws IOException {
        File outputDirectory = new File(docsDirectory);
        StringBuilder sb = new StringBuilder();
        String headerName = namespace.getName();
        if(headerName.startsWith("SD"))
            headerName = headerName.substring(2);

        // File Header for Gitbook
        sb.append("---").append(System.lineSeparator());
        sb.append("title: ").append(headerName).append(System.lineSeparator());
        sb.append("short_title: ").append(headerName).append(System.lineSeparator());
        sb.append("description: ").append(System.lineSeparator());
        sb.append("category: Operations").append(System.lineSeparator());
        sb.append("weight: ").append(namespaceNum * 10).append(System.lineSeparator());
        sb.append("---").append(System.lineSeparator());

        List<Op> ops = namespace.getOps();

        ops.sort(Comparator.comparing(Op::getOpName));

        if (ops.size() > 0)
            sb.append("# Operation classes").append(System.lineSeparator());
        for (Op op : ops) {
            sb.append("## ").append(op.getOpName()).append(System.lineSeparator());
            List<DocSection> doc = op.getDoc();
            if(!doc.isEmpty()) {
                boolean first = true;
                StringBuilder ndSignatures = new StringBuilder();
                StringBuilder sdSignatures = new StringBuilder();
                StringBuilder sdNameSignatures = new StringBuilder();
                for(Signature s : op.getSignatures()) {
                    if (first) {
                        Language lang = doc.get(0).getLanguage();
                        sb.append(MD_CODE).append(lang.equals(Language.ANY) ? Language.JAVA : lang).append(System.lineSeparator());
                        first = false;
                    }
                    String ndCode = generateMethodText(op, s, false, false, false);
                    ndSignatures.append(ndCode).append(System.lineSeparator());
                    String sdCode = generateMethodText(op, s, true, false, false);
                    sdSignatures.append(sdCode).append(System.lineSeparator());
                    String withNameCode = generateMethodText(op, s, true, false, true);
                    sdNameSignatures.append(withNameCode).append(System.lineSeparator());
                }
                sb.append(ndSignatures.toString());
                sb.append(System.lineSeparator()); // New line between INDArray and SDVariable signatures

                sb.append(sdSignatures.toString());
                sb.append(sdNameSignatures.toString());

                sb.append(MD_CODE).append(System.lineSeparator());
                StringBuilder tsb = buildDocSectionText(doc);
                sb.append(tsb.toString());
                List<Signature> l = op.getSignatures();
                Set<Parameter> alreadySeen = new HashSet<>();
                for(Signature s : l) {
                    List<Parameter> params = s.getParameters();
                    for (Parameter p : params) {
                        if(alreadySeen.contains(p)) continue;
                        alreadySeen.add(p);
                        if(p instanceof Input){
                            Input i = (Input)p;
                            sb.append("* **").append(i.getName()).append("** ").append(" (").append(i.getType()).append(") - ").append(i.getDescription() == null ? "" : DocTokens.processDocText(i.getDescription(),
                                    op, DocTokens.GenerationType.ND4J)).append(System.lineSeparator());
                        }
                        else if (p instanceof Config) {
                            Config c = (Config)p;
                            sb.append("* **").append(c.getName()).append("** - see ").append("[").append(c.getName()).append("]").append("(#").append(toAnchor(c.getName())).append(")").append(System.lineSeparator());
                        }
                        else if(p instanceof Arg) {
                            Arg arg = (Arg) p;
                            final Count count = arg.getCount();
                            if (count == null || count.equals(exactlyOne)) {
                                sb.append("* **").append(arg.getName()).append("** - ").append(arg.getDescription() == null ? "" : DocTokens.processDocText(arg.getDescription(),
                                        op, DocTokens.GenerationType.ND4J));    //.append(System.lineSeparator());
                            } else {
                                sb.append("* **").append(arg.getName()).append("** - ").append(arg.getDescription() == null ? "" : DocTokens.processDocText(arg.getDescription(),
                                        op, DocTokens.GenerationType.ND4J)).append(" (Size: ").append(count.toString()).append(")");    //.append(System.lineSeparator());
                            }

                            Object defaultValue = arg.defaultValue();
                            if(defaultValue != null){
                                sb.append(" - default = ").append(formatDefaultValue(defaultValue));
                            }

                            sb.append(System.lineSeparator());
                        }
                    }
                }
                sb.append(System.lineSeparator());
            }
        }

        if (namespace.getConfigs().size() > 0)
            sb.append("# Configuration Classes").append(System.lineSeparator());
        for (Config config : namespace.getConfigs()) {
            sb.append("## ").append(config.getName()).append(System.lineSeparator());
            for (Input i : config.getInputs()) {
                sb.append("* **").append(i.getName()).append("**- ").append(i.getDescription()).append(" (").append(i.getType()).append(" type)");
                if (i.hasDefaultValue() && (i.defaultValue() != null))
                    sb.append(" Default value:").append(formatDefaultValue(i.defaultValue())).append(System.lineSeparator());
                else
                    sb.append(System.lineSeparator());
            }
            for (Arg arg : config.getArgs()) {
                sb.append("* **").append(arg.getName()).append("** ").append("(").append(arg.getType()).append(") - ").append(arg.getDescription());
                if (arg.hasDefaultValue() && (arg.defaultValue() != null))
                    sb.append(" - default = ").append(formatDefaultValue(arg.defaultValue())).append(System.lineSeparator());
                else
                    sb.append(System.lineSeparator());
            }
            StringBuilder tsb = buildDocSectionText(config.getDoc());
            sb.append(tsb.toString());
            sb.append(System.lineSeparator());
            for (Op op : ops) {
                if (op.getConfigs().contains(config)) {
                    sb.append("Used in these ops: " + System.lineSeparator());
                    break;
                }
            }
            ops.stream().filter(op -> op.getConfigs().contains(config)).forEach(op ->
                       sb.append("[").append(op.getOpName()).append("]").append("(#").append(toAnchor(op.getOpName())).append(")").
                       append(System.lineSeparator()));

        }
        File outFile = new File(outputDirectory + "/operation-namespaces", "/" + namespace.getName().toLowerCase() + ".md");
        FileUtils.writeStringToFile(outFile, sb.toString(), StandardCharsets.UTF_8);
    }

    private static String formatDefaultValue(Object v){
        if(v == null){ return "null"; }
        else if(v instanceof int[]){ return Arrays.toString((int[]) v); }
        else if(v instanceof long[]){ return Arrays.toString((long[]) v); }
        else if(v instanceof float[]){ return Arrays.toString((float[]) v); }
        else if(v instanceof double[]){ return Arrays.toString((double[]) v); }
        else if(v instanceof boolean[]){ return Arrays.toString((boolean[]) v); }
        else if(v instanceof Input){ return ((Input)v).getName(); }
        else if(v instanceof org.nd4j.linalg.api.buffer.DataType){ return "DataType." + v; }
        else if(v instanceof LossReduce || v instanceof org.nd4j.autodiff.loss.LossReduce){ return "LossReduce." + v; }
        else return v.toString();
    }

    private static String toAnchor(String name){
        int[] codepoints = name.toLowerCase().codePoints().toArray();
        int type = Character.getType(codepoints[0]);
        StringBuilder anchor = new StringBuilder(new String(Character.toChars(codepoints[0])));
        for (int i = 1; i < codepoints.length; i++) {
            int curType = Character.getType(codepoints[i]);
            if(curType != type){
                anchor.append("-");
            }
            type = curType;
            anchor.append(new String(Character.toChars(codepoints[i])));
        }
        return anchor.toString();
    }
}


text:
package ping

import (
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/lib/snet"
	"github.com/scionproto/scion/go/lib/snet/path"
)

// Size computes the full SCION packet size for an address pair with a given
// payload size.
func Size(local, remote *snet.UDPAddr, pldSize int) (int, error) {
	pkt, err := pack(local, remote, snet.SCMPEchoRequest{Payload: make([]byte, pldSize)})
	if err != nil {
		return 0, err
	}
	if err := pkt.Serialize(); err != nil {
		return 0, err
	}
	return len(pkt.Bytes), nil
}

func pack(local, remote *snet.UDPAddr, req snet.SCMPEchoRequest) (*snet.Packet, error) {
	_, isEmpty := remote.Path.(path.Empty)
	if isEmpty && !local.IA.Equal(remote.IA) {
		return nil, serrors.New("no path for remote ISD-AS", "local", local.IA, "remote", remote.IA)
	}
	pkt := &snet.Packet{
		PacketInfo: snet.PacketInfo{
			Destination: snet.SCIONAddress{
				IA:   remote.IA,
				Host: addr.HostFromIP(remote.Host.IP),
			},
			Source: snet.SCIONAddress{
				IA:   local.IA,
				Host: addr.HostFromIP(local.Host.IP),
			},
			Path:    remote.Path,
			Payload: req,
		},
	}
	return pkt, nil
}


text:
from subprocess import Popen, PIPE

def is_class(file):
    return file.endswith(".class") and not file.startswith("META-INF")

def modified_paths(patch):
    p = Popen(["jar", "-tf", patch], stdout=PIPE)
    output, _ = p.communicate()
    return filter(is_class, [file.decode() for file in output.split(b"\n")])

def path_to_class(path):
    if "$" in path:
        return path.split("$")[0]
    else:
        return path.replace(".class", "")

def modified_classes(patch):
    classes = map(path_to_class, modified_paths(patch))
    return list(set(classes))


text:
// +build !ignore_autogenerated

// This file was autogenerated by deepcopy-gen. Do not edit it manually!

package metatypes

import (
	conversion "k8s.io/kubernetes/pkg/conversion"
)

func DeepCopy_metatypes_OwnerReference(in OwnerReference, out *OwnerReference, c *conversion.Cloner) error {
	out.APIVersion = in.APIVersion
	out.Kind = in.Kind
	out.UID = in.UID
	out.Name = in.Name
	if in.Controller != nil {
		value := *in.Controller
		out.Controller = &value
	}
	return nil
}


text:
Princely is a simple wrapper for the [Prince XML PDF generation library](http://www.princexml.com).
The plugin will also automatically register the PDF MimeType so that you can use
pdf as a format in Rails controller `respond_to` blocks.

## Example

```ruby
class Provider::EstimatesController < Provider::BaseController
  # You can render PDF templates simply by
  # using the :pdf option on render templates.
  def show
    respond_to do |format|
      format.html
      format.pdf do
        render :pdf => 'file_name',
               :template => 'controller/action',
               :handlers => %w[erb],
               :formats => %w[pdf],
               :stylesheets => %w[application prince],
               :layout => 'pdf',
               :locals => { :foo => 'bar' },
               :disposition => 'inline', # PDF will be sent inline, means you can load it inside an iFrame or Embed
               :relative_paths => true # Modify asset paths to make them relative. See [the AssetSupport module](/lib/princely/asset_support.rb)
      end
    end
  end

  # Alternatively, you can use make_and_send_pdf to render out a PDF for the
  # action without a respond_to block.
  def pdf
    make_and_send_pdf "file_name"
  end
end
```

## Render Defaults

The defaults for the render options are as follows:

    layout:          false
    template:        the template for the current controller/action
    locals:          none
    stylesheets:     none
    disposition:     attachment (created PDF file will be sent as download)
    relative_paths:  true
    server_flag:     true
    javascript_flag: false
    timeout:         none

## Contributors

* Maintainer: Jared Fraser ([modsognir](https://github.com/modsognir))
* Gemification and more: Nic Williams
* Based on code by: Seth B ([subimage](https://github.com/subimage))
* [Other Contributors](https://github.com/mbleigh/princely/contributors)

## Resources

* Copyright (c) 2007-2013 Michael Bleigh and Intridea, Inc., released under the MIT license.


text:
<?php
/**
 * PC Audit
 * (C) Gregory Oakley-Stevenson
 * @package pcaudit
 */

require_once('config.php');
          session_destroy();
          $url="index.php";
          header('HTTP/1.1 301 Moved Permanently');
          header('Location: ' . $url);
          die();


text:
namespace FluentValidation.Tests {
	using System.Globalization;
	using System.Linq;
	using System.Threading;
	using Xunit;

	public class CreditCardValidatorTests {
		TestValidator validator;

		public CreditCardValidatorTests() {
			CultureScope.SetDefaultCulture();

			validator = new TestValidator {
				v => v.RuleFor(x => x.CreditCard).CreditCard()
			};
		}

		[Fact] // copied these tests from the mvc3 unit tests.
		public void IsValidTests() {
			validator.Validate(new Person { CreditCard = null }).IsValid.ShouldBeTrue(); // Optional values are always valid
			validator.Validate(new Person { CreditCard = "0000000000000000" }).IsValid.ShouldBeTrue(); // Simplest valid value
			validator.Validate(new Person { CreditCard = "1234567890123452" }).IsValid.ShouldBeTrue(); // Good checksum
			validator.Validate(new Person { CreditCard = "1234-5678-9012-3452" }).IsValid.ShouldBeTrue(); // Good checksum, with dashes
			validator.Validate(new Person { CreditCard = "1234 5678 9012 3452" }).IsValid.ShouldBeTrue(); // Good checksum, with spaces
			validator.Validate(new Person { CreditCard = "0000000000000001" }).IsValid.ShouldBeFalse(); // Bad checksum
		}

		[Fact]
		public void When_validation_fails_the_default_error_should_be_set() {
			string creditcard = "foo";
			var result = validator.Validate(new Person { CreditCard = creditcard });
			result.Errors.Single().ErrorMessage.ShouldEqual("'Credit Card' is not a valid credit card number.");
		}

	}
}


text:
$currentWorkingDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
. $currentWorkingDir\env_asm.ps1

function updateVMImageNotShowInGUI(
   [String] $imageName,
   [String] $labelImgFamily,
   [String] $subscriptionName)
{
   Try
   {
       # Prepare subscription and storage account
       Select-AzureSubscription -Current -SubscriptionName $subscriptionName

       gLogMsg "Update-AzureVMImage -ImageName $imageName -Label $labelImgFamily -DontShowInGui"
       Update-AzureVMImage -ImageName $imageName -Label $labelImgFamily -DontShowInGui
   } Catch {
       gLogMsg "Upload Failed."
       gLogMsg $ERROR[0].Exception
   }
   return $False
}

$ret=gValidateParameters
if (!$ret) {
   gLogMsg "Invalid parameters, please specify correct parameters. See comments of env_config.ps1"
   return $ret
}

gLogin

updateVMImageNotShowInGUI $vmImageName $vmLabelImageFamily $subscriptionName


text:
module Spree
  class AffiliateLink < ActiveRecord::Base
    attr_accessible :destination_url, :name, :image_attributes, :sort

    has_one :image, :class_name => 'Spree::Image', :as => :viewable, :dependent => :destroy, :validate => true
    accepts_nested_attributes_for :image

    before_create :default_sort

    def default_sort
      self.sort = 0 if self.sort.nil?
    end
  end
end


text:
import sys, os
import random
from nlgen.cfg import read_cfg

nombre_archivo = "example_art_es.nlcfg"
archivo = open(nombre_archivo, "r").read()
config = read_cfg(archivo.strip())
permutaciones = config.permutation_values("SENTENCE")
frases = [" ".join( frase ) for frase in set(permutaciones) ]
frase = random.choice(frases)
print(frase)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Automation
{
    /// <summary>
    /// Service operation for automation usages.  (see
    /// http://aka.ms/azureautomationsdk/usageoperations for more information)
    /// </summary>
    internal partial class UsageOperations : IServiceOperations<AutomationManagementClient>, IUsageOperations
    {
        /// <summary>
        /// Initializes a new instance of the UsageOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal UsageOperations(AutomationManagementClient client)
        {
            this._client = client;
        }

        private AutomationManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.Azure.Management.Automation.AutomationManagementClient.
        /// </summary>
        public AutomationManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Retrieve the usage for the account id.  (see
        /// http://aka.ms/azureautomationsdk/usageoperations for more
        /// information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the get usage operation.
        /// </returns>
        public async Task<UsageListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/usages";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2017-05-15-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    UsageListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new UsageListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Usage usageInstance = new Usage();
                                    result.Usage.Add(usageInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        usageInstance.Id = idInstance;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        UsageCounterName nameInstance = new UsageCounterName();
                                        usageInstance.Name = nameInstance;

                                        JToken valueValue2 = nameValue["value"];
                                        if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
                                        {
                                            string valueInstance = ((string)valueValue2);
                                            nameInstance.Value = valueInstance;
                                        }

                                        JToken localizedValueValue = nameValue["localizedValue"];
                                        if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance = ((string)localizedValueValue);
                                            nameInstance.LocalizedValue = localizedValueInstance;
                                        }
                                    }

                                    JToken unitValue = valueValue["unit"];
                                    if (unitValue != null && unitValue.Type != JTokenType.Null)
                                    {
                                        string unitInstance = ((string)unitValue);
                                        usageInstance.Unit = unitInstance;
                                    }

                                    JToken currentValueValue = valueValue["currentValue"];
                                    if (currentValueValue != null && currentValueValue.Type != JTokenType.Null)
                                    {
                                        double currentValueInstance = ((double)currentValueValue);
                                        usageInstance.CurrentValue = currentValueInstance;
                                    }

                                    JToken limitValue = valueValue["limit"];
                                    if (limitValue != null && limitValue.Type != JTokenType.Null)
                                    {
                                        long limitInstance = ((long)limitValue);
                                        usageInstance.Limit = limitInstance;
                                    }

                                    JToken throttleStatusValue = valueValue["throttleStatus"];
                                    if (throttleStatusValue != null && throttleStatusValue.Type != JTokenType.Null)
                                    {
                                        string throttleStatusInstance = ((string)throttleStatusValue);
                                        usageInstance.ThrottleStatus = throttleStatusInstance;
                                    }
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
require 'test_helper'

class StaticPagesControllerTest < ActionController::TestCase

  test "should get home" do
    get :home
    assert_response :success
    assert_select "title", full_title
  end

  test "should get help" do
    get :help
    assert_response :success
    assert_select "title", full_title("Help")
  end

  test "should get about" do
    get :about
    assert_response :success
    assert_select "title", full_title("About")
  end

  test "should get contact" do
    get :contact
    assert_response :success
    assert_select "title", full_title("Contact")
  end

end


text:
module Fog
  module Rackspace
    class Databases
      class Real
        def delete_database(instance_id, name)
          request(
            :expects => 202,
            :method => 'DELETE',
            :path => "instances/#{instance_id}/databases/#{name}"
          )
        end
      end
    end
  end
end


text:
package com.github.mdr.mash.ns.collections.listClass

import com.github.mdr.mash.completions.CompletionSpec
import com.github.mdr.mash.functions.{ BoundParams, MashMethod, ParameterModel }
import com.github.mdr.mash.inference.{ Type, TypedArguments }
import com.github.mdr.mash.ns.collections.{ ListClass, SelectFunction }
import com.github.mdr.mash.runtime.MashValue

object SelectMethod extends MashMethod("select") {

  import SelectFunction.Params._

  override val params = ParameterModel(Add, Selectors)

  override def call(target: MashValue, boundParams: BoundParams): MashValue =
    SelectFunction.doSelect(target, boundParams)

  override def summaryOpt: Option[String] = SelectFunction.summaryOpt

  override def descriptionOpt: Option[String] = SelectFunction.descriptionOpt

  override def typeInferenceStrategy = ListClass.methodise(SelectFunction).typeInferenceStrategy

  override def getCompletionSpecs(argPos: Int, targetTypeOpt: Option[Type], arguments: TypedArguments): Seq[CompletionSpec] =
    ListClass.methodise(SelectFunction).getCompletionSpecs(argPos, targetTypeOpt, arguments)

}


text:
import setuptools
setuptools.setup(
    name = "hindkit",
    version = "1.0.0",
    url = "https://github.com/itfoundry/hindkit",
    author = "Liang Hai",
    author_email = "lianghai@gmail.com",
    license="MIT",
    package_dir = {"": "lib"},
    py_modules = [
        "getKerningPairsFromFEA",
        "WriteFeaturesKernFDK",
        "WriteFeaturesMarkFDK",
    ],
    packages = [
        "hindkit",
        "hindkit.objects",
    ],
    package_data = {
        "hindkit": [
            "data/*.txt",
            "data/premade/*/GlyphOrderAndAliasDB",
            "data/premade/*/features/*.fea",
        ],
    },
)


text:
import logging
import pytest
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
from tests.common.test_dimensions import create_exec_option_dimension
from tests.common.skip import SkipIfS3

class TestInsertQueriesWithPermutation(ImpalaTestSuite):
  """
  Tests for the column permutation feature of INSERT statements
  """
  @classmethod
  def get_workload(self):
    return 'functional-query'

  @classmethod
  def add_test_dimensions(cls):
    super(TestInsertQueriesWithPermutation, cls).add_test_dimensions()
    # Fix the exec_option vector to have a single value. This is needed should we decide
    # to run the insert tests in parallel (otherwise there will be two tests inserting
    # into the same table at the same time for the same file format).
    # TODO: When we do decide to run these tests in parallel we could create unique temp
    # tables for each test case to resolve the concurrency problems.
    # TODO: do we need to run with multiple file formats? This seems to be really
    # targeting FE behavior.
    cls.TestMatrix.add_dimension(create_exec_option_dimension(
        cluster_sizes=[0], disable_codegen_options=[False], batch_sizes=[0]))
    cls.TestMatrix.add_dimension(create_uncompressed_text_dimension(cls.get_workload()))

  @SkipIfS3.insert
  def test_insert_permutation(self, vector):
    map(self.cleanup_db, ["insert_permutation_test"])
    self.run_test_case('QueryTest/insert_permutation', vector)

  def teardown_method(self, method):
    map(self.cleanup_db, ["insert_permutation_test"])


text:
package org.springframework.security.config;

import org.springframework.context.ApplicationListener;
import org.springframework.security.core.session.SessionCreationEvent;

/**
 * @author Luke Taylor
 */
public class TestBusinessBeanImpl implements TestBusinessBean, ApplicationListener<SessionCreationEvent> {
    public void setInteger(int i) {
    }

    public int getInteger() {
        return 1314;
    }

    public void setString(String s) {
    }

    public String getString() {
        return "A string.";
    }

    public void doSomething() {
    }

    public void unprotected() {
    }

    public void onApplicationEvent(SessionCreationEvent event) {
        System.out.println(event);
    }
}


text:
namespace rocksdb {

// Given a path, flatten the path name by replacing all chars not in
// {[0-9,a-z,A-Z,-,_,.]} with _. And append '\0' at the end.
// Return the number of chars stored in dest not including the trailing '\0'.
static int FlattenPath(const std::string& path, char* dest, int len) {
  int write_idx = 0;
  int i = 0;
  int src_len = path.size();

  while (i < src_len && write_idx < len - 1) {
    if ((path[i] >= 'a' && path[i] <= 'z') ||
        (path[i] >= '0' && path[i] <= '9') ||
        (path[i] >= 'A' && path[i] <= 'Z') ||
        path[i] == '-' ||
        path[i] == '.' ||
        path[i] == '_'){
      dest[write_idx++] = path[i];
    } else {
      if (i > 0)
        dest[write_idx++] = '_';
    }
    i++;
  }

  dest[write_idx] = '\0';
  return write_idx;
}

static std::string MakeFileName(const std::string& name, uint64_t number,
                                const char* suffix) {
  char buf[100];
  snprintf(buf, sizeof(buf), "/%06llu.%s",
           static_cast<unsigned long long>(number),
           suffix);
  return name + buf;
}

std::string LogFileName(const std::string& name, uint64_t number) {
  assert(number > 0);
  return MakeFileName(name, number, "log");
}

std::string ArchivalDirectory(const std::string& dir) {
  return dir + "/" + ARCHIVAL_DIR;
}
std::string ArchivedLogFileName(const std::string& name, uint64_t number) {
  assert(number > 0);
  return MakeFileName(name + "/" + ARCHIVAL_DIR, number, "log");
}

std::string TableFileName(const std::string& name, uint64_t number) {
  assert(number > 0);
  return MakeFileName(name, number, "sst");
}

std::string DescriptorFileName(const std::string& dbname, uint64_t number) {
  assert(number > 0);
  char buf[100];
  snprintf(buf, sizeof(buf), "/MANIFEST-%06llu",
           static_cast<unsigned long long>(number));
  return dbname + buf;
}

std::string CurrentFileName(const std::string& dbname) {
  return dbname + "/CURRENT";
}

std::string LockFileName(const std::string& dbname) {
  return dbname + "/LOCK";
}

std::string TempFileName(const std::string& dbname, uint64_t number) {
  return MakeFileName(dbname, number, "dbtmp");
}

std::string InfoLogFileName(const std::string& dbname,
    const std::string& db_path, const std::string& log_dir) {
  if (log_dir.empty())
    return dbname + "/LOG";

  char flatten_db_path[256];
  FlattenPath(db_path, flatten_db_path, 256);
  return log_dir + "/" + flatten_db_path + "_LOG";
}

// Return the name of the old info log file for "dbname".
std::string OldInfoLogFileName(const std::string& dbname, uint64_t ts,
    const std::string& db_path, const std::string& log_dir) {
  char buf[50];
  snprintf(buf, sizeof(buf), "%llu", static_cast<unsigned long long>(ts));

  if (log_dir.empty())
    return dbname + "/LOG.old." + buf;

  char flatten_db_path[256];
  FlattenPath(db_path, flatten_db_path, 256);
  return log_dir + "/" + flatten_db_path + "_LOG.old." + buf;
}

std::string MetaDatabaseName(const std::string& dbname, uint64_t number) {
  char buf[100];
  snprintf(buf, sizeof(buf), "/METADB-%llu",
           static_cast<unsigned long long>(number));
  return dbname + buf;
}

std::string IdentityFileName(const std::string& dbname) {
  return dbname + "/IDENTITY";
}

// Owned filenames have the form:
//    dbname/IDENTITY
//    dbname/CURRENT
//    dbname/LOCK
//    dbname/LOG
//    dbname/LOG.old.[0-9]+
//    dbname/MANIFEST-[0-9]+
//    dbname/[0-9]+.(log|sst)
//    dbname/METADB-[0-9]+
//    Disregards / at the beginning
bool ParseFileName(const std::string& fname,
                   uint64_t* number,
                   FileType* type,
                   WalFileType* log_type) {
  Slice rest(fname);
  if (fname.length() > 1 && fname[0] == '/') {
    rest.remove_prefix(1);
  }
  if (rest == "IDENTITY") {
    *number = 0;
    *type = kIdentityFile;
  } else if (rest == "CURRENT") {
    *number = 0;
    *type = kCurrentFile;
  } else if (rest == "LOCK") {
    *number = 0;
    *type = kDBLockFile;
  } else if (rest == "LOG" || rest == "LOG.old") {
    *number = 0;
    *type = kInfoLogFile;
  } else if (rest.starts_with("LOG.old.")) {
    uint64_t ts_suffix;
    // sizeof also counts the trailing '\0'.
    rest.remove_prefix(sizeof("LOG.old.") - 1);
    if (!ConsumeDecimalNumber(&rest, &ts_suffix)) {
      return false;
    }
    *number = ts_suffix;
    *type = kInfoLogFile;
  } else if (rest.starts_with("MANIFEST-")) {
    rest.remove_prefix(strlen("MANIFEST-"));
    uint64_t num;
    if (!ConsumeDecimalNumber(&rest, &num)) {
      return false;
    }
    if (!rest.empty()) {
      return false;
    }
    *type = kDescriptorFile;
    *number = num;
  } else if (rest.starts_with("METADB-")) {
    rest.remove_prefix(strlen("METADB-"));
    uint64_t num;
    if (!ConsumeDecimalNumber(&rest, &num)) {
      return false;
    }
    if (!rest.empty()) {
      return false;
    }
    *type = kMetaDatabase;
    *number = num;
  } else {
    // Avoid strtoull() to keep filename format independent of the
    // current locale
    bool archive_dir_found = false;
    if (rest.starts_with(ARCHIVAL_DIR)) {
      if (rest.size() <= ARCHIVAL_DIR.size()) {
        return false;
      }
      rest.remove_prefix(ARCHIVAL_DIR.size() + 1); // Add 1 to remove / also
      if (log_type) {
        *log_type = kArchivedLogFile;
      }
      archive_dir_found = true;
    }
    uint64_t num;
    if (!ConsumeDecimalNumber(&rest, &num)) {
      return false;
    }
    Slice suffix = rest;
    if (suffix == Slice(".log")) {
      *type = kLogFile;
      if (log_type && !archive_dir_found) {
        *log_type = kAliveLogFile;
      }
    } else if (archive_dir_found) {
      return false; // Archive dir can contain only log files
    } else if (suffix == Slice(".sst")) {
      *type = kTableFile;
    } else if (suffix == Slice(".dbtmp")) {
      *type = kTempFile;
    } else {
      return false;
    }
    *number = num;
  }
  return true;
}

Status SetCurrentFile(Env* env, const std::string& dbname,
                      uint64_t descriptor_number,
                      Directory* directory_to_fsync) {
  // Remove leading "dbname/" and add newline to manifest file name
  std::string manifest = DescriptorFileName(dbname, descriptor_number);
  Slice contents = manifest;
  assert(contents.starts_with(dbname + "/"));
  contents.remove_prefix(dbname.size() + 1);
  std::string tmp = TempFileName(dbname, descriptor_number);
  Status s = WriteStringToFile(env, contents.ToString() + "\n", tmp, true);
  if (s.ok()) {
    s = env->RenameFile(tmp, CurrentFileName(dbname));
  }
  if (s.ok()) {
    if (directory_to_fsync != nullptr) {
      directory_to_fsync->Fsync();
    }
  } else {
    env->DeleteFile(tmp);
  }
  return s;
}

Status SetIdentityFile(Env* env, const std::string& dbname) {
  std::string id = env->GenerateUniqueId();
  assert(!id.empty());
  // Reserve the filename dbname/000000.dbtmp for the temporary identity file
  std::string tmp = TempFileName(dbname, 0);
  Status s = WriteStringToFile(env, id, tmp, true);
  if (s.ok()) {
    s = env->RenameFile(tmp, IdentityFileName(dbname));
  }
  if (!s.ok()) {
    env->DeleteFile(tmp);
  }
  return s;
}

}  // namespace rocksdb


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>iPad Popover: Top/Bottom</title>
    <link rel="stylesheet" href="../chui/chui.ios.css">

	<app>
		<view id="main" ui-background-style="slanted-left-equal" style="background-color: #bbbac4" ui-navigation-status="current">
         <toolbar class="ui-custom-tint">
            <uibutton id="showPopover1" class="ui-custom-tint" style="background-color: #000">
                Show Popover 1
            </uibutton>
            <uibutton id="showPopover2" class="ui-custom-tint" style="background-color: #000">
                Show Popover is a long button 2
            </uibutton>
             <uibutton id="showPopover3" class="ui-custom-tint" style="background-color: #000">
                 Show Popover 3
             </uibutton>
         </toolbar>
         <subview ui-associations="withNavBar withBottomToolBar">
             <scrollpanel>

             </scrollpanel>
         </subview>
         <toolbar ui-placement="bottom" class="ui-custom-tint">
             <uibutton id="showPopover4" class="ui-custom-tint" style="background-color: #000">
                 Show Popover 4
             </uibutton>
             <uibutton id="showPopover5" class="ui-custom-tint" style="background-color: #000">
                 Show Popover is a very long button you know 5
             </uibutton>
             <uibutton id="showPopover6" class="ui-custom-tint" style="background-color: #000">
                 Show Popover 6
             </uibutton>
         </toolbar>
     </view>
</app>


text:
package materials

import (
	"github.com/DexterLB/traytor/hdrcolour"
	"github.com/DexterLB/traytor/ray"
	"github.com/DexterLB/traytor/sampler"
)

// EmissiveMaterial acts as a lamp
type EmissiveMaterial struct {
	Colour   *sampler.AnySampler
	Strength *sampler.AnySampler
}

// Shade returns the emitted colour after intersecting the material
func (m *EmissiveMaterial) Shade(intersection *ray.Intersection, raytracer Raytracer) *hdrcolour.Colour {
	return m.Colour.GetColour(intersection).Scaled(float32(m.Strength.GetFac(intersection)))
}


text:
<?php

namespace Veles\Cache\Traits;

use Exception;
use Veles\Cache\Adapters\CacheAdapterAbstract;
use Veles\Cache\Adapters\CacheAdapterInterface;

trait CacheAdapterTrait
{
	/** @var CacheAdapterInterface */
	protected static $adapter;
	/** @var  string|CacheAdapterAbstract */
	protected static $adapter_name;

	/**
	 * Set cache adapter initialisation
	 *
	 * @param CacheAdapterInterface $adapter Adapter
	 */
	public static function setAdapter(CacheAdapterInterface $adapter)
	{
		self::$adapter = $adapter;
	}

	/**
	 * Get cache adapter instance
	 *
	 * @throws Exception
	 * @return CacheAdapterInterface
	 */
	public static function getAdapter()
	{
		if (null === self::$adapter) {
			throw new Exception('Adapter not set!');
		}

		return self::$adapter;
	}
}


text:
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[lined,boxed]{algorithm2e}
\usepackage{graphicx}
\author{Ritobroto Maitra\\ Intern: Guardtime}
\title{A Short Review: Quantum Immunity of KSI}
\date{Draft Report}
\begin{document}
\maketitle

\section{}

The Keyless Signature Infrastructure developed by Guardtime brings in a new paradigm that has several technical and practical advantages against the traditional PKI. We need to migrate the security proofs to the quantum setting.

Note: In this draft version, all definitions and related terminologies are borrowed from the original paper on the security proof of the BLT scheme. In the final version, for the sake of completeness, we will include them for a complete reading.

This draft is merely for walking through the essential ideas of the migration, the full version (which is ready, pending comments on this one) includes all the extra material such as theorems and references of the proofs of those theorems from relevant papers.

Assume that the adversary $A_1$ has committed the hash value $r$ as well as the advice $a$. We make no assumption about the nature of $a$ at this stage. Assume that $A_2$ is able to come up with a forgery $x`$.

In this case, walking step-by-step through the original proof, let us see if we can migrate or preserve the conditions.

[All work referenced after this, if not mentioned otherwise, is from \textit{Security Proofs for the BLT Signature Scheme, Ahto Buldas, Risto Laanoja, and Ahto Truu}].

Theorem 3 is respectful, which means that in a quantum game, there is no need to find if there exists an interpreter to translate it. This is straight-forward, since this follows a balanced structure.

The same follows for the entire oracle model used. However, we must make an important observation here - there is nothing, theoretically, preventing an adversary with full control from performing queries in quantum superposition. However, even using the quantum oracle model, we can use the following reduction:

Let us say that our construction involving $R$ is value-dominating. This is easy to prove since $w_{G^e}(T(A)) = w_{G^e}(T(B))$ whenever $w_{G^i}(T(A)) = w_{G^i}(T(B))$. In this case, however, we can also use the \textit{effective} reduction, since $alpha_{G^e}(T(A)) \geq w_{G^i}(T(A))$.

For the next one, however, we can \textit{not} use game-preserving reductions anymore. Let us, instead, use a translator $T$ or a quantum transformer that uses a quantum game $G`$ instead. From the underlying assumptions of security, we have an ($A,B$)-consistent reduction. Also, we can use in this context the property that $alpha_{G`^e}(T`(A`)) \geq w_{G`^i}(T`(A`))$.  This directly implies that with this reduction, we can apply a game-updating condition. Although this reduction is non-trivial, it can be verified using the proof by Katz et al, (but using the respectful reduction instead of the consistent-successive reduction used in the original proof).

Given this, it is now a trivial task to propose the migration of the proof in its entirety, by only proving that there exists a translator - which also stems as a by-product of the previous transformation, as a value-dominating, extendible and straight-line transformation.

The novelty of this entire proof is in that we do not have to a lot of ``re-working'' of the original proof - we can just use the original assumptions and the original games with the reductions and updates. It could have been done in a lot more trivially but in a rather tedious way by re-working the entire path, but in my opinion this is more useful since it keeps intact all the other parts of the infrastructure.

Q.E.D.

\end{document}