text:
CGFloat const MRTableBuilderDefaultRowHeight = 44.0;

@interface MRTableBuilder ()

@property (weak, nonatomic, readwrite) UITableView* tableView;

@end

@implementation MRTableBuilder

#pragma mark - NSObject

- (instancetype)init
{
	if (self = [super init]) {
		_sections = [NSMutableArray array];
	}
	return self;
}

- (void)dealloc
{
	self.tableView.delegate = nil;
	self.tableView.dataSource = nil;
}

//Only say YES to some selectors if set explicitly or at least one section or row has a value set
- (BOOL)respondsToSelector:(SEL)aSelector
{
	[self enumerateSectionsUsingBlock:^(MRTableSection* section, BOOL* stop) {
		self.useEstimatedHeaderHeights |= section.header.estimatedHeight > 0;
		self.useEstimatedFooterHeights |= section.footer.estimatedHeight > 0;
		self.useHeaderViews |= section.header != nil;
		self.useFooterViews |= section.footer != nil;
		self.useHeaderHeights |= section.header.height || section.headerHeight;
		self.useFooterHeights |= section.footer.height || section.footerHeight;
	}];

	[self enumerateRowsUsingBlock:^(MRTableSection* section, MRTableRow* row, BOOL* stop) {
		self.hasTitlesForDeleteConfirmationButtons |= row.titleForDeleteConfirmationButton != nil;
		self.useEditActions |= row.editActions != nil;
		self.useHighlights |= row.shouldHighlight != nil;
		self.useIndents |= row.shouldIndentWhileEditing != nil;
		self.useEditRows |= row.canEdit != nil;
		self.useMoveRows |= row.canMove != nil;
		self.useMenus |= row.shouldShowMenu != nil;
		self.useEditingStyles |= row.editingStyle != nil;
		self.useIndentationLevels |= row.indentationLevel != nil;
	}];

	if (aSelector == @selector(tableView:estimatedHeightForHeaderInSection:)) {
		return self.useEstimatedHeaderHeights;
	}
	if (aSelector == @selector(tableView:estimatedHeightForFooterInSection:)) {
		return self.useEstimatedFooterHeights;
	}
	if (aSelector == @selector(tableView:viewForHeaderInSection:)) {
		return self.useHeaderViews;
	}
	if (aSelector == @selector(tableView:viewForFooterInSection:)) {
		return self.useFooterViews;
	}
	if (aSelector == @selector(tableView:heightForHeaderInSection:)) {
		return self.useHeaderHeights;
	}
	if (aSelector == @selector(tableView:heightForFooterInSection:)) {
		return self.useFooterHeights;
	}
	if (aSelector == @selector(tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:)) {
		return self.hasTitlesForDeleteConfirmationButtons;
	}
	if (aSelector == @selector(tableView:editActionsForRowAtIndexPath:)) {
		return self.useEditActions;
	}
	if (aSelector == @selector(tableView:shouldHighlightRowAtIndexPath:)) {
		return self.useHighlights;
	}
	if (aSelector == @selector(tableView:shouldIndentWhileEditingRowAtIndexPath:)) {
		return self.useIndents;
	}
	if (aSelector == @selector(tableView:canEditRowAtIndexPath:)) {
		return self.useEditRows;
	}
	if (aSelector == @selector(tableView:canMoveRowAtIndexPath:)) {
		return self.useMoveRows;
	}
	if (aSelector == @selector(tableView:commitEditingStyle:forRowAtIndexPath:)) {
		return self.useEditingStyles;
	}
	if (aSelector == @selector(tableView:moveRowAtIndexPath:toIndexPath:)) {
		return self.useMoveRows;
	}
	if (aSelector == @selector(tableView:shouldShowMenuForRowAtIndexPath:)) {
		return self.useMenus;
	}
	if (aSelector == @selector(tableView:editingStyleForRowAtIndexPath:)) {
		return self.useEditingStyles;
	}
	if (aSelector == @selector(tableView:indentationLevelForRowAtIndexPath:)) {
		return self.useIndentationLevels;
	}
	return [super respondsToSelector:aSelector];
}

#pragma mark - Public

- (void)bindToTableView:(UITableView*)tableView
{
	//Clear out the old datasource and delegate
	tableView.dataSource = nil;
	tableView.delegate = nil;

	//Prevent tableView:didEndDisplayingCell:forRowAtIndexPath from being called on previous cells
	[tableView reloadData];

	//Set self as the new datasource and delegate
	_tableView = tableView;
	tableView.dataSource = self;
	tableView.delegate = self;

	//Register custom headers and footers
	[self enumerateSectionsUsingBlock:^(MRTableSection* section, BOOL* stop) {
		[self registerSection:section];
	}];

	//Register custom cells
	[self enumerateRowsUsingBlock:^(MRTableSection* section, MRTableRow* row, BOOL* stop) {
		[self registerRow:row];
	}];

	//Trigger a reload of the table
	[tableView reloadData];
}

- (MRTableSection*)sectionAtIndex:(NSUInteger)index
{
	//Safety check
	if (index < self.sections.count) {
		return self.sections[index];
	}
	return nil;
}

- (MRTableSection*)sectionAtIndexPath:(NSIndexPath*)indexPath
{
	return [self sectionAtIndex:indexPath.section];
}

- (void)reloadSection:(MRTableSection*)section
{
	[self reloadSection:section withAnimation:UITableViewRowAnimationNone];
}

- (void)reloadSection:(MRTableSection*)section withAnimation:(UITableViewRowAnimation)animation
{
	[self registerSection:section];
	NSUInteger index = [self.sections indexOfObject:section];
	NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:index];
	[self.tableView reloadSections:indexSet withRowAnimation:animation];
}

- (void)reloadSections:(NSArray*)sections
{
	[self reloadSections:sections withAnimation:UITableViewRowAnimationNone];
}

- (void)reloadSections:(NSArray*)sections withAnimation:(UITableViewRowAnimation)animation
{
	NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
	for (MRTableSection* section in sections) {
		[self registerSection:section];
		NSUInteger index = [self.sections indexOfObject:section];
		[indexSet addIndex:index];
	}
	[self.tableView reloadSections:indexSet withRowAnimation:animation];
}

- (void)addSection:(MRTableSection*)section
{
	NSInteger index = self.sections.count;
	[self insertSection:section atIndex:index];
}

- (void)addSection:(MRTableSection*)section withAnimation:(UITableViewRowAnimation)animation
{
	NSInteger index = self.sections.count;
	[self insertSection:section atIndex:index withAnimation:animation];
}

- (void)insertSection:(MRTableSection*)section atIndex:(NSUInteger)index
{
	section.tableBuilder = self;
	[self registerSection:section];
	[self.sections insertObject:section atIndex:index];
}

- (void)insertSection:(MRTableSection*)section aboveSection:(MRTableSection*)aboveSection
{
	NSInteger index = [self.sections indexOfObject:aboveSection];
	[self insertSection:section atIndex:index];
}

- (void)insertSection:(MRTableSection*)section belowSection:(MRTableSection*)belowSection
{
	NSInteger index = [self.sections indexOfObject:belowSection] + 1;
	[self insertSection:section atIndex:index];
}

- (void)insertSections:(NSArray*)sections belowSection:(MRTableSection*)belowSection
{
	MRTableSection* topSection = belowSection;
	for (MRTableSection* section in sections) {
		[self insertSection:section belowSection:topSection];
		topSection = section;
	};
}

- (void)insertSections:(NSArray*)sections aboveSection:(MRTableSection*)aboveSection
{
	for (MRTableSection* section in sections) {
		[self insertSection:section aboveSection:aboveSection];
	};
}

- (void)insertSection:(MRTableSection*)section atIndex:(NSUInteger)index withAnimation:(UITableViewRowAnimation)animation
{
	[self.tableView beginUpdates];
	[self insertSection:section atIndex:index];
	NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:index];
	[self.tableView insertSections:indexSet withRowAnimation:animation];
	[self.tableView endUpdates];
}

- (void)insertSection:(MRTableSection*)section aboveSection:(MRTableSection*)aboveSection withAnimation:(UITableViewRowAnimation)animation
{
	NSInteger index = [self.sections indexOfObject:aboveSection];
	[self insertSection:section atIndex:index withAnimation:animation];
}

- (void)insertSection:(MRTableSection*)section belowSection:(MRTableSection*)belowSection withAnimation:(UITableViewRowAnimation)animation
{
	NSInteger index = [self.sections indexOfObject:belowSection] + 1;
	[self insertSection:section atIndex:index withAnimation:animation];
}

- (void)insertSections:(NSArray*)sections belowSection:(MRTableSection*)belowSection withAnimation:(UITableViewRowAnimation)animation
{
	[self.tableView beginUpdates];
	[self insertSections:sections belowSection:belowSection];
	[self.tableView insertSections:[self indexSetForSections:sections] withRowAnimation:animation];
	[self.tableView endUpdates];
}

- (void)insertSections:(NSArray*)sections aboveSection:(MRTableSection*)aboveSection withAnimation:(UITableViewRowAnimation)animation
{
	[self.tableView beginUpdates];
	[self insertSections:sections aboveSection:aboveSection];
	[self.tableView insertSections:[self indexSetForSections:sections] withRowAnimation:animation];
	[self.tableView endUpdates];
}

- (void)removeSection:(MRTableSection*)section
{
	[self.sections removeObject:section];
}

- (void)removeSection:(MRTableSection*)section withAnimation:(UITableViewRowAnimation)animation
{
	[self.tableView beginUpdates];
	NSUInteger index = [self.sections indexOfObject:section];
	[self.sections removeObject:section];
	NSIndexSet* indexSet = [NSIndexSet indexSetWithIndex:index];
	[self.tableView deleteSections:indexSet withRowAnimation:animation];
	[self.tableView endUpdates];
}

- (void)clear
{
	[self.sections removeAllObjects];
}

- (NSIndexPath*)indexPathForRow:(MRTableRow*)aRow
{
	for (int i = 0; i < self.sections.count; i++) {
		MRTableSection* section = self.sections[i];
		for (int j = 0; j < section.rows.count; j++) {
			MRTableRow* row = section.rows[j];
			if (row == aRow) {
				return [NSIndexPath indexPathForRow:j inSection:i];;
			}
		}
	}
	return nil;
}

- (BOOL)isSectionVisible:(MRTableSection*)section
{
	NSInteger index = [self.sections indexOfObject:section];
	CGRect visibleRect = CGRectMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y, self.tableView.bounds.size.width, self.tableView.bounds.size.height);
	CGRect sectionRect = [self.tableView rectForSection:index];
	return CGRectIntersectsRect(visibleRect, sectionRect);
}

- (BOOL)isRowVisible:(MRTableRow*)row
{
	NSIndexPath* indexPath = [self indexPathForRow:row];
	return [[self.tableView indexPathsForVisibleRows] containsObject:indexPath];
}

- (void)reloadRow:(MRTableRow*)row
{
	[self reloadRow:row withAnimation:UITableViewRowAnimationAutomatic];
}

- (void)reloadRow:(MRTableRow*)row withAnimation:(UITableViewRowAnimation)animation
{
	NSIndexPath* indexPath = [self indexPathForRow:row];
	if (indexPath) {
		[self.tableView reloadRowsAtIndexPaths:@[ indexPath ] withRowAnimation:animation];
	}
}

- (void)reloadRows:(NSArray*)rows
{
	[self reloadRows:rows withAnimation:UITableViewRowAnimationAutomatic];
}

- (void)reloadRows:(NSArray*)rows withAnimation:(UITableViewRowAnimation)animation
{
	NSMutableArray* indexPaths = [NSMutableArray array];
	for (MRTableRow* row in rows) {
		NSIndexPath* indexPath = [self indexPathForRow:row];
		if (indexPath) {
			[indexPaths addObject:indexPath];
		}
	}
	[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:animation];
}

- (void)scrollToRow:(MRTableRow*)row
{
	[self scrollToRow:row atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (void)scrollToRow:(MRTableRow*)row atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated
{
	NSIndexPath* indexPath = [self indexPathForRow:row];
	[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES];
}

- (id)cellForRow:(MRTableRow*)row
{
	if (!row) {
		return nil;
	}

	NSIndexPath* indexPath = [self indexPathForRow:row];
	if (!indexPath) {
		return nil;
	}

	UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
	if (!cell) {
		cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
	}

	return cell;
}

- (void)registerRow:(MRTableRow*)row
{
	if (row.cellNib) {
		[self.tableView registerNib:row.cellNib forCellReuseIdentifier:row.reuseIdentifier];
		return;
	} else {
		[self.tableView registerClass:row.cellClass forCellReuseIdentifier:row.reuseIdentifier];
	}
}

- (void)registerSection:(MRTableSection*)section
{
	if (section.header) {
		if (section.header.viewNib) {
			[self.tableView registerNib:section.header.viewNib forHeaderFooterViewReuseIdentifier:section.header.reuseIdentifier];
		} else {
			[self.tableView registerClass:section.header.viewClass forHeaderFooterViewReuseIdentifier:section.header.reuseIdentifier];
		}
	}
	if (section.footer) {
		if (section.footer.viewNib) {
			[self.tableView registerNib:section.footer.viewNib forHeaderFooterViewReuseIdentifier:section.footer.reuseIdentifier];
		} else {
			[self.tableView registerClass:section.footer.viewClass forHeaderFooterViewReuseIdentifier:section.footer.reuseIdentifier];
		}
	}
	for (MRTableRow* row in section.rows) {
		[self registerRow:row];
	}
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView numberOfRowsInSection:section];
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView cellForRowAtIndexPath:indexPath];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return self.sections.count;
}

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView titleForHeaderInSection:section];
}

- (NSString*)tableView:(UITableView*)tableView titleForFooterInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView titleForFooterInSection:section];
}

- (BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView canEditRowAtIndexPath:indexPath];
}

- (BOOL)tableView:(UITableView*)tableView canMoveRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView canMoveRowAtIndexPath:indexPath];
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
	return self.sectionIndexTitles;
}

- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index
{
	if (self.sectionForSectionIndex) {
		return self.sectionForSectionIndex(title, index);
	}
	return 0;
}

- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
	if (self.onMoveRow) {
		self.onMoveRow(sourceIndexPath, destinationIndexPath);
	}

	MRTableSection* sourceSection = [self sectionAtIndexPath:sourceIndexPath];
	MRTableSection* destinationSection = [self sectionAtIndexPath:destinationIndexPath];
	MRTableRow* row = [sourceSection rowAtIndexPath:sourceIndexPath];
	[sourceSection.rows removeObject:row];
	[destinationSection.rows insertObject:row atIndex:destinationIndexPath.row];
}

#pragma mark - UITableViewDelegate

// Display customization

- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView willDisplayHeaderView:(UIView*)view forSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	[formSection tableView:tableView willDisplayHeaderView:view forSection:section];
}

- (void)tableView:(UITableView*)tableView willDisplayFooterView:(UIView*)view forSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	[formSection tableView:tableView willDisplayFooterView:view forSection:section];
}

- (void)tableView:(UITableView*)tableView didEndDisplayingCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didEndDisplayingCell:cell forRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView didEndDisplayingHeaderView:(UIView*)view forSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	[formSection tableView:tableView didEndDisplayingHeaderView:view forSection:section];
}

- (void)tableView:(UITableView*)tableView didEndDisplayingFooterView:(UIView*)view forSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	[formSection tableView:tableView didEndDisplayingFooterView:view forSection:section];
}

// Variable height support

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView heightForHeaderInSection:section];
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView heightForFooterInSection:section];
}

// Use the estimatedHeight methods to quickly calcuate guessed values which will allow for fast load times of the table.
// If these methods are implemented, the above -tableView:heightForXXX calls will be deferred until views are ready to be displayed, so more expensive logic can be placed there.
- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView estimatedHeightForRowAtIndexPath:indexPath];
}

- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView estimatedHeightForHeaderInSection:section];
}

- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForFooterInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView estimatedHeightForFooterInSection:section];
}

// Section header & footer information. Views are preferred over title should you decide to provide both

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView viewForHeaderInSection:section];
}

- (UIView*)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
	MRTableSection* formSection = [self sectionAtIndex:section];
	return [formSection tableView:tableView viewForFooterInSection:section];
}

// Accessories (disclosures).

- (void)tableView:(UITableView*)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}

// Selection

// -tableView:shouldHighlightRowAtIndexPath: is called when a touch comes down on a row.
// Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.

- (BOOL)tableView:(UITableView*)tableView shouldHighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView shouldHighlightRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView didHighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didHighlightRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView didUnhighlightRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didUnhighlightRowAtIndexPath:indexPath];
}

// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
- (NSIndexPath*)tableView:(UITableView*)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView willSelectRowAtIndexPath:indexPath];
}

- (NSIndexPath*)tableView:(UITableView*)tableView willDeselectRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView willDeselectRowAtIndexPath:indexPath];
}

// Called after the user changes the selection.
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didSelectRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView didDeselectRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didDeselectRowAtIndexPath:indexPath];
}

// Editing

// Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView editingStyleForRowAtIndexPath:indexPath];
}

- (NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView titleForDeleteConfirmationButtonForRowAtIndexPath:indexPath];
}

// supercedes -tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: if return value is non-nil
- (NSArray*)tableView:(UITableView*)tableView editActionsForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView editActionsForRowAtIndexPath:indexPath];
}

// Controls whether the background is indented while editing.  If not implemented, the default is YES.  This is unrelated to the indentation level below.  This method only applies to grouped style table views.
- (BOOL)tableView:(UITableView*)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView shouldIndentWhileEditingRowAtIndexPath:indexPath];
}

// The willBegin/didEnd methods are called whenever the 'editing' property is automatically changed by the table (allowing insert/delete/move). This is done by a swipe activating a single row
- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView willBeginEditingRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView didEndEditingRowAtIndexPath:indexPath];
}

// Moving/reordering

// Allows customization of the target row for a particular row as it is being moved/reordered
- (NSIndexPath*)tableView:(UITableView*)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath*)sourceIndexPath toProposedIndexPath:(NSIndexPath*)proposedDestinationIndexPath
{
	if (self.targetIndexPathForMove) {
		return self.targetIndexPathForMove(sourceIndexPath, proposedDestinationIndexPath);
	}
	return proposedDestinationIndexPath;
}

// Indentation

// return 'depth' of row for hierarchies
- (NSInteger)tableView:(UITableView*)tableView indentationLevelForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
}

// Copy/Paste.  All three methods must be implemented by the delegate.

- (BOOL)tableView:(UITableView*)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath*)indexPath
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView shouldShowMenuForRowAtIndexPath:indexPath];
}

- (BOOL)tableView:(UITableView*)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	return [formSection tableView:tableView canPerformAction:action forRowAtIndexPath:indexPath withSender:sender];
}

- (void)tableView:(UITableView*)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath*)indexPath withSender:(id)sender
{
	MRTableSection* formSection = [self sectionAtIndexPath:indexPath];
	[formSection tableView:tableView performAction:action forRowAtIndexPath:indexPath withSender:sender];
}

#pragma mark - Private

- (void)enumerateSectionsUsingBlock:(void (^)(MRTableSection* section, BOOL* stop))block
{
	for (int i = 0; i < self.sections.count; i++) {
		MRTableSection* section = self.sections[i];
		if (block) {
			BOOL stop = NO;
			block(section, &stop);
			if (stop) {
				break;
			}
		}
	}
}

- (void)enumerateRowsUsingBlock:(void (^)(MRTableSection* section, MRTableRow* row, BOOL* stop))block
{
	for (int i = 0; i < self.sections.count; i++) {
		MRTableSection* section = self.sections[i];
		for (int j = 0; j < section.rows.count; j++) {
			MRTableRow* row = section.rows[j];
			if (block) {
				BOOL stop = NO;
				block(section, row, &stop);
				if (stop) {
					break;
				}
			}
		}
	}
}

- (NSIndexSet*)indexSetForSections:(NSArray*)sections
{
	NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
	[sections enumerateObjectsUsingBlock:^(id section, NSUInteger index, BOOL* stop) {
		[indexSet addIndex:[self.sections indexOfObject:section]];
	}];
	return [indexSet copy];
}

@end


text:
MIT LICENSE

Ngx boot Loading is repository of Pre Bootstrap Angular 2 css animation on initial Angular 2 Web apps loading.
The source of each animation css and html source is available at /lib folder each folder is a Pre Bootstrap loading page! make sure to check the demo

# Demo
First Loading Animation library Bubble-up
https://adenovan.github.io/ngx-bootloading/lib/bubble-up

Line Grow
https://adenovan.github.io/ngx-bootloading/lib/line-grow

More to come

# Usage

put the library template's css on assets folder and don't forget to include the template css on index.html head!

```bash
  <link rel="stylesheet" href="assets/bootloading.min.css">
```

copy html inside body tag on library template lib/folder/index.html and paste on your app-root tag

```bash
<app-root>
    <div class="bootloading-wrapper">
      <img src="assets/logo.png" alt="" class="bootloading-logo">
      <h1 class="bootloading-title">Company Name</h1>
      <div class="bootloading-bubble-wrapper ">
        <div class="dot-1"></div>
        <div class="dot-2"></div>
        <div class="dot-3"></div>
        <div class="dot-4"></div>
        <div class="dot-5"></div>
      </div>
    </div>
</app-root>
```

# Example
Demo of Angular 2 App use this loading
https://adenovan.github.io/ngx-bootloading

Example Angular 2 project with this initial custom loading animation available at /src folder and was generated with [Angular CLI] (https://github.com/angular/angular-cli) version 1.0.1.

# Contribution

Create a folder in lib/ directory with your Pre Bootstrap loading code,
bubble up is good example using only static css animation and html as a template, make it slim its need to load faster than the Angular 2 App bootstrap!

redpajama_set_name: RedPajamaGithub


text:
Doge4commit
==========

[![dogecoin tip for next commit](http://dog4commit.com/projects/1.svg)](http://dog4commit.com/projects/1)
[![bitcoin tip for next commit](http://tip4commit.com/projects/685.svg)](http://tip4commit.com/projects/685)

Donate dogecoins to open source projects or make commits and get tips for it.

Official site: http://dog4commit.com/

License
=======

[MIT License](https://github.com/arowser/dog4commit/blob/master/LICENSE)

Based on [Tip4commit](http://tip4commit.com/), [MIT License](https://github.com/tip4commit/tip4commit/blob/master/LICENSE), copyright (c) 2013-2014 tip4commit


text:
using System;

class HexadecimalToDecimal
{
    static void Main()
    {
        /*
         *  Problem 15: Hexadecimal to Decimal Number
         *
         *  - Using loops write a program that converts a hexadecimal integer number to its decimal form.
         *
         *  - The input is entered as string. The output should be a variable of type long.
         *
         *  - Do not use the built-in .NET functionality.
         *
         * */

        Console.Title = "Hexadecimal to Decimal";
        Console.WriteLine("The program converts a hexadecimal integer number to its decimal form.\n");

        Console.WriteLine("Enter the hexadecimal number:");
        string input = Console.ReadLine();
        Console.WriteLine();

        int lenght = (input.Length) - 1;
        int power = lenght;
        long result = 0;
        long sum = 0;
        int pos;

        Console.WriteLine("Hex number: {0}", input);

        for (int i = 0; i <= lenght; i++)
        {
            pos = input[i];

            switch (input[i])
            {
                case '0': pos = 0; break;
                case '1': pos = 1; break;
                case '2': pos = 2; break;
                case '3': pos = 3; break;
                case '4': pos = 4; break;
                case '5': pos = 5; break;
                case '6': pos = 6; break;
                case '7': pos = 7; break;
                case '8': pos = 8; break;
                case '9': pos = 9; break;
                case 'A': pos = 10; break;
                case 'a': pos = 10; break;
                case 'B': pos = 11; break;
                case 'b': pos = 11; break;
                case 'C': pos = 12; break;
                case 'c': pos = 12; break;
                case 'D': pos = 13; break;
                case 'd': pos = 13; break;
                case 'E': pos = 14; break;
                case 'e': pos = 14; break;
                case 'F': pos = 15; break;
                case 'f': pos = 15; break;

                default:
                    Console.WriteLine();
                    Console.WriteLine("Invalid input!\n");
                    Environment.Exit(0);
                    break;
            }

            result = pos * ((long)(Math.Pow(16, power)));
            sum = sum + result;
            power--;
        }

        Console.WriteLine("Dec number: {0}", sum);
        Console.WriteLine();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.appplatform.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.appplatform.models.DiagnosticParameters;

/** Samples for Deployments GenerateThreadDump. */
public final class DeploymentsGenerateThreadDumpSamples {
    /*
     * x-ms-original-file: specification/appplatform/resource-manager/Microsoft.AppPlatform/stable/2022-04-01/examples/Deployments_GenerateThreadDump.json
     */
    /**
     * Sample code: Deployments_GenerateHeapDump.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void deploymentsGenerateHeapDump(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .springServices()
            .manager()
            .serviceClient()
            .getDeployments()
            .generateThreadDump(
                "myResourceGroup",
                "myservice",
                "myapp",
                "mydeployment",
                new DiagnosticParameters().withAppInstance("myappinstance").withFilePath("/byos/diagnose"),
                Context.NONE);
    }
}


text:
import initialState from '../static/state.js';
const time = (state = initialState, action) => {
    switch (action.type) {
        case 'TIME_TICK':
          return Date.now();
        default:
            return state;
    }
};

export default time;


text:
import 'bootstrap-sass/assets/javascripts/bootstrap/transition.js';
import 'bootstrap-sass/assets/javascripts/bootstrap/alert.js';
import 'bootstrap-sass/assets/javascripts/bootstrap/collapse.js';
import 'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js';
import 'bootstrap-sass/assets/javascripts/bootstrap/modal.js';
import 'jquery'

// loads the code syntax highlighting library
import './highlight.js';

// Creates links to the Symfony documentation
import './doclinks.js';


text:
package io.reactivex;

import java.util.concurrent.*;

import org.openjdk.jmh.infra.Blackhole;
import org.reactivestreams.*;

import io.reactivex.disposables.Disposable;

/**
 * A multi-type asynchronous consumer.
 */
public final class PerfAsyncConsumer extends CountDownLatch implements Subscriber<Object>, Observer<Object>,
SingleObserver<Object>, CompletableObserver, MaybeObserver<Object> {

    final Blackhole bh;

    public PerfAsyncConsumer(Blackhole bh) {
        super(1);
        this.bh = bh;
    }

    @Override
    public void onSuccess(Object value) {
        bh.consume(value);
        countDown();
    }

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE);
    }

    @Override
    public void onNext(Object t) {
        bh.consume(t);
    }

    @Override
    public void onError(Throwable t) {
        t.printStackTrace();
        countDown();
    }

    @Override
    public void onComplete() {
        bh.consume(true);
        countDown();
    }

    /**
     * Wait for the terminal signal.
     * @param count if less than 1001, a spin-wait is used
     */
    public void await(int count) {
        if (count <= 1000) {
            while (getCount() != 0) { }
        } else {
            try {
                await();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

}


text:
var express = require('express');
var router = express.Router();
var Pubsub = require('../lib/eventchannel');
var Sensor = require('../models/sensor');

router.get('/', function(req, res) {
    res.send({
        success: true
    });
});

// router.get('/devices', function(req, res){});

//var unitTimestamp = Math.round((new Date()).getTime() / 1000);
//curl -H "Content-Type: application/json" -d '{"uuid":"xyz","t":30, "h":40, "tmp":1423761255422}' http://localhost:3000/sensor/collect
router.post('/collect', function(req, res){
    // console.log('COLLECT', req.body);
    //THIS IS A JOKE :)
    Pubsub.emit('live-tracker', req.body);
    // router.app.server.io.sockets.in('live-tracker').emit('kaka', req.body);
    if(req.body) Sensor.create(req.body);

    res.send({
        status: true
    });
});

module.exports = function register(app) {
    app.use('/sensor', router);
    router.app = app;
};


text:
<?php
/**
 * Concrete subclass of  Noumenal_Acl_FacadeAbstract
 *
 * Defines guest, user, admin, and system roles most commonly needed.
 *
 * Usage in Model class or Controller implementing
 * Noumenal_Acl_ResourceInterface:
 *
 *     $acl = new Noumenal_Acl;
 *     $acl->isAllowed($this, null);
 *
 * ('null' implies all priviledges as per Zend_Acl)
 */
class Noumenal_Acl extends Noumenal_Acl_FacadeAbstract
{
	protected $_roles = array(
		'guest' => null,
		'user'  => 'guest',
		'admin' => 'user',
		'system'=> 'admin'
	);
}


text:
import collections
from functools import partial
import string

import numpy as np
import pytest

import pandas as pd
from pandas import Series
import pandas._testing as tm
from pandas.core import ops
import pandas.core.common as com
from pandas.util.version import Version

def test_get_callable_name():
    getname = com.get_callable_name

    def fn(x):
        return x

    lambda_ = lambda x: x
    part1 = partial(fn)
    part2 = partial(part1)

    class somecall:
        def __call__(self):
            # This shouldn't actually get called below; somecall.__init__
            #  should.
            raise NotImplementedError

    assert getname(fn) == "fn"
    assert getname(lambda_)
    assert getname(part1) == "fn"
    assert getname(part2) == "fn"
    assert getname(somecall()) == "somecall"
    assert getname(1) is None

def test_any_none():
    assert com.any_none(1, 2, 3, None)
    assert not com.any_none(1, 2, 3, 4)

def test_all_not_none():
    assert com.all_not_none(1, 2, 3, 4)
    assert not com.all_not_none(1, 2, 3, None)
    assert not com.all_not_none(None, None, None, None)

def test_random_state():
    import numpy.random as npr

    # Check with seed
    state = com.random_state(5)
    assert state.uniform() == npr.RandomState(5).uniform()

    # Check with random state object
    state2 = npr.RandomState(10)
    assert com.random_state(state2).uniform() == npr.RandomState(10).uniform()

    # check with no arg random state
    assert com.random_state() is np.random

    # check array-like
    # GH32503
    state_arr_like = npr.randint(0, 2**31, size=624, dtype="uint32")
    assert (
        com.random_state(state_arr_like).uniform()
        == npr.RandomState(state_arr_like).uniform()
    )

    # Check BitGenerators
    # GH32503
    assert (
        com.random_state(npr.MT19937(3)).uniform()
        == npr.RandomState(npr.MT19937(3)).uniform()
    )
    assert (
        com.random_state(npr.PCG64(11)).uniform()
        == npr.RandomState(npr.PCG64(11)).uniform()
    )

    # Error for floats or strings
    msg = (
        "random_state must be an integer, array-like, a BitGenerator, Generator, "
        "a numpy RandomState, or None"
    )
    with pytest.raises(ValueError, match=msg):
        com.random_state("test")

    with pytest.raises(ValueError, match=msg):
        com.random_state(5.5)

@pytest.mark.parametrize(
    "left, right, expected",
    [
        (Series([1], name="x"), Series([2], name="x"), "x"),
        (Series([1], name="x"), Series([2], name="y"), None),
        (Series([1]), Series([2], name="x"), None),
        (Series([1], name="x"), Series([2]), None),
        (Series([1], name="x"), [2], "x"),
        ([1], Series([2], name="y"), "y"),
        # matching NAs
        (Series([1], name=np.nan), pd.Index([], name=np.nan), np.nan),
        (Series([1], name=np.nan), pd.Index([], name=pd.NaT), None),
        (Series([1], name=pd.NA), pd.Index([], name=pd.NA), pd.NA),
        # tuple name GH#39757
        (
            Series([1], name=np.int64(1)),
            pd.Index([], name=(np.int64(1), np.int64(2))),
            None,
        ),
        (
            Series([1], name=(np.int64(1), np.int64(2))),
            pd.Index([], name=(np.int64(1), np.int64(2))),
            (np.int64(1), np.int64(2)),
        ),
        pytest.param(
            Series([1], name=(np.float64("nan"), np.int64(2))),
            pd.Index([], name=(np.float64("nan"), np.int64(2))),
            (np.float64("nan"), np.int64(2)),
            marks=pytest.mark.xfail(
                reason="Not checking for matching NAs inside tuples."
            ),
        ),
    ],
)
def test_maybe_match_name(left, right, expected):
    res = ops.common._maybe_match_name(left, right)
    assert res is expected or res == expected

def test_standardize_mapping():
    # No uninitialized defaultdicts
    msg = r"to_dict\(\) only accepts initialized defaultdicts"
    with pytest.raises(TypeError, match=msg):
        com.standardize_mapping(collections.defaultdict)

    # No non-mapping subtypes, instance
    msg = "unsupported type: <class 'list'>"
    with pytest.raises(TypeError, match=msg):
        com.standardize_mapping([])

    # No non-mapping subtypes, class
    with pytest.raises(TypeError, match=msg):
        com.standardize_mapping(list)

    fill = {"bad": "data"}
    assert com.standardize_mapping(fill) == dict

    # Convert instance to type
    assert com.standardize_mapping({}) == dict

    dd = collections.defaultdict(list)
    assert isinstance(com.standardize_mapping(dd), partial)

def test_git_version():
    # GH 21295
    git_version = pd.__git_version__
    assert len(git_version) == 40
    assert all(c in string.hexdigits for c in git_version)

def test_version_tag():
    version = Version(pd.__version__)
    try:
        version > Version("0.0.1")
    except TypeError:
        raise ValueError(
            "No git tags exist, please sync tags between upstream and your repo"
        )

@pytest.mark.parametrize(
    "obj", [(obj,) for obj in pd.__dict__.values() if callable(obj)]
)
def test_serializable(obj):
    # GH 35611
    unpickled = tm.round_trip_pickle(obj)
    assert type(obj) == type(unpickled)

class TestIsBoolIndexer:
    def test_non_bool_array_with_na(self):
        # in particular, this should not raise
        arr = np.array(["A", "B", np.nan], dtype=object)
        assert not com.is_bool_indexer(arr)

    def test_list_subclass(self):
        # GH#42433

        class MyList(list):
            pass

        val = MyList(["a"])

        assert not com.is_bool_indexer(val)

        val = MyList([True])
        assert com.is_bool_indexer(val)

    def test_frozenlist(self):
        # GH#42461
        data = {"col1": [1, 2], "col2": [3, 4]}
        df = pd.DataFrame(data=data)

        frozen = df.index.names[1:]
        assert not com.is_bool_indexer(frozen)

        result = df[frozen]
        expected = df[[]]
        tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("with_exception", [True, False])
def test_temp_setattr(with_exception):
    # GH#45954
    ser = Series(dtype=object)
    ser.name = "first"
    # Raise a ValueError in either case to satisfy pytest.raises
    match = "Inside exception raised" if with_exception else "Outside exception raised"
    with pytest.raises(ValueError, match=match):
        with com.temp_setattr(ser, "name", "second"):
            assert ser.name == "second"
            if with_exception:
                raise ValueError("Inside exception raised")
        raise ValueError("Outside exception raised")
    assert ser.name == "first"


text:
extern crate dotenv;
#[macro_use] extern crate diesel_codegen;

pub mod schema;
pub mod models;

use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;

use self::models::Hit;

pub fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url)
        .expect(&format!("Error connecting to {}", database_url))
}

pub fn create_hit<'a>(conn: &PgConnection, id: i32) -> Hit {
    use schema::hits;
    let new_hit = Hit {
        id: id,
        hits_so_far: 0,
    };

    diesel::insert(&new_hit).into(hits::table)
        .get_result(conn)
        .expect("Error saving new hit")
}


text:
package org.jivesoftware.smackx.caps.provider;

import java.io.IOException;

import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;

import org.jivesoftware.smackx.caps.EntityCapsManager;
import org.jivesoftware.smackx.caps.packet.CapsExtension;

public class CapsExtensionProvider extends ExtensionElementProvider<CapsExtension> {

    @Override
    public CapsExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException {
        String hash, version, node;
        if (parser.getEventType() == XmlPullParser.Event.START_ELEMENT
                && parser.getName().equalsIgnoreCase(EntityCapsManager.ELEMENT)) {
            hash = parser.getAttributeValue(null, "hash");
            version = parser.getAttributeValue(null, "ver");
            node = parser.getAttributeValue(null, "node");
        } else {
            // TODO: Should be SmackParsingException.
            throw new IOException("Malformed Caps element");
        }

        parser.next();

        if (!(parser.getEventType() == XmlPullParser.Event.END_ELEMENT
                && parser.getName().equalsIgnoreCase(EntityCapsManager.ELEMENT))) {
            // TODO: Should be SmackParsingException.
            throw new IOException("Malformed nested Caps element");
        }

        if (hash != null && version != null && node != null) {
            return new CapsExtension(node, version, hash);
        } else {
            // TODO: Should be SmackParsingException.
            throw new IOException("Caps element with missing attributes. Attributes: hash=" + hash + " version="
                            + version + " node=" + node);
        }
    }

}


text:
How to run the data tracker in docker
=======================

In the Embassy deployment, all components of the data tracker run in [docker](https://www.docker.com/) containers, i.e. go, mongodb, the perl tracking code etc.

For development, you can run the same containers on your local machine.
For development convenience, you can use [Docker compose](https://docs.docker.com/compose/) to easily start and stop the services. (but note we do not use docker-compose in production)

1. Mongodb
----------

Bring up the server

  docker-compose up -d mongodb

Use this command if you want to start a client to poke around in the database:

  docker-compose run db_client

* We use the [openshift/mongodb-32-centos7](https://hub.docker.com/r/openshift/mongodb-32-centos7/) mongodb image because it is production-ready and runs non-root.
* We use different passwords in production and development.

2. Perl tracking code
---------------------

These are the scripts that get run twice daily, to gather the data from IMS, hPSCreg etc.

First get the perl dependencies. For convenience in development, the modules will get installed on your local machine in the directory ./tracker/local. This means you don't have to re-install dependencies each time you build a new image.

  docker-compose run cpanm

Next, set up your environment with your hpscreg and ims username and password:

  export HPSCREG_USER=??????
  export HPSCREG_PASS=??????
  export IMS_USER=??????
  export IMS_PASS=??????

Next, run the tracking code:

  docker-compose run tracker

3. Compile angular code:
-----------------------

This is development convenience.  We build the javascript onto your local machine so you don't have to rebuild it each time your images chanegs.

  docker-compose run npm

3. Go webserver
---------------

First build the webserver.  Again, this is development convenience. We fetch the external dependencies onto your local machine so you don't have to re-fetch them when your image changes.

  docker-compose run webserver_build

Now bring up the webserver:

  docker-compose up -d webserver

This serves the app on port 8000 of your local machine. Open this link in your webrowser: [http://127.0.0.1:8000](http://127.0.0.1:8000)

Principles of secure docker deployment
===============================

* All containers run non-root
* SELinux is enforced in production
* Drop all capabilities
* Only publish the important ports to localhost.
* Mount file systems read-only where possible.
* Use official docker repos, not user-contributed.  The only place where I broke this rule is the centos/mongodb image.
* Keep passwords and API keys out of the image, in case the image ever accidentally ends up in a public repo.  Pass in passwords and keys at run time using environment variables.
* Run on a host with a minimal operating system. On Embassy we use coreos.


text:
package com.facebook.buck.android;

import com.facebook.buck.android.apkmodule.APKModuleGraph;
import com.facebook.buck.android.packageable.AndroidPackageableCollection;
import com.facebook.buck.android.packageable.AndroidPackageableCollector;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.common.BuildRules;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Collection;
import java.util.SortedSet;

public class AndroidAppModularityGraphEnhancer {

  private final BuildTarget originalBuildTarget;
  private final SortedSet<BuildRule> originalDeps;
  private final BuildRuleResolver ruleResolver;
  private final SourcePathRuleFinder ruleFinder;
  private final ImmutableSet<BuildTarget> buildTargetsToExcludeFromDex;
  private final APKModuleGraph apkModuleGraph;

  AndroidAppModularityGraphEnhancer(
      BuildTarget buildTarget,
      BuildRuleParams originalParams,
      BuildRuleResolver ruleResolver,
      ImmutableSet<BuildTarget> buildTargetsToExcludeFromDex,
      APKModuleGraph apkModuleGraph) {
    this.originalBuildTarget = buildTarget;
    this.originalDeps = originalParams.getBuildDeps();
    this.ruleResolver = ruleResolver;
    this.ruleFinder = new SourcePathRuleFinder(ruleResolver);
    this.buildTargetsToExcludeFromDex = buildTargetsToExcludeFromDex;
    this.apkModuleGraph = apkModuleGraph;
  }

  AndroidAppModularityGraphEnhancementResult createAdditionalBuildables() {

    ImmutableSortedSet.Builder<BuildRule> enhancedDeps = ImmutableSortedSet.naturalOrder();
    enhancedDeps.addAll(originalDeps);

    AndroidPackageableCollector collector =
        new AndroidPackageableCollector(
            originalBuildTarget, buildTargetsToExcludeFromDex, apkModuleGraph);
    collector.addPackageables(
        AndroidPackageableCollector.getPackageableRules(originalDeps), ruleResolver);
    AndroidPackageableCollection packageableCollection = collector.build();

    enhancedDeps.addAll(getTargetsAsRules(packageableCollection.getJavaLibrariesToDex()));

    // Add dependencies on all the build rules generating third-party JARs.  This is mainly to
    // correctly capture deps when a prebuilt_jar forwards the output from another build rule.
    enhancedDeps.addAll(
        ruleFinder.filterBuildRuleInputs(
            packageableCollection
                .getPathsToThirdPartyJars()
                .get(apkModuleGraph.getRootAPKModule())));

    return AndroidAppModularityGraphEnhancementResult.builder()
        .setPackageableCollection(packageableCollection)
        .setFinalDeps(enhancedDeps.build())
        .setAPKModuleGraph(apkModuleGraph)
        .build();
  }

  private ImmutableSortedSet<BuildRule> getTargetsAsRules(Collection<BuildTarget> buildTargets) {
    return BuildRules.toBuildRulesFor(originalBuildTarget, ruleResolver, buildTargets);
  }
}


text:
<?php

namespace InsaLan\PizzaBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class OrderAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('expiration', null, array('label' => "Horaire limite"))
            ->add('delivery', null, array('label' => "Horaire de livraison"))
            ->add('capacity', null, array('label' => "Nombre de pizzas max"))
            ->add('foreignCapacity', null, array('label' => "Limite de commandes pour non joueurs"))
            ->add('closed', null, array('required' => false, 'label' => "Verrouillé"));
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('delivery', null, array('label' => "Horaire de livraison"))
            ->addIdentifier('capacity', null, array('label' => "Capacité"))
            ->addIdentifier('closed', null, array('required' => false, 'label' => "Verrouillé"));
        ;
    }
}


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System.Diagnostics;
using System.IO;
using Bytescout.Spreadsheet;

namespace Bytescout.Spreadsheet.Demo.Csharp.ImportFrom2DArray
{
    class Program
    {
        static void Main(string[] args)
        {
            const string fileName = "CSharpImportFrom2DArray.xls";

            // Create a new spreadsheet
            Spreadsheet spreadsheet = new Spreadsheet();

            // Get the data from the 2D array that we want to import
            string[,] stockPrices = Get2DArray();

            // Import data into spreadheet
            spreadsheet.ImportFrom2DArray(stockPrices);

            // Save the spreadsheet
            if (File.Exists(fileName)) File.Delete(fileName);
            spreadsheet.SaveAs(fileName);

            // Close spreadsheet
            spreadsheet.Close();

            // Open the spreadsheet
            Process.Start(fileName);
        }

        /// <summary>
        /// Creates a 2D array of stock prices
        /// </summary>
        /// <returns>2d array of stock prices</returns>
        private static string[,] Get2DArray()
        {
            string[,] stockPrices = new string[10, 2];

            stockPrices[0, 0] = "AAPL"; stockPrices[0, 1] = "24,89";
            stockPrices[1, 0] = "AMZN"; stockPrices[1, 1] = "27,95";
            stockPrices[2, 0] = "DELL"; stockPrices[2, 1] = "12,68";
            stockPrices[3, 0] = "EBAY"; stockPrices[3, 1] = "57,27";
            stockPrices[4, 0] = "GOOG"; stockPrices[4, 1] = "28,98";

            stockPrices[5, 0] = "IBM "; stockPrices[5, 1] = "24,00";
            stockPrices[6, 0] = "INTC"; stockPrices[6, 1] = "12,24";
            stockPrices[7, 0] = "MSFT"; stockPrices[7, 1] = "37,85";
            stockPrices[8, 0] = "SNE "; stockPrices[8, 1] = "39,91";
            stockPrices[9, 0] = "YHOO"; stockPrices[9, 1] = "78,72";

            return stockPrices;
        }

    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! The `ByteString` struct.

use cssparser::CowRcStr;
use html5ever::{LocalName, Namespace};
use servo_atoms::Atom;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::{Borrow, Cow, ToOwned};
use std::default::Default;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops;
use std::ops::{Deref, DerefMut};
use std::str;
use std::str::{Bytes, FromStr};

/// Encapsulates the IDL `ByteString` type.
#[derive(Clone, Debug, Default, Eq, JSTraceable, MallocSizeOf, PartialEq)]
pub struct ByteString(Vec<u8>);

impl ByteString {
    /// Creates a new `ByteString`.
    pub fn new(value: Vec<u8>) -> ByteString {
        ByteString(value)
    }

    /// Returns `self` as a string, if it encodes valid UTF-8, and `None`
    /// otherwise.
    pub fn as_str(&self) -> Option<&str> {
        str::from_utf8(&self.0).ok()
    }

    /// Returns the length.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Compare `self` to `other`, matching A–Z and a–z as equal.
    pub fn eq_ignore_case(&self, other: &ByteString) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }

    /// Returns `self` with A–Z replaced by a–z.
    pub fn to_lower(&self) -> ByteString {
        ByteString::new(self.0.to_ascii_lowercase())
    }
}

impl Into<Vec<u8>> for ByteString {
    fn into(self) -> Vec<u8> {
        self.0
    }
}

impl Hash for ByteString {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl FromStr for ByteString {
    type Err = ();
    fn from_str(s: &str) -> Result<ByteString, ()> {
        Ok(ByteString::new(s.to_owned().into_bytes()))
    }
}

impl ops::Deref for ByteString {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.0
    }
}

/// A string that is constructed from a UCS-2 buffer by replacing invalid code
/// points with the replacement character.
#[derive(Clone, Default, MallocSizeOf)]
pub struct USVString(pub String);

/// Returns whether `s` is a `token`, as defined by
/// [RFC 2616](http://tools.ietf.org/html/rfc2616#page-17).
pub fn is_token(s: &[u8]) -> bool {
    if s.is_empty() {
        return false; // A token must be at least a single character
    }
    s.iter().all(|&x| {
        // http://tools.ietf.org/html/rfc2616#section-2.2
        match x {
            0...31 | 127 => false, // CTLs
            40 |
            41 |
            60 |
            62 |
            64 |
            44 |
            59 |
            58 |
            92 |
            34 |
            47 |
            91 |
            93 |
            63 |
            61 |
            123 |
            125 |
            32 => false, // separators
            x if x > 127 => false, // non-CHARs
            _ => true,
        }
    })
}

/// A DOMString.
///
/// This type corresponds to the [`DOMString`](idl) type in WebIDL.
///
/// [idl]: https://heycam.github.io/webidl/#idl-DOMString
///
/// Conceptually, a DOMString has the same value space as a JavaScript String,
/// i.e., an array of 16-bit *code units* representing UTF-16, potentially with
/// unpaired surrogates present (also sometimes called WTF-16).
///
/// Currently, this type stores a Rust `String`, in order to avoid issues when
/// integrating with the rest of the Rust ecosystem and even the rest of the
/// browser itself.
///
/// However, Rust `String`s are guaranteed to be valid UTF-8, and as such have
/// a *smaller value space* than WTF-16 (i.e., some JavaScript String values
/// can not be represented as a Rust `String`). This introduces the question of
/// what to do with values being passed from JavaScript to Rust that contain
/// unpaired surrogates.
///
/// The hypothesis is that it does not matter much how exactly those values are
/// transformed, because passing unpaired surrogates into the DOM is very rare.
/// In order to test this hypothesis, Servo will panic when encountering any
/// unpaired surrogates on conversion to `DOMString` by default. (The command
/// line option `-Z replace-surrogates` instead causes Servo to replace the
/// unpaired surrogate by a U+FFFD replacement character.)
///
/// Currently, the lack of crash reports about this issue provides some
/// evidence to support the hypothesis. This evidence will hopefully be used to
/// convince other browser vendors that it would be safe to replace unpaired
/// surrogates at the boundary between JavaScript and native code. (This would
/// unify the `DOMString` and `USVString` types, both in the WebIDL standard
/// and in Servo.)
///
/// This type is currently `!Send`, in order to help with an independent
/// experiment to store `JSString`s rather than Rust `String`s.
#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd)]
pub struct DOMString(String, PhantomData<*const ()>);

impl DOMString {
    /// Creates a new `DOMString`.
    pub fn new() -> DOMString {
        DOMString(String::new(), PhantomData)
    }

    /// Creates a new `DOMString` from a `String`.
    pub fn from_string(s: String) -> DOMString {
        DOMString(s, PhantomData)
    }

    /// Appends a given string slice onto the end of this String.
    pub fn push_str(&mut self, string: &str) {
        self.0.push_str(string)
    }

    /// Clears this `DOMString`, removing all contents.
    pub fn clear(&mut self) {
        self.0.clear()
    }

    /// Shortens this String to the specified length.
    pub fn truncate(&mut self, new_len: usize) {
        self.0.truncate(new_len);
    }

    /// An iterator over the bytes of this `DOMString`.
    pub fn bytes(&self) -> Bytes {
        self.0.bytes()
    }
}

impl Borrow<str> for DOMString {
    #[inline]
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Default for DOMString {
    fn default() -> Self {
        DOMString(String::new(), PhantomData)
    }
}

impl Deref for DOMString {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        &self.0
    }
}

impl DerefMut for DOMString {
    #[inline]
    fn deref_mut(&mut self) -> &mut str {
        &mut self.0
    }
}

impl AsRef<str> for DOMString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for DOMString {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl PartialEq<str> for DOMString {
    fn eq(&self, other: &str) -> bool {
        &**self == other
    }
}

impl<'a> PartialEq<&'a str> for DOMString {
    fn eq(&self, other: &&'a str) -> bool {
        &**self == *other
    }
}

impl From<String> for DOMString {
    fn from(contents: String) -> DOMString {
        DOMString(contents, PhantomData)
    }
}

impl<'a> From<&'a str> for DOMString {
    fn from(contents: &str) -> DOMString {
        DOMString::from(String::from(contents))
    }
}

impl<'a> From<Cow<'a, str>> for DOMString {
    fn from(contents: Cow<'a, str>) -> DOMString {
        match contents {
            Cow::Owned(s) => DOMString::from(s),
            Cow::Borrowed(s) => DOMString::from(s),
        }
    }
}

impl From<DOMString> for LocalName {
    fn from(contents: DOMString) -> LocalName {
        LocalName::from(contents.0)
    }
}

impl From<DOMString> for Namespace {
    fn from(contents: DOMString) -> Namespace {
        Namespace::from(contents.0)
    }
}

impl From<DOMString> for Atom {
    fn from(contents: DOMString) -> Atom {
        Atom::from(contents.0)
    }
}

impl From<DOMString> for String {
    fn from(contents: DOMString) -> String {
        contents.0
    }
}

impl Into<Vec<u8>> for DOMString {
    fn into(self) -> Vec<u8> {
        self.0.into()
    }
}

impl<'a> Into<Cow<'a, str>> for DOMString {
    fn into(self) -> Cow<'a, str> {
        self.0.into()
    }
}

impl<'a> Into<CowRcStr<'a>> for DOMString {
    fn into(self) -> CowRcStr<'a> {
        self.0.into()
    }
}

impl Extend<char> for DOMString {
    fn extend<I>(&mut self, iterable: I) where I: IntoIterator<Item=char> {
        self.0.extend(iterable)
    }
}


text:
class Root < Formula
  desc "Object oriented framework for large scale data analysis"
  homepage "https://root.cern.ch/"
  url "https://root.cern.ch/download/root_v6.20.04.source.tar.gz"
  version "6.20.04"
  sha256 "1f8c76ccdb550e64e6ddb092b4a7e9d0a10655ef80044828cba12d5e7c874472"
  revision 1
  head "https://github.com/root-project/root.git"

  bottle do
    sha256 "1ca7ad236fb7dd679e05c67de244e3b543aee4f5a1f339a4696cb5a8fd0e039f" => :catalina
    sha256 "860c572ff58fe06359ea953b9df387454080131289b5c81aca21b7a39a918e59" => :mojave
    sha256 "ddad01a197626587c16422fff0a1afd9dde8f15df3fe295107b757bf50231a94" => :high_sierra
  end

  # https://github.com/Homebrew/homebrew-core/issues/30726
  # strings libCling.so | grep Xcode:
  #  /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
  #  /Applications/Xcode.app/Contents/Developer
  pour_bottle? do
    reason "The bottle hardcodes locations inside Xcode.app"
    satisfy do
      MacOS::Xcode.installed? &&
        MacOS::Xcode.prefix.to_s.include?("/Applications/Xcode.app/")
    end
  end

  depends_on "cmake" => :build
  depends_on "cfitsio"
  depends_on "davix"
  depends_on "fftw"
  depends_on "gcc" # for gfortran
  depends_on "gl2ps"
  depends_on "graphviz"
  depends_on "gsl"
  # Temporarily depend on Homebrew libxml2 to work around a brew issue:
  # https://github.com/Homebrew/brew/issues/5068
  depends_on "libxml2" if MacOS.version >= :mojave
  depends_on "lz4"
  depends_on "numpy" # for tmva
  depends_on "openssl@1.1"
  depends_on "pcre"
  depends_on "python@3.8"
  depends_on "tbb"
  depends_on "xrootd"
  depends_on "xz" # for LZMA
  depends_on "zstd"

  skip_clean "bin"

  def install
    # Work around "error: no member named 'signbit' in the global namespace"
    ENV.delete("SDKROOT") if DevelopmentTools.clang_build_version >= 900

    # Freetype/afterimage/gl2ps/lz4 are vendored in the tarball, so are fine.
    # However, this is still permitting the build process to make remote
    # connections. As a hack, since upstream support it, we inreplace
    # this file to "encourage" the connection over HTTPS rather than HTTP.
    inreplace "cmake/modules/SearchInstalledSoftware.cmake",
              "http://lcgpackages",
              "https://lcgpackages"

    args = std_cmake_args + %W[
      -DCLING_CXX_PATH=clang++
      -DCMAKE_INSTALL_ELISPDIR=#{elisp}
      -DPYTHON_EXECUTABLE=#{Formula["python@3.8"].opt_bin}/python3
      -Dbuiltin_cfitsio=OFF
      -Dbuiltin_freetype=ON
      -Dbuiltin_glew=ON
      -Ddavix=ON
      -Dfftw3=ON
      -Dfitsio=ON
      -Dfortran=ON
      -Dgdml=ON
      -Dgnuinstall=ON
      -Dimt=ON
      -Dmathmore=ON
      -Dminuit2=ON
      -Dmysql=OFF
      -Dpgsql=OFF
      -Dpython=ON
      -Droofit=ON
      -Dssl=ON
      -Dtmva=ON
      -Dxrootd=ON
    ]

    cxx_version = (MacOS.version < :mojave) ? 14 : 17
    args << "-DCMAKE_CXX_STANDARD=#{cxx_version}"

    mkdir "builddir" do
      system "cmake", "..", *args

      # Work around superenv stripping out isysroot leading to errors with
      # libsystem_symptoms.dylib (only available on >= 10.12) and
      # libsystem_darwin.dylib (only available on >= 10.13)
      if MacOS.version < :high_sierra
        system "xcrun", "make", "install"
      else
        system "make", "install"
      end

      chmod 0755, Dir[bin/"*.*sh"]
    end
  end

  def caveats
    <<~EOS
      Because ROOT depends on several installation-dependent
      environment variables to function properly, you should
      add the following commands to your shell initialization
      script (.bashrc/.profile/etc.), or call them directly
      before using ROOT.

      For bash users:
        . #{HOMEBREW_PREFIX}/bin/thisroot.sh
      For zsh users:
        pushd #{HOMEBREW_PREFIX} >/dev/null; . bin/thisroot.sh; popd >/dev/null
      For csh/tcsh users:
        source #{HOMEBREW_PREFIX}/bin/thisroot.csh
      For fish users:
        . #{HOMEBREW_PREFIX}/bin/thisroot.fish
    EOS
  end

  test do
    (testpath/"test.C").write <<~EOS
      #include <iostream>
      void test() {
        std::cout << "Hello, world!" << std::endl;
      }
    EOS

    # Test ROOT command line mode
    system "#{bin}/root", "-b", "-l", "-q", "-e", "gSystem->LoadAllLibraries(); 0"

    # Test ROOT executable
    (testpath/"test_root.bash").write <<~EOS
      . #{bin}/thisroot.sh
      root -l -b -n -q test.C
    EOS
    assert_equal "\nProcessing test.C...\nHello, world!\n",
                 shell_output("/bin/bash test_root.bash")

    (testpath/"test.cpp").write <<~EOS
      #include <iostream>
      #include <TString.h>
      int main() {
        std::cout << TString("Hello, world!") << std::endl;
        return 0;
      }
    EOS

    # Test linking
    (testpath/"test_compile.bash").write <<~EOS
      . #{bin}/thisroot.sh
      $(root-config --cxx) $(root-config --cflags) $(root-config --libs) $(root-config --ldflags) test.cpp
      ./a.out
    EOS
    assert_equal "Hello, world!\n",
                 shell_output("/bin/bash test_compile.bash")

    # Test Python module
    ENV["PYTHONPATH"] = lib/"root"
    system Formula["python@3.8"].opt_bin/"python3", "-c", "import ROOT; ROOT.gSystem.LoadAllLibraries()"
  end
end


text:
var request = require('request');
var cheerio = require('cheerio');
var Entry = require('../../../models/Entry');
var sp = require('./info.json');
var extractor = require('../../extractor');

module.exports = {
  // Custom headers
  customHeaders: {},
  // Generate sources
  generateSources: function() {
    var result = [];
    sp.kijiji.locations.forEach(function(place) {
      var location = '/' + place.alias;
      var suffix = place.code
      var address = place.name;
      sp.kijiji.adTypes.forEach(function(adType) {
        var type = adType.code;
        sp.kijiji.services.forEach(function(service) {
          var serviceAlias = service.alias_en;
          if (place.name === 'Quebec') {
            serviceAlias = service.alias_fr;
          }
          var pagesArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
          // var pagesArray = [1];
          pagesArray.forEach(function(page) {
            var middle = '/page-' + page;
            if (page === 1) {
              middle = '';
            }

            var path = sp.kijiji.website + '/' +
              serviceAlias +
              location + middle + '/' + service.code +
              suffix +
              type;
            var obj = {
              url: path,
              address: address,
              project: service.name,
              category: adType.name,
              country: 'Canada',
              source: 'Kijiji'
            }
            result.push(obj);
          });
        });
      });
    });
    return result;
  },
  // Parse page
  parsePage: function(page) {
    return new Promise(function(resolve, reject) {
      var $ = cheerio.load(page.htmlBody);
      var list = [];
      $('a.title').each(function() {
        var url = $(this).attr('href');
        delete page.htmlBody;
        var current = 1;
        var expected = parseInt($('span.selected').text());
        if (page.url.split('/').length > 6) {
          current = parseInt(page.url.split('/')[5].split('-')[1]);
        }
        list.push({
          url: sp.kijiji.website + url,
          address: page.address,
          project: page.project,
          category: page.category,
          country: page.country,
          source: page.source,
          okToGo: current == expected
        });
      });
      return resolve(list);
    });
  },
  // Parse entry
  parseEntry: function(entry) {
    return new Promise(function(resolve, reject) {
      var $ = cheerio.load(entry.htmlBody);
      var date = $('table.ad-attributes td').html();
      var text = $('#UserContent').text();
      var obj = new Entry({
        url: entry.url,
        body: text,
        date: parseDate(date),
        address: entry.address,
        source: 'Kijiji',
        country: 'Canada',
        project: entry.project,
        phone: extractor.getPhone(text),
        language: extractor.getLanguage(text),
        email: extractor.getEmail(text),
        category: entry.category,
        town: entry.url.split('/')[4].split('-').join(' ')
      });
      return resolve(obj);
    });
  }
}

function parseDate(date) {
  var arr = date.split('-');
  var year = parseInt('20' + arr[2]);
  var month = parseMonth(arr[1]) - 1;
  var day = parseInt(arr[0]);
  return new Date(year, month, day);
}

function parseMonth(month) {
  var lowerM = month.toLowerCase();
  if (lowerM === 'jan' || lowerM === 'janv.')
    return 1;
  else if (lowerM === 'feb' || lowerM === 'févr.')
    return 2;
  else if (lowerM === 'mar' || lowerM === 'mars')
    return 3;
  else if (lowerM === 'apr')
    return 4;
  else if (lowerM === 'may')
    return 5;
  else if (lowerM === 'jun')
    return 6;
  else if (lowerM === 'jul')
    return 7
  else if (lowerM === 'aug')
    return 8;
  else if (lowerM === 'sep')
    return 9;
  else if (lowerM === 'oct')
    return 10;
  else if (lowerM === 'nov')
    return 11;
  else if (lowerM === 'dec' || lowerM === 'déc.')
    return 12;
  else {
    console.log(lowerM);
    return 4;
  }
}


text:
alter table GENERIC_REPORTER disable constraint SYS_C0021099;
alter table GENERIC_REPORTER disable constraint SYS_C004452;
alter table GENERIC_REPORTER disable constraint SYS_C004453;
alter table GENERIC_REPORTER disable constraint GREP;

alter table GENERIC_REPORTER disable primary key;

--EXIT;


text:
require_relative 'base'
require_relative 'whois.centralnic.com.rb'

module Whois
  class Parsers

    # Parser for the whois.nic.pw server.
    #
    # It aliases the whois.centralnic.com parser because
    # the .PW TLD is powered by Centralnic.
    class WhoisNicPw < WhoisCentralnicCom
    end

  end
end


text:
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports DotNetNuke
Imports DotNetNuke.Security

Namespace DotNetNuke.Modules.SearchDirectory
    Partial Class SearchDirectory
        Inherits Entities.Modules.PortalModuleBase

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load

        End Sub

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click
            'Dim d As New FullStory.FullStoryDataContext
            'If d.Agape_Main_GlobalDatas.Count > 0 Then
            '    Response.Redirect(NavigateURL(CInt(d.Agape_Main_GlobalDatas.First.StaffDirectoryTabId)) & "?search=" & SearchBox.Text)

            'End If

        End Sub
    End Class
End Namespace