text:
require 'rails_helper'

RSpec.describe "products/show", type: :view do
  before(:each) do
    @product = assign(:product, Product.create!())
  end

  it "renders attributes in <p>" do
    render
  end
end

redpajama_set_name: RedPajamaGithub


text:
@implementation URBNAlertActionButton

@end

static NSInteger const kURBNAlertViewHeightPadding = 80.f;

@interface URBNAlertView()

@property (nonatomic, strong) URBNAlertConfig *alertConfig;
@property (nonatomic, strong) URBNAlertStyle *alertStyler;
@property (nonatomic, strong) UIView *titleBgView;
@property (nonatomic, copy) NSArray *buttons;
@property (nonatomic, assign) NSInteger sectionCount;

@end

@implementation URBNAlertView

- (instancetype)initWithAlertConfig:(URBNAlertConfig *)config alertStyler:(URBNAlertStyle *)alertStyler customView:(UIView *)customView {
    self = [super init];
    if (self) {
        self.alertConfig = config;
        self.alertStyler = alertStyler;

        if (!customView) {
            // Give it a dummy view
            self.customView = [UIView new];
        }
        else {
            self.customView = customView;
            self.sectionCount++;
        }

        self.customView.translatesAutoresizingMaskIntoConstraints = NO;

        self.backgroundColor = self.alertStyler.backgroundColor ?: [UIColor whiteColor];
        self.layer.cornerRadius = self.alertStyler.alertCornerRadius.floatValue;

        UIView *buttonContainer = [UIView new];
        NSDictionary *views;

        [self addSubview:self.titleBgView];
        [self addSubview:self.titleLabel];
        [self addSubview:self.messageTextView];
        [self addSubview:self.errorLabel];
        [self addSubview:self.customView];

        NSMutableDictionary *mutableViews = [NSMutableDictionary dictionaryWithDictionary:@{@"_customView" : _customView, @"_titleLabel" : _titleLabel, @"_titleBgView": _titleBgView, @"_messageTextView" : _messageTextView, @"buttonContainer" : buttonContainer, @"_errorLabel" : _errorLabel}];

        if (self.alertConfig.inputs && self.alertConfig.inputs.count > 0) {
            __weak typeof(self) weakSelf = self;

            [self.alertConfig.inputs enumerateObjectsUsingBlock:^(URBNTextField *tf, NSUInteger idx, BOOL *stop) {
                tf.edgeInsets = alertStyler.textFieldEdgeInsets;
                tf.translatesAutoresizingMaskIntoConstraints = NO;
                [mutableViews setObject:tf forKey:[NSString stringWithFormat:@"textField%lu", (unsigned long)idx]];
                weakSelf.sectionCount++;
                [weakSelf addSubview:tf];
            }];
        }

        views = [mutableViews copy];

        // Add some buttons
        NSMutableArray *btns = [NSMutableArray new];
        buttonContainer.translatesAutoresizingMaskIntoConstraints = NO;

        __weak typeof(self) weakSelf = self;
        [self.alertConfig.actions enumerateObjectsUsingBlock:^(URBNAlertAction *action, NSUInteger idx, BOOL *stop) {
            if (action.isButton) {
                URBNAlertActionButton *btn = [weakSelf createAlertViewButtonWithAction:action atIndex:idx];
                [buttonContainer addSubview:btn];
                [btns addObject:btn];
                action.actionButton = btn;
            }
        }];

        [self addSubview:buttonContainer];

        // Handle if no title or messages, give 0 margins
        NSNumber *titleMargin = self.alertConfig.title.length > 0 ? self.alertStyler.sectionVerticalMargin : @0;
        NSNumber *msgMargin = self.alertConfig.message.length > 0 ? @([self.alertStyler.sectionVerticalMargin floatValue]+[self.alertStyler.messageVerticalMargin floatValue]) : @0;

        if (titleMargin.floatValue > 0) {
            self.sectionCount++;
        }

        if (msgMargin.floatValue > 0) {
            self.sectionCount++;
        }

        NSDictionary *metrics = @{@"sectionMargin" : self.alertStyler.sectionVerticalMargin,
                                  @"btnH" : self.alertStyler.buttonHeight,
                                  @"lblHMargin" : self.alertStyler.labelHorizontalMargin,
                                  @"titleVMargin" : titleMargin,
                                  @"msgVMargin" : msgMargin,
                                  @"btnTopMargin" : @(self.alertStyler.buttonMarginEdgeInsets.top),
                                  @"btnLeftMargin" : @(self.alertStyler.buttonMarginEdgeInsets.left),
                                  @"btnBottomMargin" : @(self.alertStyler.buttonMarginEdgeInsets.bottom),
                                  @"btnRightMargin" : @(self.alertStyler.buttonMarginEdgeInsets.right),
                                  @"cvMargin" : self.alertStyler.customViewMargin,
                                  @"tfVMargin": self.alertStyler.textFieldVerticalMargin};

        for (UIView *lbl in @[self.titleLabel, self.messageTextView, self.errorLabel]) {
            lbl.translatesAutoresizingMaskIntoConstraints = NO;
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-lblHMargin-[lbl]-lblHMargin-|" options:0 metrics:metrics views:NSDictionaryOfVariableBindings(lbl)]];
        }

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-cvMargin-[_customView]-cvMargin-|" options:0 metrics:metrics views:views]];

        if (!self.alertConfig.inputs && self.alertConfig.inputs.count == 0) {
            if (self.alertConfig.isActiveAlert) {
                [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-titleVMargin-[_titleLabel]-msgVMargin-[_messageTextView]-cvMargin-[_customView]-5-[_errorLabel]-cvMargin-[buttonContainer]|" options:0 metrics:metrics views:views]];
            }
            // Passive alert, dont added margins for buttonContainer
            else {
                [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-titleVMargin-[_titleLabel]-msgVMargin-[_messageTextView]-cvMargin-[_customView]-cvMargin-|" options:0 metrics:metrics views:views]];
            }
        }
        else {
            NSMutableString *vertVfl = [NSMutableString stringWithString:@"V:|-titleVMargin-[_titleLabel]-msgVMargin-[_messageTextView]-cvMargin-[_customView]-cvMargin-"];

            [self.alertConfig.inputs enumerateObjectsUsingBlock:^(UITextField *tf, NSUInteger idx, BOOL *stop) {
                [vertVfl appendString:[NSString stringWithFormat:@"[textField%lu]-tfVMargin-", (unsigned long)idx]];
                [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-lblHMargin-[textField%lu]-lblHMargin-|", (unsigned long)idx] options:0 metrics:metrics views:views]];
            }];

            [vertVfl appendString:@"[_errorLabel][buttonContainer]|"];

            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vertVfl options:0 metrics:metrics views:views]];
        }

        // Button Constraints
        self.buttons = [btns copy];
        if (self.buttons.count == 1) {
            self.sectionCount++;
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
        }
        else if (self.buttons.count == 2) {
            self.sectionCount++;
            if([self.alertStyler.buttonAlignVertically intValue] == 0){
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-[btnTwo(==btnOne)]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject, @"btnTwo" : self.buttons[1]}]];
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnTwo(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnTwo" : self.buttons[1]}]];
            }else{
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-[btnTwo(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject, @"btnTwo" : self.buttons[1]}]];
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
                [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnTwo]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnTwo" : self.buttons[1]}]];
            }
        } else if (self.buttons.count == 3) {
            self.sectionCount++;
            // alertStyler.buttonAlignVertically ALWAYS
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-[btnTwo(btnH)]-btnBottomMargin-[btnThree(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject, @"btnTwo" : self.buttons[1], @"btnThree" : self.buttons[2]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnTwo]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnTwo" : self.buttons[1]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnThree]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnThree" : self.buttons[2]}]];
        } else if (self.buttons.count == 4) {
            self.sectionCount++;
            // alertStyler.buttonAlignVertically ALWAYS
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-[btnTwo(btnH)]-btnBottomMargin-[btnThree(btnH)]-btnBottomMargin-[btnFour(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject, @"btnTwo" : self.buttons[1], @"btnThree" : self.buttons[2], @"btnFour" : self.buttons[3]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnTwo]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnTwo" : self.buttons[1]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnThree]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnThree" : self.buttons[2]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnFour]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnFour" : self.buttons[3]}]];
        } else if (self.buttons.count == 5) {
            self.sectionCount++;
            // alertStyler.buttonAlignVertically ALWAYS
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-btnTopMargin-[btnOne(btnH)]-btnBottomMargin-[btnTwo(btnH)]-btnBottomMargin-[btnThree(btnH)]-btnBottomMargin-[btnFour(btnH)]-btnBottomMargin-[btnFive(btnH)]-btnBottomMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject, @"btnTwo" : self.buttons[1], @"btnThree" : self.buttons[2], @"btnFour" : self.buttons[3], @"btnFive" : self.buttons[4]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnOne]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnOne" : self.buttons.firstObject}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnTwo]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnTwo" : self.buttons[1]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnThree]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnThree" : self.buttons[2]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnFour]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnFour" : self.buttons[3]}]];
            [buttonContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-btnLeftMargin-[btnFive]-btnRightMargin-|" options:0 metrics:metrics views:@{@"btnFive" : self.buttons[4]}]];
        }
        // TODO: Handle 3+ buttons with a vertical layout

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[buttonContainer]|" options:0 metrics:metrics views:views]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_titleBgView]|" options:0 metrics:metrics views:views]];

        // If passive alert & a passive action was added, need call back when alertview is touched
        if (!self.alertConfig.isActiveAlert && self.alertConfig.actions.count > 0) {
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(passiveAlertViewTouched)];
            [self addGestureRecognizer:tapGesture];
        }
    }

    return self;
}

- (void)layoutSubviews {
    [self.messageTextView sizeToFit];
    [self.messageTextView layoutIfNeeded];

    CGFloat buttonHeight = self.buttons.count == 0 ? 0 : self.alertStyler.buttonHeight.floatValue;
    CGFloat screenHeight = SCREEN_HEIGHT;

    // Need this check because before iOS 8 screen.bounes.size is NOT orientation dependent
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    if ((SYSTEM_VERSION_LESS_THAN(@"8.0")) && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        screenHeight = screenSize.width;
    }

    CGFloat maxHeight = screenHeight - self.titleLabel.intrinsicContentSize.height - (self.alertStyler.sectionVerticalMargin.floatValue * self.sectionCount) - buttonHeight - kURBNAlertViewHeightPadding;

    if (!self.messageTextView.urbn_heightLayoutConstraint) {
        [self.messageTextView urbn_addHeightLayoutConstraintWithConstant:0];
    }

    if (self.messageTextView.text.length > 0) {
        if (self.messageTextView.contentSize.height > maxHeight) {
            self.messageTextView.urbn_heightLayoutConstraint.constant = maxHeight;
            self.messageTextView.scrollEnabled = YES;
        }
        else {
            self.messageTextView.urbn_heightLayoutConstraint.constant = self.messageTextView.contentSize.height;
        }
    }
    // code above needs to be called before super. Crashes on iOS 7 if called after

    [super layoutSubviews];

    self.titleLabel.preferredMaxLayoutWidth = self.titleLabel.frame.size.width;

    self.layer.shadowColor = self.alertStyler.alertViewShadowColor.CGColor;
    self.layer.shadowOffset = self.alertStyler.alertShadowOffset;
    self.layer.shadowOpacity = self.alertStyler.alertViewShadowOpacity.floatValue;
    self.layer.shadowRadius = self.alertStyler.alertViewShadowRadius.floatValue;
    [self.layer setActions:@{@"shadowPath" : [NSNull null]}];

    // rounding title BG
    CGRect tbgf = self.titleBgView.frame;
    CGFloat tbgf_h = self.titleLabel.frame.origin.y+self.titleLabel.frame.size.height+([self.alertStyler.sectionVerticalMargin floatValue]);
    tbgf = CGRectMake(tbgf.origin.x, 0, tbgf.size.width, tbgf_h);
    self.titleBgView.frame = tbgf;
    UIBezierPath *maskPath;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:_titleBgView.bounds
                                     byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
                                           cornerRadii:CGSizeMake(self.alertStyler.alertCornerRadius.floatValue, self.alertStyler.alertCornerRadius.floatValue)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    _titleBgView.layer.mask = maskLayer;
}

#pragma mark - Getters

- (UIView *)titleBgView {
    if (!_titleBgView) {
        _titleBgView = [UIView new];
        _titleBgView.translatesAutoresizingMaskIntoConstraints = NO;
        _titleBgView.backgroundColor = self.alertStyler.titleBackgroundColor;
        //_titleBgView.layer.cornerRadius = self.alertStyler.alertCornerRadius.floatValue;
    }
    return _titleBgView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.numberOfLines = 2;
        _titleLabel.textAlignment = self.alertStyler.titleAlignment;
        _titleLabel.adjustsFontSizeToFitWidth = YES;
        _titleLabel.font = self.alertStyler.titleFont;
        _titleLabel.textColor = self.alertStyler.titleColor;
        _titleLabel.text = self.alertConfig.title;
    }

    return _titleLabel;
}

- (UITextView *)messageTextView {
    if (!_messageTextView) {
        _messageTextView = [UITextView new];
        _messageTextView.backgroundColor = [UIColor clearColor];
        _messageTextView.font = self.alertStyler.messageFont;
        _messageTextView.textColor = self.alertStyler.messageColor;
        if(self.alertConfig.attributedMessage != nil){
            _messageTextView.attributedText = self.alertConfig.attributedMessage;
        }else{
            _messageTextView.text = self.alertConfig.message;
        }
        _messageTextView.textAlignment = self.alertStyler.messageAlignment;
        _messageTextView.scrollEnabled = NO;
        _messageTextView.editable = NO;
        [_messageTextView setContentInset:UIEdgeInsetsZero];
        [_messageTextView scrollRangeToVisible:NSMakeRange(0, 0)];
    }

    return _messageTextView;
}

- (UILabel *)errorLabel {
    if (!_errorLabel) {
        _errorLabel = [UILabel new];
        _errorLabel.numberOfLines = 0;
        _errorLabel.font = self.alertStyler.errorTextFont;
        _errorLabel.textColor = self.alertStyler.errorTextColor;
        _errorLabel.alpha = 0;
    }

    return _errorLabel;
}

#pragma mark - Methods
- (URBNAlertActionButton *)createAlertViewButtonWithAction:(URBNAlertAction *)action atIndex:(NSInteger)index {
    UIColor *bgColor = self.alertStyler.buttonBackgroundColor;
    UIColor *titleColor = self.alertStyler.buttonTitleColor;

    if (action.actionType == URBNAlertActionTypeDestructive) {
        titleColor = self.alertStyler.destructiveButtonTitleColor;
        bgColor = self.alertStyler.destructionButtonBackgroundColor;
    }
    else if (action.actionType == URBNAlertActionTypeCancel) {
        titleColor = self.alertStyler.cancelButtonTitleColor;
        bgColor = self.alertStyler.cancelButtonBackgroundColor;
    }

    URBNAlertActionButton *btn = [URBNAlertActionButton buttonWithType:UIButtonTypeCustom];
    btn.translatesAutoresizingMaskIntoConstraints = NO;
    btn.backgroundColor = bgColor;
    btn.titleLabel.font = self.alertStyler.buttonFont;
    btn.layer.cornerRadius = self.alertStyler.buttonCornerRadius.floatValue;
    btn.layer.borderWidth = self.alertStyler.buttonBorderWidth.floatValue;
    btn.layer.borderColor = self.alertStyler.buttonBorderColor.CGColor;
    btn.layer.shadowColor = self.alertStyler.buttonShadowColor.CGColor;
    btn.layer.shadowOpacity = self.alertStyler.buttonShadowOpacity.floatValue;
    btn.layer.shadowRadius = self.alertStyler.buttonShadowRadius.floatValue;
    btn.layer.shadowOffset = self.alertStyler.buttonShadowOffset;
    btn.titleLabel.layer.shadowColor = self.alertStyler.buttonTitleShadowColor.CGColor;
    btn.titleLabel.layer.shadowOpacity = self.alertStyler.buttonTitleShadowOpacity.floatValue;
    btn.titleLabel.layer.shadowRadius = self.alertStyler.buttonTitleShadowRadius.floatValue;
    btn.titleLabel.layer.shadowOffset = self.alertStyler.buttonTitleShadowOffset;
    btn.tag = index;
    btn.actionType = action.actionType;
    btn.alertStyler = self.alertStyler;

    [btn setTitle:action.title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchUpInside];
    if(action.rightIcon != nil){
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
        UIImageView* icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:action.rightIcon]];
        [btn addSubview:icon];
        icon.center = CGPointMake(btn.frame.size.width - 20,btn.frame.size.height/2);
        icon.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    }
    return btn;
}

- (void)setErrorLabelText:(NSString *)errorText {
    [UIView animateWithDuration:0.2 animations:^{
        self.errorLabel.text = errorText;
        self.errorLabel.alpha = 1;
    }];
}

- (void)setLoadingState:(BOOL)newState forTextFieldAtIndex:(NSUInteger)index {
    [self setButtonsEnabled:!newState];
    if (index < self.alertConfig.inputs.count) {
        UITextField *textField = [self.alertConfig.inputs objectAtIndex:index];

        if (newState) {
            // Disable buttons, show loading
            [textField urbn_showLoading:YES animated:YES spinnerInsets:UIEdgeInsetsMake(0, 0, 0, 8)];
        }
        else {
            if (textField) {
                [textField urbn_showLoading:NO animated:YES];
            }
        }
    }
}

- (void)setButtonsEnabled:(BOOL)enabled {
    for (URBNAlertAction *action in self.alertConfig.actions) {
        [action setEnabled:enabled];
    }
}

#pragma mark - Actions
- (void)buttonTouch:(id)sender {
    UIButton *btn = (UIButton *)sender;

    if (self.buttonTouchedBlock) {
        self.buttonTouchedBlock([self.alertConfig.actions objectAtIndex:btn.tag]);
    }
}

- (void)passiveAlertViewTouched {
    if (self.alertViewTouchedBlock) {
        self.alertViewTouchedBlock(self.alertConfig.actions.firstObject);
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Prevent crashing undo bug
    if(range.length + range.location > textField.text.length) {
        return NO;
    }

    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    return (newLength > self.alertStyler.textFieldMaxLength.integerValue) ? NO : YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    return NO;
}

@end


text:
extern XMPFileHandler * MPEG4_MetaHandlerCTor ( XMPFiles * parent );

extern bool MPEG4_CheckFormat ( XMP_FileFormat format,
								 XMP_StringPtr  filePath,
								 LFA_FileRef    fileRef,
								 XMPFiles *     parent );

static const XMP_OptionBits kMPEG4_HandlerFlags = ( kXMPFiles_CanInjectXMP |
													kXMPFiles_CanExpand |
													kXMPFiles_CanRewrite |
													kXMPFiles_PrefersInPlace |
													kXMPFiles_CanReconcile |
													kXMPFiles_AllowsOnlyXMP |
													kXMPFiles_ReturnsRawPacket |
													kXMPFiles_AllowsSafeUpdate
												  );

class MPEG4_MetaHandler : public XMPFileHandler
{
public:

	void CacheFileData();
	void ProcessXMP();

	void UpdateFile ( bool doSafeUpdate );
    void WriteFile  ( LFA_FileRef sourceRef, const std::string & sourcePath );

	MPEG4_MetaHandler ( XMPFiles * _parent );
	virtual ~MPEG4_MetaHandler();

private:

	MPEG4_MetaHandler() : xmpBoxPos(0) {};	// Hidden on purpose.

	void MakeLegacyDigest ( std::string * digestStr );
	void PickNewLocation();

	XMP_Uns64 xmpBoxPos;	// The file offset of the XMP box (the size field, not the content).

	std::string mvhdBox;	// ! Both contain binary data, but std::string is handy.
	std::vector<std::string> cprtBoxes;

};	// MPEG4_MetaHandler

// =================================================================================================

#endif // __MPEG4_Handler_hpp__


text:
<transfer-table tr-model="tableData" limits="tableLimits" help-text="tableHelpText">

    <allocated ng-model="tableData.allocated.length">

                        <hz-magic-search-bar filter-facets="facets"></hz-magic-search-bar>

                    Name

                             {$ ::tableHelpText.noAllocText $}

                        {$ row.name $}

                        <action-list>
                            <button tabIndex="0"
                                    ng-class="'btn btn-default'"
                                    ng-click="trCtrl.deallocate(row)"
                                    type="button">

                            </button>
                        </action-list>

    </allocated>

    <available>

                        <hz-magic-search-bar filter-facets="facets"></hz-magic-search-bar>

                    Name

                             {$ ::tableHelpText.noAvailText $}

                    {$ row.name $}

                        <action-list button-tooltip="row.warningMessage"
                                     bt-model="ctrl.tooltipModel"
                                     bt-disabled="!row.disabled"
                                     warning-classes="'invalid'">
                            <notifications>

                            </notifications>
                            <button tabIndex="0"
                                    ng-class="'btn btn-default'"
                                    ng-click="trCtrl.allocate(row)"
                                    type="button">

                            </button>
                        </action-list>

            <select
                    d-select
                    id="{$ id $}_select"
                    data-add-item-url
                    multiple
                    name="{$ name $}" >
            </select>

    </available>

</transfer-table>


text:
"""
  Copyright 2015 Netflix, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
"""
import os

__author__ = 'tgianos'

__all__ = []

for module in os.listdir(os.path.dirname(__file__)):
    if module != '__init__.py' and module[-3:] == '.py':
        __all__.append(module[:-3])


text:
@implementation UIView (MKHDesignableAnimation)

- (void)animateWithNib:(NSString *)targetNibName
              duration:(NSTimeInterval)duration
                 delay:(NSTimeInterval)delay
               options:(UIViewAnimationOptions)options
            animations:(void (^)(id weakSelf, id targetView))animations
            completion:(void (^)(BOOL finished))completion
{
    static UIViewController *ctrl = nil;

    if ([targetNibName isKindOfClass:NSString.class] &&
        targetNibName.length &&
        animations)
    {
        if (!ctrl)
        {
            ctrl = [UIViewController new];
        }

        //===

        // load target view:

        __block UIView *targetView =
        [[NSBundle mainBundle]
         loadNibNamed:targetNibName owner:ctrl options:nil].lastObject;

        //===

        // animate:

        __block typeof(self) weakSelf = self;

        [UIView
         animateWithDuration:duration
         delay:delay
         options:options
         animations:^{

             animations(weakSelf, targetView);
         }
         completion:completion];
    }
}

- (void)animateWithNib:(NSString *)targetNibName
            animations:(void (^)(id weakSelf, id targetView))animations
            completion:(void (^)(BOOL finished))completion
{
    [self
     animateWithNib:targetNibName
     duration:0.7
     delay:0.0
     options:0
     animations:animations
     completion:completion];
}

- (void)animateWithNib:(NSString *)targetNibName
            animations:(void (^)(id weakSelf, id targetView))animations
{
    [self
     animateWithNib:targetNibName
     duration:0.7
     delay:0.0
     options:0
     animations:animations
     completion:nil];
}

@end


text:
package server

import (
	"fmt"
	"net"
	"strings"
	"time"

	"github.com/cilium/cilium/api/v1/health/models"
	ciliumModels "github.com/cilium/cilium/api/v1/models"
	"github.com/cilium/cilium/pkg/health/client"
	"github.com/cilium/cilium/pkg/health/defaults"
	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/logging/logfields"

	"github.com/servak/go-fastping"
	"github.com/sirupsen/logrus"
)

// healthReport is a snapshot of the health of the cluster.
type healthReport struct {
	startTime time.Time
	nodes     []*models.NodeStatus
}

type prober struct {
	*fastping.Pinger
	server *Server

	// 'stop' is closed upon a call to prober.Stop(). When the stopping is
	// finished, then prober.Done() will be notified.
	stop         chan bool
	proberExited chan bool
	done         chan bool

	// The lock protects multiple requests attempting to update the status
	// at the same time - ie, serialize updates between the periodic prober
	// and probes initiated via "GET /status/probe". It is also used to
	// co-ordinate updates of the ICMP responses and the HTTP responses.
	lock.RWMutex

	// start is the start time for the current probe cycle.
	start   time.Time
	results map[ipString]*models.PathStatus
	nodes   nodeMap
}

// copyResultRLocked makes a copy of the path status for the specified IP.
func (p *prober) copyResultRLocked(ip string) *models.PathStatus {
	status := p.results[ipString(ip)]
	if status == nil {
		return nil
	}

	result := &models.PathStatus{
		IP: ip,
	}
	paths := map[**models.ConnectivityStatus]*models.ConnectivityStatus{
		&result.Icmp: status.Icmp,
		&result.HTTP: status.HTTP,
	}
	for res, value := range paths {
		if value != nil {
			*res = &*value
		}
	}
	return result
}

// getResults gathers a copy of all of the results for nodes currently in the
// cluster.
func (p *prober) getResults() *healthReport {
	p.RLock()
	defer p.RUnlock()

	// De-duplicate IPs in 'p.nodes' by building a map based on node.Name.
	resultMap := map[string]*models.NodeStatus{}
	for _, node := range p.nodes {
		if resultMap[node.Name] != nil {
			continue
		}
		primaryIP := node.PrimaryIP()
		healthIP := node.HealthIP()
		status := &models.NodeStatus{
			Name: node.Name,
			Host: &models.HostStatus{
				PrimaryAddress: p.copyResultRLocked(primaryIP),
			},
		}
		if healthIP != "" {
			status.Endpoint = p.copyResultRLocked(healthIP)
		}
		secondaryResults := []*models.PathStatus{}
		for _, addr := range node.SecondaryAddresses {
			if addr.Enabled {
				secondaryStatus := p.copyResultRLocked(addr.IP)
				secondaryResults = append(secondaryResults, secondaryStatus)
			}
		}
		status.Host.SecondaryAddresses = secondaryResults
		resultMap[node.Name] = status
	}

	result := &healthReport{startTime: p.start}
	for _, res := range resultMap {
		result.nodes = append(result.nodes, res)
	}
	return result
}

func isIPv4(ip string) bool {
	netIP := net.ParseIP(ip)
	return netIP != nil && !strings.Contains(ip, ":")
}

func skipAddress(elem *ciliumModels.NodeAddressingElement) bool {
	return elem == nil || !elem.Enabled || elem.IP == "<nil>"
}

// resolveIP attempts to sanitize 'node' and 'ip', and if successful, returns
// the name of the node and the IP address specified in the addressing element.
// If validation fails or this IP should not be pinged, 'ip' is returned as nil.
func resolveIP(n *healthNode, addr *ciliumModels.NodeAddressingElement, proto string, primary bool) (string, *net.IPAddr) {
	node := n.NodeElement
	network := "ip6:icmp"
	if isIPv4(addr.IP) {
		network = "ip4:icmp"
	}
	scopedLog := log.WithFields(logrus.Fields{
		logfields.NodeName: node.Name,
		logfields.IPAddr:   addr.IP,
		"primary":          primary,
	})

	if skipAddress(addr) {
		scopedLog.Debug("Skipping probe for address")
		return "", nil
	}

	ra, err := net.ResolveIPAddr(network, addr.IP)
	if err != nil {
		scopedLog.Debug("Unable to resolve address")
		return "", nil
	}

	scopedLog.WithField("protocol", proto).Debug("Probing for connectivity to node")
	return node.Name, ra
}

// markIPsLocked marks all nodes in the prober for deletion.
func (p *prober) markIPsLocked() {
	for ip, node := range p.nodes {
		node.deletionMark = true
		p.nodes[ip] = node
	}
}

// sweepIPsLocked iterates through nodes in the prober and removes nodes which
// are marked for deletion.
func (p *prober) sweepIPsLocked() {
	for ip, node := range p.nodes {
		if node.deletionMark {
			// Remove deleted nodes from:
			// * Results (accessed from ICMP pinger or TCP prober)
			// * ICMP pinger
			// * TCP prober
			for elem := range node.Addresses() {
				delete(p.results, ipString(elem.IP))
				p.RemoveIP(elem.IP) // ICMP pinger
			}
			delete(p.nodes, ip) // TCP prober
		}
	}
}

// setNodes sets the list of nodes for the prober, and updates the pinger to
// start sending pings to all of the nodes.
// setNodes will steal references to nodes referenced from 'nodes', so the
// caller should not modify them after a call to setNodes.
func (p *prober) setNodes(nodes nodeMap) {
	p.Lock()
	defer p.Unlock()

	// Mark all nodes for deletion, insert nodes that should not be deleted
	// then at the end of the function, sweep all nodes that remain as
	// "to be deleted".
	p.markIPsLocked()

	for _, n := range nodes {
		for elem, primary := range n.Addresses() {
			_, addr := resolveIP(&n, elem, "icmp", primary)

			ip := ipString(elem.IP)
			result := &models.ConnectivityStatus{}
			if addr == nil {
				result.Status = "Failed to resolve IP"
			} else {
				result.Status = "Connection timed out"
				p.AddIPAddr(addr)
				p.nodes[ip] = n
			}

			if p.results[ip] == nil {
				p.results[ip] = &models.PathStatus{
					IP: elem.IP,
				}
			}
			p.results[ip].Icmp = result
		}
	}

	p.sweepIPsLocked()
}

func (p *prober) httpProbe(node string, ip string, port int) *models.ConnectivityStatus {
	result := &models.ConnectivityStatus{}

	host := fmt.Sprintf("http://%s:%d", ip, port)
	scopedLog := log.WithFields(logrus.Fields{
		logfields.NodeName: node,
		logfields.IPAddr:   ip,
		"host":             host,
		"path":             PortToPaths[port],
	})

	client, err := client.NewClient(host)
	if err == nil {
		scopedLog.Debug("Greeting host")
		start := time.Now()
		_, err = client.Restapi.GetHello(nil)
		rtt := time.Since(start)
		if err == nil {
			scopedLog.WithField("rtt", rtt).Debug("Greeting successful")
			result.Status = ""
			result.Latency = rtt.Nanoseconds()
		} else {
			scopedLog.WithError(err).Debug("Greeting snubbed")
			result.Status = "Connection timed out"
		}
	} else {
		scopedLog.WithError(err).Info("Failed to express greeting to host")
		result.Status = err.Error()
	}

	return result
}

func (p *prober) runHTTPProbe() {
	startTime := time.Now()
	p.Lock()
	p.start = startTime
	p.Unlock()

	// p.nodes is mapped from all known IPs -> nodes in N:M configuration,
	// so multiple IPs could refer to the same node. To ensure we only
	// ping each node once, deduplicate nodes into map of nodeName -> []IP.
	// When probing below, we won't hold the lock on 'p.nodes' so take
	// a copy of all of the IPs we need to reference.
	nodes := make(map[string][]*net.IPAddr)
	p.RLock()
	for _, node := range p.nodes {
		if nodes[node.Name] != nil {
			// Already handled this node.
			continue
		}
		nodes[node.Name] = []*net.IPAddr{}
		for elem, primary := range node.Addresses() {
			if _, addr := resolveIP(&node, elem, "http", primary); addr != nil {
				nodes[node.Name] = append(nodes[node.Name], addr)
			}
		}
	}
	p.RUnlock()

	for name, ips := range nodes {
		for _, ip := range ips {
			scopedLog := log.WithFields(logrus.Fields{
				logfields.NodeName: name,
				logfields.IPAddr:   ip.String(),
			})

			status := &models.PathStatus{}
			ports := map[int]**models.ConnectivityStatus{
				defaults.HTTPPathPort: &status.HTTP,
			}
			for port, result := range ports {
				*result = p.httpProbe(name, ip.String(), port)
				if status.HTTP.Status != "" {
					scopedLog.WithFields(logrus.Fields{
						logfields.Port: port,
					}).Debugf("Failed to probe: %s", status.HTTP.Status)
				}
			}

			peer := ipString(ip.String())
			p.Lock()
			if _, ok := p.results[peer]; ok {
				p.results[peer].HTTP = status.HTTP
			} else {
				// While we weren't holding the lock, the
				// pinger's OnIdle() callback fired and updated
				// the set of nodes to remove this node.
				scopedLog.Debug("Node disappeared before result written")
			}
			p.Unlock()
		}
	}
}

// Done returns a channel that is closed when RunLoop() is stopped by an error.
// It must be called after the RunLoop() call.
func (p *prober) Done() <-chan bool {
	return p.done
}

// Run sends a single probes out to all of the other cilium nodes to gather
// connectivity status for the cluster.
func (p *prober) Run() error {
	err := p.Pinger.Run()
	p.runHTTPProbe()
	return err
}

// Stop disrupts the currently running RunLoop(). This may only be called after
// a call to RunLoop().
func (p *prober) Stop() {
	p.Pinger.Stop()
	close(p.stop)
	<-p.proberExited
	close(p.done)
}

// RunLoop periodically sends probes out to all of the other cilium nodes to
// gather connectivity status for the cluster.
//
// This is a non-blocking method so it immediately returns. If you want to
// stop sending packets, call Stop().
func (p *prober) RunLoop() {
	// FIXME: Spread the probes out across the probing interval
	p.Pinger.RunLoop()

	go func() {
		tick := time.NewTicker(p.server.ProbeInterval)
	loop:
		for {
			select {
			case <-p.stop:
				break loop
			case <-tick.C:
				p.runHTTPProbe()
				continue
			}
		}
		tick.Stop()
		close(p.proberExited)
	}()
}

// newPinger prepares a prober. The caller may invoke one the Run* methods of
// the prober to populate its 'results' map.
func newProber(s *Server, nodes nodeMap) *prober {
	prober := &prober{
		Pinger:       fastping.NewPinger(),
		server:       s,
		done:         make(chan bool),
		proberExited: make(chan bool),
		stop:         make(chan bool),
		results:      make(map[ipString]*models.PathStatus),
		nodes:        make(nodeMap),
	}
	prober.MaxRTT = s.ProbeDeadline

	prober.setNodes(nodes)
	prober.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
		prober.Lock()
		defer prober.Unlock()
		node, exists := prober.nodes[ipString(addr.String())]

		scopedLog := log.WithFields(logrus.Fields{
			logfields.IPAddr: addr,
			"rtt":            rtt,
		})
		if !exists {
			scopedLog.Debugf("Node disappeared, skip result")
			return
		}

		prober.results[ipString(addr.String())].Icmp = &models.ConnectivityStatus{
			Latency: rtt.Nanoseconds(),
			Status:  "",
		}
		scopedLog.WithFields(logrus.Fields{
			logfields.NodeName: node.Name,
		}).Debugf("Probe successful")
	}

	return prober
}


text:
namespace StockSharp.BitStamp.Native.Model
{
	using System;
	using System.Reflection;

	using Newtonsoft.Json;

	[Obfuscation(Feature = "renaming", ApplyToMembers = true)]
	class UserOrder
	{
		[JsonProperty("id")]
		public long Id { get; set; }

		[JsonProperty("datetime")]
		//[JsonConverter(typeof(JsonDateTimeConverter))]
		public DateTime Time { get; set; }

		[JsonProperty("type")]
		public int Type { get; set; }

		[JsonProperty("price")]
		public double Price { get; set; }

		[JsonProperty("amount")]
		public double Amount { get; set; }

		[JsonProperty("currency_pair")]
		public string CurrencyPair { get; set; }
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 75(2): 249 (1980)

#### Original name
Henicospora P.M. Kirk & B. Sutton

### Remarks
null


text:
using namespace llvm;

#define DEBUG_TYPE "WinCOFFStreamer"

MCWinCOFFStreamer::MCWinCOFFStreamer(MCContext &Context,
                                     std::unique_ptr<MCAsmBackend> MAB,
                                     std::unique_ptr<MCCodeEmitter> CE,
                                     std::unique_ptr<MCObjectWriter> OW)
    : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)),
      CurSymbol(nullptr) {}

void MCWinCOFFStreamer::EmitInstToData(const MCInst &Inst,
                                       const MCSubtargetInfo &STI) {
  MCDataFragment *DF = getOrCreateDataFragment();

  SmallVector<MCFixup, 4> Fixups;
  SmallString<256> Code;
  raw_svector_ostream VecOS(Code);
  getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);

  // Add the fixups and data.
  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
    Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
    DF->getFixups().push_back(Fixups[i]);
  }
  DF->setHasInstructions(STI);
  DF->getContents().append(Code.begin(), Code.end());
}

void MCWinCOFFStreamer::InitSections(bool NoExecStack) {
  // FIXME: this is identical to the ELF one.
  // This emulates the same behavior of GNU as. This makes it easier
  // to compare the output as the major sections are in the same order.
  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
  EmitCodeAlignment(4);

  SwitchSection(getContext().getObjectFileInfo()->getDataSection());
  EmitCodeAlignment(4);

  SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
  EmitCodeAlignment(4);

  SwitchSection(getContext().getObjectFileInfo()->getTextSection());
}

void MCWinCOFFStreamer::EmitLabel(MCSymbol *S, SMLoc Loc) {
  auto *Symbol = cast<MCSymbolCOFF>(S);
  MCObjectStreamer::EmitLabel(Symbol, Loc);
}

void MCWinCOFFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
  // Let the target do whatever target specific stuff it needs to do.
  getAssembler().getBackend().handleAssemblerFlag(Flag);

  switch (Flag) {
  // None of these require COFF specific handling.
  case MCAF_SyntaxUnified:
  case MCAF_Code16:
  case MCAF_Code32:
  case MCAF_Code64:
    break;
  case MCAF_SubsectionsViaSymbols:
    llvm_unreachable("COFF doesn't support .subsections_via_symbols");
  }
}

void MCWinCOFFStreamer::EmitThumbFunc(MCSymbol *Func) {
  llvm_unreachable("not implemented");
}

bool MCWinCOFFStreamer::EmitSymbolAttribute(MCSymbol *S,
                                            MCSymbolAttr Attribute) {
  auto *Symbol = cast<MCSymbolCOFF>(S);
  getAssembler().registerSymbol(*Symbol);

  switch (Attribute) {
  default: return false;
  case MCSA_WeakReference:
  case MCSA_Weak:
    Symbol->setIsWeakExternal();
    Symbol->setExternal(true);
    break;
  case MCSA_Global:
    Symbol->setExternal(true);
    break;
  case MCSA_AltEntry:
    llvm_unreachable("COFF doesn't support the .alt_entry attribute");
  }

  return true;
}

void MCWinCOFFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  llvm_unreachable("not implemented");
}

void MCWinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *S) {
  auto *Symbol = cast<MCSymbolCOFF>(S);
  if (CurSymbol)
    Error("starting a new symbol definition without completing the "
          "previous one");
  CurSymbol = Symbol;
}

void MCWinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
  if (!CurSymbol) {
    Error("storage class specified outside of symbol definition");
    return;
  }

  if (StorageClass & ~COFF::SSC_Invalid) {
    Error("storage class value '" + Twine(StorageClass) +
               "' out of range");
    return;
  }

  getAssembler().registerSymbol(*CurSymbol);
  cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
}

void MCWinCOFFStreamer::EmitCOFFSymbolType(int Type) {
  if (!CurSymbol) {
    Error("symbol type specified outside of a symbol definition");
    return;
  }

  if (Type & ~0xffff) {
    Error("type value '" + Twine(Type) + "' out of range");
    return;
  }

  getAssembler().registerSymbol(*CurSymbol);
  cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
}

void MCWinCOFFStreamer::EndCOFFSymbolDef() {
  if (!CurSymbol)
    Error("ending symbol definition without starting one");
  CurSymbol = nullptr;
}

void MCWinCOFFStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
  // SafeSEH is a feature specific to 32-bit x86.  It does not exist (and is
  // unnecessary) on all platforms which use table-based exception dispatch.
  if (getContext().getObjectFileInfo()->getTargetTriple().getArch() !=
      Triple::x86)
    return;

  const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
  if (CSymbol->isSafeSEH())
    return;

  MCSection *SXData = getContext().getObjectFileInfo()->getSXDataSection();
  getAssembler().registerSection(*SXData);
  if (SXData->getAlignment() < 4)
    SXData->setAlignment(Align(4));

  new MCSymbolIdFragment(Symbol, SXData);

  getAssembler().registerSymbol(*Symbol);
  CSymbol->setIsSafeSEH();

  // The Microsoft linker requires that the symbol type of a handler be
  // function. Go ahead and oblige it here.
  CSymbol->setType(COFF::IMAGE_SYM_DTYPE_FUNCTION
                   << COFF::SCT_COMPLEX_TYPE_SHIFT);
}

void MCWinCOFFStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
  MCSection *Sec = getCurrentSectionOnly();
  getAssembler().registerSection(*Sec);
  if (Sec->getAlignment() < 4)
    Sec->setAlignment(Align(4));

  new MCSymbolIdFragment(Symbol, getCurrentSectionOnly());

  getAssembler().registerSymbol(*Symbol);
}

void MCWinCOFFStreamer::EmitCOFFSectionIndex(const MCSymbol *Symbol) {
  visitUsedSymbol(*Symbol);
  MCDataFragment *DF = getOrCreateDataFragment();
  const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
  MCFixup Fixup = MCFixup::create(DF->getContents().size(), SRE, FK_SecRel_2);
  DF->getFixups().push_back(Fixup);
  DF->getContents().resize(DF->getContents().size() + 2, 0);
}

void MCWinCOFFStreamer::EmitCOFFSecRel32(const MCSymbol *Symbol,
                                         uint64_t Offset) {
  visitUsedSymbol(*Symbol);
  MCDataFragment *DF = getOrCreateDataFragment();
  // Create Symbol A for the relocation relative reference.
  const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
  // Add the constant offset, if given.
  if (Offset)
    MCE = MCBinaryExpr::createAdd(
        MCE, MCConstantExpr::create(Offset, getContext()), getContext());
  // Build the secrel32 relocation.
  MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_SecRel_4);
  // Record the relocation.
  DF->getFixups().push_back(Fixup);
  // Emit 4 bytes (zeros) to the object file.
  DF->getContents().resize(DF->getContents().size() + 4, 0);
}

void MCWinCOFFStreamer::EmitCOFFImgRel32(const MCSymbol *Symbol,
                                         int64_t Offset) {
  visitUsedSymbol(*Symbol);
  MCDataFragment *DF = getOrCreateDataFragment();
  // Create Symbol A for the relocation relative reference.
  const MCExpr *MCE = MCSymbolRefExpr::create(
      Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, getContext());
  // Add the constant offset, if given.
  if (Offset)
    MCE = MCBinaryExpr::createAdd(
        MCE, MCConstantExpr::create(Offset, getContext()), getContext());
  // Build the imgrel relocation.
  MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_Data_4);
  // Record the relocation.
  DF->getFixups().push_back(Fixup);
  // Emit 4 bytes (zeros) to the object file.
  DF->getContents().resize(DF->getContents().size() + 4, 0);
}

void MCWinCOFFStreamer::EmitCommonSymbol(MCSymbol *S, uint64_t Size,
                                         unsigned ByteAlignment) {
  auto *Symbol = cast<MCSymbolCOFF>(S);

  const Triple &T = getContext().getObjectFileInfo()->getTargetTriple();
  if (T.isWindowsMSVCEnvironment()) {
    if (ByteAlignment > 32)
      report_fatal_error("alignment is limited to 32-bytes");

    // Round size up to alignment so that we will honor the alignment request.
    Size = std::max(Size, static_cast<uint64_t>(ByteAlignment));
  }

  getAssembler().registerSymbol(*Symbol);
  Symbol->setExternal(true);
  Symbol->setCommon(Size, ByteAlignment);

  if (!T.isWindowsMSVCEnvironment() && ByteAlignment > 1) {
    SmallString<128> Directive;
    raw_svector_ostream OS(Directive);
    const MCObjectFileInfo *MFI = getContext().getObjectFileInfo();

    OS << " -aligncomm:\"" << Symbol->getName() << "\","
       << Log2_32_Ceil(ByteAlignment);

    PushSection();
    SwitchSection(MFI->getDrectveSection());
    EmitBytes(Directive);
    PopSection();
  }
}

void MCWinCOFFStreamer::EmitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
                                              unsigned ByteAlignment) {
  auto *Symbol = cast<MCSymbolCOFF>(S);

  MCSection *Section = getContext().getObjectFileInfo()->getBSSSection();
  PushSection();
  SwitchSection(Section);
  EmitValueToAlignment(ByteAlignment, 0, 1, 0);
  EmitLabel(Symbol);
  Symbol->setExternal(false);
  EmitZeros(Size);
  PopSection();
}

void MCWinCOFFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
                                     uint64_t Size, unsigned ByteAlignment,
                                     SMLoc Loc) {
  llvm_unreachable("not implemented");
}

void MCWinCOFFStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
                                       uint64_t Size, unsigned ByteAlignment) {
  llvm_unreachable("not implemented");
}

// TODO: Implement this if you want to emit .comment section in COFF obj files.
void MCWinCOFFStreamer::EmitIdent(StringRef IdentString) {
  llvm_unreachable("not implemented");
}

void MCWinCOFFStreamer::EmitWinEHHandlerData(SMLoc Loc) {
  llvm_unreachable("not implemented");
}

void MCWinCOFFStreamer::FinishImpl() {
  MCObjectStreamer::FinishImpl();
}

void MCWinCOFFStreamer::Error(const Twine &Msg) const {
  getContext().reportError(SMLoc(), Msg);
}


text:
Mouse wheel normalization across multiple multiple browsers.

## Original source
This code is extracted and from Facebook's [Fixed Data Table](https://github.com/facebook/fixed-data-table). Apart from import fixes, the code is unmodified.

## Usage
Just add it as an dependency in npm.

You can use it as follows:

```js
import normalizeWheel from 'normalize-wheel';

document.addEventListener('mousewheel', function (event) {
    const normalized = normalizeWheel(event);

    console.log(normalized.pixelX, normalized.pixelY);
});
```

## License
See the `LICENSE` file.


text:
function c = linewrap(s, maxchars)
%LINEWRAP Separate a single string into multiple strings
%   C = LINEWRAP(S, MAXCHARS) separates a single string into multiple
%   strings by separating the input string, S, on word breaks.  S must be a
%   single-row char array. MAXCHARS is a nonnegative integer scalar
%   specifying the maximum length of the broken string.  C is a cell array
%   of strings.
%
%   C = LINEWRAP(S) is the same as C = LINEWRAP(S, 80).
%
%   Note: Words longer than MAXCHARS are not broken into separate lines.
%   This means that C may contain strings longer than MAXCHARS.
%
%   This implementation was inspired a blog posting about a Java line
%   wrapping function:
%   http://joust.kano.net/weblog/archives/000060.html
%   In particular, the regular expression used here is the one mentioned in
%   Jeremy Stein's comment.
%
%   Example
%       s = 'Image courtesy of Joe and Frank Hardy, MIT, 1993.'
%       c = linewrap(s, 40)
%
%   See also TEXTWRAP.

% Steven L. Eddins
% $Revision: 1.7 $  $Date: 2006/02/08 16:54:51 $

error(nargchk(1, 2, nargin));

bad_s = ~ischar(s) || (ndims(s) > 2) || (size(s, 1) ~= 1);
if bad_s
   error('S must be a single-row char array.');
end

if nargin < 2
   % Default value for second input argument.
   maxchars = 80;
end

% Trim leading and trailing whitespace.
s = strtrim(s);

% Form the desired regular expression from maxchars.
exp = sprintf('(\\S\\S{%d,}|.{1,%d})(?:\\s+|$)', maxchars, maxchars);

% Interpretation of regular expression (for maxchars = 80):
% '(\\S\\S{80,}|.{1,80})(?:\\s+|$)'
%
% Match either a non-whitespace character followed by 80 or more
% non-whitespace characters, OR any sequence of between 1 and 80
% characters; all followed by either one or more whitespace characters OR
% end-of-line.

tokens = regexp(s, exp, 'tokens').';

% Each element if the cell array tokens is single-element cell array
% containing a string.  Convert this to a cell array of strings.
get_contents = @(f) f{1};
c = cellfun(get_contents, tokens, 'UniformOutput', false);

% Remove trailing whitespace characters from strings in c.  This can happen
% if multiple whitespace characters separated the last word on a line from
% the first word on the following line.
c = deblank(c);


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        metafile.h
// Purpose:     wxMetaFile, wxMetaFileDC classes.
//              This probably should be restricted to Windows platforms,
//              but if there is an equivalent on your platform, great.
// Author:      Stefan Csomor
// Modified by:
// Created:     1998-01-01
// RCS-ID:      $Id: metafile.h,v 1.6 2005/08/19 13:48:20 MW Exp $
// Copyright:   (c) Stefan Csomor
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_METAFIILE_H_
#define _WX_METAFIILE_H_

#include "wx/dc.h"
#include "wx/gdiobj.h"

#if wxUSE_DATAOBJ
#include "wx/dataobj.h"
#endif

/*
 * Metafile and metafile device context classes
 *
 */

#define wxMetaFile wxMetafile
#define wxMetaFileDC wxMetafileDC

class WXDLLEXPORT wxMetafile;
class wxMetafileRefData ;

#define M_METAFILEDATA ((wxMetafileRefData *)m_refData)

class WXDLLEXPORT wxMetafile: public wxGDIObject
{
    DECLARE_DYNAMIC_CLASS(wxMetafile)
public:
    // Copy constructor
    wxMetafile(const wxMetafile& metafile)
      : wxGDIObject()
    { Ref(metafile); }

    wxMetafile(const wxString& file = wxEmptyString);
    ~wxMetafile(void);

    // After this is called, the metafile cannot be used for anything
    // since it is now owned by the clipboard.
    virtual bool SetClipboard(int width = 0, int height = 0);

    virtual bool Play(wxDC *dc);
    bool Ok() const ;

    wxSize GetSize() const;
    int GetWidth() const { return GetSize().x; }
    int GetHeight() const { return GetSize().y; }

    // Implementation
    WXHMETAFILE GetHMETAFILE() const ;
    void SetHMETAFILE(WXHMETAFILE mf) ;

    // Operators
    inline wxMetafile& operator = (const wxMetafile& metafile) { if (*this == metafile) return (*this); Ref(metafile); return *this; }
    inline bool operator == (const wxMetafile& metafile) { return m_refData == metafile.m_refData; }
    inline bool operator != (const wxMetafile& metafile) { return m_refData != metafile.m_refData; }

protected:
};

class WXDLLEXPORT wxMetafileDC: public wxDC
{
  DECLARE_DYNAMIC_CLASS(wxMetafileDC)

 public:
    // the ctor parameters specify the filename (empty for memory metafiles),
    // the metafile picture size and the optional description/comment
    wxMetafileDC(const wxString& filename = wxEmptyString,
                    int width = 0, int height = 0,
                    const wxString& description = wxEmptyString);

  ~wxMetafileDC(void);

  // Should be called at end of drawing
  virtual wxMetafile *Close(void);
  virtual void DoGetSize(int *width, int *height) const ;

  // Implementation
  inline wxMetafile *GetMetaFile(void) const { return m_metaFile; }
  inline void SetMetaFile(wxMetafile *mf) { m_metaFile = mf; }

protected:
  wxMetafile*   m_metaFile;
};

/*
 * Pass filename of existing non-placeable metafile, and bounding box.
 * Adds a placeable metafile header, sets the mapping mode to anisotropic,
 * and sets the window origin and extent to mimic the wxMM_TEXT mapping mode.
 *
 */

// No origin or extent
#define wxMakeMetaFilePlaceable wxMakeMetafilePlaceable
bool WXDLLEXPORT wxMakeMetafilePlaceable(const wxString& filename, float scale = 1.0);

// Optional origin and extent
bool WXDLLEXPORT wxMakeMetaFilePlaceable(const wxString& filename, int x1, int y1, int x2, int y2, float scale = 1.0, bool useOriginAndExtent = TRUE);

// ----------------------------------------------------------------------------
// wxMetafileDataObject is a specialization of wxDataObject for metafile data
// ----------------------------------------------------------------------------

#if wxUSE_DATAOBJ
class WXDLLEXPORT wxMetafileDataObject : public wxDataObjectSimple
{
public:
  // ctors
  wxMetafileDataObject()
    : wxDataObjectSimple(wxDF_METAFILE) {  };
  wxMetafileDataObject(const wxMetafile& metafile)
    : wxDataObjectSimple(wxDF_METAFILE), m_metafile(metafile) { }

    // virtual functions which you may override if you want to provide data on
    // demand only - otherwise, the trivial default versions will be used
    virtual void SetMetafile(const wxMetafile& metafile)
        { m_metafile = metafile; }
    virtual wxMetafile GetMetafile() const
        { return m_metafile; }

    // implement base class pure virtuals
    virtual size_t GetDataSize() const;
    virtual bool GetDataHere(void *buf) const;
    virtual bool SetData(size_t len, const void *buf);

    virtual size_t GetDataSize(const wxDataFormat& WXUNUSED(format)) const
        { return GetDataSize(); }
    virtual bool GetDataHere(const wxDataFormat& WXUNUSED(format),
                             void *buf) const
        { return GetDataHere(buf); }
    virtual bool SetData(const wxDataFormat& WXUNUSED(format),
                         size_t len, const void *buf)
        { return SetData(len, buf); }
protected:
  wxMetafile   m_metafile;
};
#endif

#endif
    // _WX_METAFIILE_H_