text:
import logging
import re
import copy

from collections import OrderedDict

#: Macro regex
RE_MACRO = re.compile(r'\$\{(.+?)\}')

#: Macro variable regex
RE_MACRO_VAR = re.compile(r'[a-z][a-z0-9\._]*', flags=re.IGNORECASE)

class Context(OrderedDict):
	"""
	An environment variable and context
	"""

	@staticmethod
	def definitions_in( specs_dict ):
		"""
		Traverse specifications dict and detect definitions
		"""

		# Prepare properties
		defs = set()
		stack = [ specs_dict ]

		# Traverse stack
		while stack:
			top = stack.pop(0)
			for k,v in top.items():
				if isinstance(v, dict):
					if k == "define":
						defs.update( v.keys() )
					else:
						stack.append(v)
				elif isinstance(v, list):
					for d in v:
						if isinstance(d, dict):
							stack.append(d)

		# Return definitions
		return defs

	def __init__(self, contents={}, definitions=set()):
		"""
		Initialize parent dictionary
		"""
		OrderedDict.__init__(self, contents)
		self._definitions = definitions

	def fork(self):
		"""
		Deep copy current context into another context
		"""
		return Context( copy.deepcopy(self), self._definitions )

	def set(self, name, value, include_flag=True):
		"""
		Set the specified value in the context and optionally
		also update a flat representation of the value.
		"""

		# Set value
		self[name] = value

		# Update flat representation
		if include_flag:

			if isinstance(value, dict):
				for k,v in value.items():
					self.set( "%s.%s" % (name,k), v )

			elif isinstance(value, list):
				i = 0
				for v in value:
					if 'name' in v:
						self.set( "%s.%s" % (name,v['name']), v )
					else:
						self.set( "%s.%i" % (name,i), v )
					i += 1

	def merge(self, name, value, include_flag=True):
		"""
		Merge the specified value in the context and optionally
		also update a flat representation of the value.
		"""

		# Set value
		if name in self:
			if isinstance(value, dict):

				# Merge list
				i = len(self[name])
				self[name] += value

				# Update flat representation
				if include_flag:
					for v in value:
						if 'name' in v:
							self.set( "%s.%s" % (name,v['name']), v )
						else:
							self.set( "%s.%i" % (name,i), v )
						i += 1

				# Don't continue
				return

			elif isinstance(value, list):

				# Merge dictionary
				self[name].update( value )

				# Update flat representation
				if include_flag:
					for k,v in value.items():
						self.set( "%s.%s" % (name,k), v )

				# Don't continue
				return

		# Update value
		self[name] = value

	def render(self):
		"""
		Replace all macros in this context and return a
		dictionary with all values
		"""
		logger = logging.getLogger('context')

		# Prepare properties
		self._unreplaced = set()
		replaced = True

		# Deep-copy dictionary
		dictionary = copy.deepcopy(self)

		# Keep replacing until there are no other macros to replace
		while replaced:
			# Replace and check if this was indeed replaced
			(dictionary, replaced) = self.replaceMacros( dictionary )

		# Log unreplaced items
		for m in self._unreplaced:
			if not m in self._definitions:
				logger.warn("Unknown macro '${%s}' encountered in specifications!" % m)

		# Return a new context with the new dictionary
		return Context( dictionary )

	def evaluate(self, expr):
		"""
		Evaluate a macro expression
		"""
		logger = logging.getLogger('context')

		# Reset properties
		self._evalMissing = False

		# Extract default value
		defaultValue = None
		if '|' in expr:
			(expr, defaultValue) = expr.split("|", 1)

		# Check if this is an expression
		if ('*' in expr) or ('+' in expr) or ('/' in expr) or ('%' in expr) or \
			('-' in expr) or ('^' in expr) or ('(' in expr) or (')' in expr):

			# Replace helper
			def replace(m):
				key = m.group(0)

				# Ignore some functions
				if key in [ 'str', 'int', 'float', 'pow', 'round' ]:
					return m.group(0)

				# Replace values
				if not key in self:
					self._evalMissing = True
					return ""
				else:

					# Check if we should wrap value in quotes
					value = str(self[key])
					if value.isdigit() or ((value.count(".") == 1) and value.replace(".","").isdigit()):
						return value
					else:
						return '"%s"' % value.replace('"', '\\"')

			# Expand variables
			eval_expr = RE_MACRO_VAR.sub( replace, expr )

			# Check if we had missing properties
			if self._evalMissing:
				return defaultValue

			# Otherwise evaluate expression
			try:
				return eval(eval_expr)
			except Exception as e:
				logger.warn("Error evaluating macro expression '%s': %s" % (expr, str(e)))
				return defaultValue

		else:

			# It's a plain value, return calculation
			if expr in self:
				return self[expr]
			else:
				return defaultValue

	def replaceMacros(self, where, _firstCall=True):
		"""
		Replace all macros in context to the given string
		"""
		unused = False

		# Check if a value was indeed updated
		if _firstCall:
			self._did_replace = False

		# Replace helper
		def replace(m):
			# Try to evaluate expression
			key = m.group(1)
			value = self.evaluate( key )
			if value is None:
				# Return un-replaced
				self._unreplaced.add(key)
				return m.group(0)
			else:
				# Return replaced & mark action
				self._did_replace = True
				# Remove from unreplaced
				if key in self._unreplaced:
					self._unreplaced.remove(key)
				return str(value)

		# Replace all macros in dict
		if isinstance(where, dict):
			ans = {}
			for k,v in where.items():
				(ans[k], unused) = self.replaceMacros(v, False)

			return (ans, self._did_replace)

		# Replace all macros in list
		elif isinstance(where, list):
			ans = []
			for v in where:
				ans.append( self.replaceMacros(v, False)[0] )
			return (ans, self._did_replace)

		# Replace all macros in string
		elif isinstance(where, str):
			return (RE_MACRO.sub( replace, where ), self._did_replace)

		# Pass through everything else
		else:
			return (where, self._did_replace)


text:
<?php
// The User->Posts relation inherits the default Post permissions
require(APP . 'Config' . DS . 'Acl' . DS . 'Post.php');

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Error</title>

This is the default view for the blockip-package.

                To customize this, simply edit your blockip-configuration file and set
                error_view to your own custom blade-template (the default is blockip::default).


text:
@class UIImage, UIImageView, UILabel, UIColor, UIButton;
@class UITextFieldAtomBackgroundView;
@class UITextFieldBackgroundView;
@class UITextFieldBorderView;
@class UITextFieldLabel;
@class UITextInputTraits;
@class UITextSelectionView;
@class UITextInteractionAssistant;
@class UIPopoverController;
@protocol UITextFieldDelegate;
@protocol UITextSelecting;

typedef NS_ENUM(NSInteger, UITextBorderStyle) {
    UITextBorderStyleNone,
    UITextBorderStyleLine,
    UITextBorderStyleBezel,
    UITextBorderStyleRoundedRect
};

typedef NS_ENUM(NSInteger, UITextFieldViewMode) {
    UITextFieldViewModeNever,
    UITextFieldViewModeWhileEditing,
    UITextFieldViewModeUnlessEditing,
    UITextFieldViewModeAlways
};

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITextField : UIControl <UITextInput, NSCoding>

@property(nonatomic,copy)   NSString               *text;                 // default is nil
@property(nonatomic,copy)   NSAttributedString     *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
@property(nonatomic,retain) UIColor                *textColor;            // default is nil. use opaque black
@property(nonatomic,retain) UIFont                 *font;                 // default is nil. use system font 12 pt
@property(nonatomic)        NSTextAlignment         textAlignment;        // default is NSLeftTextAlignment
@property(nonatomic)        UITextBorderStyle       borderStyle;          // default is UITextBorderStyleNone. If set to UITextBorderStyleRoundedRect, custom background images are ignored.
@property(nonatomic,copy)   NSDictionary           *defaultTextAttributes NS_AVAILABLE_IOS(7_0); // applies attributes to the full range of text. Unset attributes act like default values.

@property(nonatomic,copy)   NSString               *placeholder;          // default is nil. string is drawn 70% gray
@property(nonatomic,copy)   NSAttributedString     *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil
@property(nonatomic)        BOOL                    clearsOnBeginEditing; // default is NO which moves cursor to location clicked. if YES, all text cleared
@property(nonatomic)        BOOL                    adjustsFontSizeToFitWidth; // default is NO. if YES, text will shrink to minFontSize along baseline
@property(nonatomic)        CGFloat                 minimumFontSize;      // default is 0.0. actual min may be pinned to something readable. used if adjustsFontSizeToFitWidth is YES
@property(nonatomic,assign) id<UITextFieldDelegate> delegate;             // default is nil. weak reference
@property(nonatomic,retain) UIImage                *background;           // default is nil. draw in border rect. image should be stretchable
@property(nonatomic,retain) UIImage                *disabledBackground;   // default is nil. ignored if background not set. image should be stretchable

@property(nonatomic,readonly,getter=isEditing) BOOL editing;
@property(nonatomic) BOOL allowsEditingTextAttributes NS_AVAILABLE_IOS(6_0); // default is NO. allows editing text attributes with style operations and pasting rich text
@property(nonatomic,copy) NSDictionary *typingAttributes NS_AVAILABLE_IOS(6_0); // automatically resets when the selection changes

// You can supply custom views which are displayed at the left or right
// sides of the text field. Uses for such views could be to show an icon or
// a button to operate on the text in the field in an application-defined
// manner.
//
// A very common use is to display a clear button on the right side of the
// text field, and a standard clear button is provided. Note: if the clear
// button overlaps one of the other views, the clear button will be given
// precedence.

@property(nonatomic)        UITextFieldViewMode  clearButtonMode; // sets when the clear button shows up. default is UITextFieldViewModeNever

@property(nonatomic,retain) UIView              *leftView;        // e.g. magnifying glass
@property(nonatomic)        UITextFieldViewMode  leftViewMode;    // sets when the left view shows up. default is UITextFieldViewModeNever

@property(nonatomic,retain) UIView              *rightView;       // e.g. bookmarks button
@property(nonatomic)        UITextFieldViewMode  rightViewMode;   // sets when the right view shows up. default is UITextFieldViewModeNever

// drawing and positioning overrides

- (CGRect)borderRectForBounds:(CGRect)bounds;
- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)placeholderRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;
- (CGRect)clearButtonRectForBounds:(CGRect)bounds;
- (CGRect)leftViewRectForBounds:(CGRect)bounds;
- (CGRect)rightViewRectForBounds:(CGRect)bounds;

- (void)drawTextInRect:(CGRect)rect;
- (void)drawPlaceholderInRect:(CGRect)rect;

// Presented when object becomes first responder.  If set to nil, reverts to following responder chain.  If
// set while first responder, will not take effect until reloadInputViews is called.
@property (readwrite, retain) UIView *inputView;
@property (readwrite, retain) UIView *inputAccessoryView;

@property(nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS(6_0); // defaults to NO. if YES, the selection UI is hidden, and inserting text will replace the contents of the field. changing the selection will automatically set this to NO.

@end

@interface UIView (UITextField)
- (BOOL)endEditing:(BOOL)force;    // use to make the view or any subview that is the first responder resign (optionally force)
@end

@protocol UITextFieldDelegate <NSObject>

@optional

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField;             // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text

- (BOOL)textFieldShouldClear:(UITextField *)textField;               // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // called when 'return' key pressed. return NO to ignore.

@end

UIKIT_EXTERN NSString *const UITextFieldTextDidBeginEditingNotification;
UIKIT_EXTERN NSString *const UITextFieldTextDidEndEditingNotification;
UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;


text:
<?php

namespace Scribe\Arthur\DoctrineFixturesBundle\DataFixtures\Tree;

/**
 * Class TreeStore.
 */
class TreeStore implements TreeStoreInterface
{
    /**
     * @var array
     */
    protected $tree;

    /**
     * @var string
     */
    protected $root;

    /**
     * @param mixed[]     $tree
     * @param null|string $root
     *
     * @return $this
     */
    public static function create(array $tree = [], $root = null)
    {
        $instance = (new self())
            ->setTree($tree)
            ->setRoot($root);

        return $instance;
    }

    /**
     * @param array|null $tree
     *
     * @return $this
     */
    public function setTree(array $tree = null)
    {
        $this->tree = $tree ?: [];

        return $this;
    }

    /**
     * @param null $root
     *
     * @return $this
     */
    public function setRoot($root = null)
    {
        $this->root = $root;

        return $this;
    }

    /**
     * @param string,... $keySet
     *
     * @return mixed
     */
    public function get(...$keySet)
    {
        $keySet = $this->root === null ? $keySet : array_merge((array) $this->root, $keySet);

        return $this->resolveDeepSearch($this->tree, $keySet);
    }

    /**
     * @param array $tree
     * @param array $keySet
     *
     * @return null|mixed
     */
    protected function resolveDeepSearch(array $tree, array $keySet)
    {
        $key = array_shift($keySet);

        if (true !== array_key_exists($key, $tree)) {
            return;
        }

        if (false === (count($keySet) > 0)) {
            return $tree[$key];
        }

        if (!is_array($tree[$key])) {
            return;
        }

        return $this->resolveDeepSearch($tree[$key], $keySet);
    }
}

/* EOF */


text:
function Window_BattleItem() {
    this.initialize.apply(this, arguments);
}

Window_BattleItem.prototype = Object.create(Window_ItemList.prototype);
Window_BattleItem.prototype.constructor = Window_BattleItem;

Window_BattleItem.prototype.initialize = function(x, y, width, height) {
    Window_ItemList.prototype.initialize.call(this, x, y, width, height);
    this.hide();
};

Window_BattleItem.prototype.includes = function(item) {
    return $gameParty.canUse(item);
};

Window_BattleItem.prototype.show = function() {
    this.selectLast();
    this.showHelpWindow();
    Window_ItemList.prototype.show.call(this);
};

Window_BattleItem.prototype.hide = function() {
    this.hideHelpWindow();
    Window_ItemList.prototype.hide.call(this);
};


text:
.tableHeader {
	font-weight: bolder;
}
.tbox {
		background-color: #F4F7FA;
		border: #5e5d63 1px solid;
		color: #000000;
		font: 10px verdana, tahoma, arial, helvetica, sans-serif;
}

.shaded {
	background-color: gray;
	filter:alpha(opacity=85);
    opacity: 0.85;
	-moz-opacity:0.85;
	-khtml-opacity: 0.85;
	margin: 10px 10px 10px 10px;
	width:auto;
	float: top;
}

.error {
	font-style:italic;
	font-weight:bold;
	font-family:Geneva, Arial, Helvetica, sans-serif;
}

body {
	/*background-image:url(images/background.png);*/
	background-attachment:fixed;
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace YuYan.Domain.Database
{
    [Table("SurveyQuestionItem")]
    public class tbSurveyQuestionItem: tbTbase
    {
        [Key, Column("Id")]
        public int QuestionItemId { get; set; }
        public int QuestionId { get; set; }
        public string ItemDescription { get; set; }
        public int ItemOrder { get; set; }
        public Nullable<int> Score { get; set; }
        public Nullable<int> GotoQuestionId { get; set; }

        [ForeignKey("QuestionId")]
        public virtual tbSurveyQuestion tbSurveyQuestion { get; set; }
    }
}


text:
package net.savantly.sprout.module.content.model.webPageLayout;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OrderColumn;
import javax.persistence.Table;

import net.savantly.sprout.core.domain.PersistedDomainObject;

@Entity
@Table(name="WEB_PAGE_LAYOUT")
public class WebPageLayout extends PersistedDomainObject {
	@Column(unique=true)
	private String name;
	private String description;
	@ElementCollection(fetch=FetchType.EAGER)
	@CollectionTable(name = "WEB_PAGE_LAYOUT_PLACEHOLDER")
	@OrderColumn(name = "index_id")
	private Set<String> placeHolders = new HashSet<>();
	private String template;
	private boolean showHeader = true;
	private boolean showFooter = true;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}

	public Set<String> getPlaceHolders() {
		return placeHolders;
	}
	public void setPlaceHolders(Set<String> placeholders) {
		this.placeHolders = placeholders;
	}
	public String getTemplate() {
		return template;
	}
	public void setTemplate(String template) {
		this.template = template;
	}
	public boolean isShowHeader() {
		return showHeader;
	}
	public void setShowHeader(boolean showHeader) {
		this.showHeader = showHeader;
	}
	public boolean isShowFooter() {
		return showFooter;
	}
	public void setShowFooter(boolean showFooter) {
		this.showFooter = showFooter;
	}
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-catalog-search',
  templateUrl: './catalog-search.component.html',
  styleUrls: ['./catalog-search.component.css']
})
export class CatalogSearchComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package com.microsoft.bingads.v12.api.test.entities.bid_suggestion_data.read;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({BulkKeywordBidSuggestionReadFromRowValuesBidTest.class,
    BulkKeywordBidSuggestionReadFromRowValuesTextTest.class})
public class BulkKeywordBidSuggestionReadTests {

}


text:
from . import AWSObject, AWSProperty
from .validators import boolean, integer

class Cluster(AWSObject):
    resource_type = "AWS::Redshift::Cluster"

    props = {
        'AllowVersionUpgrade': (boolean, False),
        'AutomatedSnapshotRetentionPeriod': (integer, False),
        'AvailabilityZone': (basestring, False),
        'ClusterParameterGroupName': (basestring, False),
        'ClusterSecurityGroups': (list, False),
        'ClusterSubnetGroupName': (basestring, False),
        'ClusterType': (basestring, True),
        'ClusterVersion': (basestring, False),
        'DBName': (basestring, True),
        'ElasticIp': (basestring, False),
        'Encrypted': (boolean, False),
        'HsmClientCertificateIdentifier': (basestring, False),
        'HsmConfigurationIdentifier': (basestring, False),
        'KmsKeyId': (basestring, False),
        'MasterUsername': (basestring, True),
        'MasterUserPassword': (basestring, True),
        'NodeType': (basestring, True),
        'NumberOfNodes': (integer, False),  # Conditional
        'OwnerAccount': (basestring, False),
        'Port': (integer, False),
        'PreferredMaintenanceWindow': (basestring, False),
        'PubliclyAccessible': (boolean, False),
        'SnapshotClusterIdentifier': (basestring, False),
        'SnapshotIdentifier': (basestring, False),
        'VpcSecurityGroupIds': (list, False),
    }

class AmazonRedshiftParameter(AWSProperty):
    props = {
        'ParameterName': (basestring, True),
        'ParameterValue': (basestring, True),
    }

class ClusterParameterGroup(AWSObject):
    resource_type = "AWS::Redshift::ClusterParameterGroup"

    props = {
        'Description': (basestring, True),
        'ParameterGroupFamily': (basestring, True),
        'Parameters': ([AmazonRedshiftParameter], False),
    }

class ClusterSecurityGroup(AWSObject):
    resource_type = "AWS::Redshift::ClusterSecurityGroup"

    props = {
        'Description': (basestring, True),
    }

class ClusterSecurityGroupIngress(AWSObject):
    resource_type = "AWS::Redshift::ClusterSecurityGroupIngress"

    props = {
        'ClusterSecurityGroupName': (basestring, True),
        'CIDRIP': (basestring, False),
        'EC2SecurityGroupName': (basestring, False),
        'EC2SecurityGroupOwnerId': (basestring, False),
    }

class ClusterSubnetGroup(AWSObject):
    resource_type = "AWS::Redshift::ClusterSubnetGroup"

    props = {
        'Description': (basestring, True),
        'SubnetIds': (list, True),
    }


text:
from calculator import Calls
from calculator import HandResult
from calculator import OrderBy
from calculator import Board
from calculator import Calculate
from calculator import TeamSummary
from io import BytesIO
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
from openpyxl.styles import colors
from openpyxl.styles import fills
from openpyxl.writer.excel import save_virtual_workbook
from openpyxl import load_workbook
import csv

def ReadXlsxInput(filename):
  """ Reads input from an Xlsx file.

  Input file must have a sheet titled "Team Names" and sheet titled "Raw Hand
  Scores". This code will read the first continuous block of hand records,
  stopping at the first blank line.

  Args:
    filename: path to the input file.

  Returns:
    A tuple (input wb object,
             list of Boards from the input in no defined order).
  """

  wb = load_workbook(filename)
  board_no_to_hr_list = {}
  teams_sheet = wb["Team Names"]
  raw_input_sheet = wb["Raw Hand Scores"]
  first = True
  for row in raw_input_sheet.rows:
    if not row[0].value:
      break
    if first:
      first = False
    else:
      board_no = int(row[0].value)
      hr_list = board_no_to_hr_list.setdefault(board_no, [])
      # For Tichu calls, need to make sure empty cells default to ''
      for i in xrange(3, 7):
        row[i].value = '' if not row[i].value else row[i].value
      hr_list.append(
        HandResult(board_no, int(row[1].value), int(row[2].value),
                   int(row[7].value), int(row[8].value),
                   Calls(row[3].value, row[4].value, row[5].value,
                         row[6].value)))
  board_list = []
  for k, v in board_no_to_hr_list.items():
    board_list.append(Board(k, v))
  return (wb, board_list)

def SetNumberFormat(cell, format):
  cell.number_format = format

def SetAlignment(cell, alignment):
  cell.alignment = alignment

def SetFill(cell, color):
  cell.fill = PatternFill(fill_type=fills.FILL_SOLID, start_color=color,
                          end_color=color)

def SetFont(cell, bold, color=colors.BLACK):
  cell.font = Font(bold=bold, color=color)

def SetBorder(cell, left=False, right=False, top=False, bottom=False):
  left_border = 'thin' if left else 'none'
  right_border = 'thin' if right else 'none'
  top_border = 'thin' if top else 'none'
  bottom_border = 'thin' if bottom  else 'none'
  cell.border = Border(left=Side(style=left_border),
                       right=Side(style=right_border),
                       top=Side(style=top_border),
                       bottom=Side(style=bottom_border))

def SetColumnStyle(sheet, column, style_fun):
  cell_range = column + '1:' + column + '1000'
  for meta_cell in sheet[cell_range]:
    for cell in meta_cell:
      style_fun(cell)

def SetSheetHeaders(sheet):
  """ Sets the style of the top line in sheet with a frozen top row.

  Args:
    sheet: worksheet in which to set styles.
  """

  for meta_cell in sheet['A1:U1']:
    for cell in meta_cell:
      cell.font = Font(bold=True)
      cell.alignment = Alignment(horizontal='center')
  sheet.freeze_panes = sheet['A2']

SECTION_HEADER_COLOR = '6D9EEB'
def SetSectionHeaderStyleAndText(sheet, row_no, col_no, num_cols, text_list):
  """ Sets the style and header text for a section header.

  Args:
    sheet: worksheet in which to set style and text.
    row_no: row in which section header is set.
    col_no: first column of the header.
    num_cols: number of columns in the header.
    text_list: If text_list has only one member merges the header cells and
      centers the text in it. Otherwise the length of text_list must be the
      size of num_cols, and each column is populated with the corresponding text
      in text_list.
  """

  assert(len(text_list) == num_cols or len(text_list) == 1)
  for col in xrange(col_no, col_no + num_cols):
    cell = sheet.cell(row=row_no, column=col)
    SetFill(cell, SECTION_HEADER_COLOR)
    SetAlignment(cell, Alignment(horizontal='center'))
    SetFont(cell, True, color=colors.WHITE)

    if len(text_list) > 1:
      if col == col_no:
        SetBorder(cell, True, False, True, True)
      elif col == col_no + num_cols:
        SetBorder(cell, False, True, True, True)
      else:
        SetBorder(cell, False, False, True, True)
      cell.value = text_list[col-col_no]

  if len(text_list) == 1:
    cell = sheet.cell(row=row_no, column = col_no);
    cell.value = text_list[0]
    sheet.merge_cells(start_row=row_no, start_column=col_no, end_row=row_no,
                      end_column=num_cols)
    SetBorder(cell, True, True, True, True)

def SetDataTableStyle(sheet, start_row, start_col, num_rows, num_cols,
                      color=None):
  """ Sets the style and border around a data table.

  Args:
    sheet: worksheet in which to set style.
    start_row: row with the first set of data.
    start_col: column with the first set of data.
    num_rows: number of rows in the dataset.
    num_cols: number of columns in the datast.
    color: if set - all cells will be filled with color.
  """

  # Set the alignment to be 'right' everywhere but the headers.
  for row_no in xrange(start_row, start_row + num_rows):
    for col_no in xrange(start_col, num_cols + start_col):
      SetAlignment(sheet.cell(column=col_no, row=row_no),
                   Alignment(horizontal='right'))

  # Fill in right and left borders on all rows but the last one.
  for row in xrange(start_row, start_row + num_rows - 1):
    SetBorder(sheet.cell(row=row, column=start_col + num_cols - 1),
              False, True, False, False)
    SetBorder(sheet.cell(row=row, column=start_col), True, False, False, False)

  # Fill in bottom border on the last row for all columns but the first and
  # last.
  for col in xrange(start_col + 1, num_cols + start_col - 1):
    SetBorder(sheet.cell(row=start_row + num_rows - 1, column=col),
        False, False, False, True)

  # Fill in broders of bottom corners.
  SetBorder(sheet.cell(row=start_row + num_rows - 1,
                       column=start_col + num_cols - 1),
            False, True, False, True)
  SetBorder(sheet.cell(row=start_row + num_rows - 1, column=start_col),
            True, False, False, True)

  if color:
    for row in xrange(start_row, start_row + num_rows):
      for col in xrange(start_col, num_cols + start_col):
        SetFill(sheet.cell(row=row, column=col), color)

SUMMARY_TABLE_OFFSET = 3
SUMMARY_TABLE_COLOR = 'FCEAD8'
RANK_TEXT = "Rank"
TEAM_TEXT = "Team"
BOARD_NO_TEXT = "Board No"
MPS_TEXT = "MPs"
RPS_TEXT = "RPs"
LPS_TEXT = "LPs"
APS_TEXT = "APs"
SIT_OUT_BONUS_TEXT = "Sit-out Bonus"

def WriteXlsxAggressivenessSummaries(max_rounds, scores, sheet):
  """ Writes a summary of play by aggressiveness to sheet.

  Two main components of the sheet. Starting at column 1, there will be a list
  of data tables for each team, with the aggressiveness points for each
  board in order of descending aggressiveness. To the right on top of the page
  will be a list of all teams ranked by total aggressiveness.

  Args:
    max_rounds: Max number of rounds expected for each team. Teams that played
        fewer rounds will have an extra field with a bonus sit-out offset.
    scores: TeamSummaries listed in decreasing order of aggressiveness.
    sheet: sheet in which the summaries will be written.
  """

  sheet.title = 'Summary by Agressiveness'

  headers = [BOARD_NO_TEXT, APS_TEXT]
  sheet.append(headers)
  SetSheetHeaders(sheet)

  # Write a table for each team represented in scores.
  row_no = 1
  for s in scores:
    row_no += 1
    SetSectionHeaderStyleAndText(sheet, row_no, 1, len(headers),
                                 ["Team {0}".format(s.team_no)])
    start_row = row_no + 1
    for key in sorted(s.board_aps.keys()):
      row_no += 1
      row_dict = [key, s.board_aps[key]]
      for col_no in range(1, len(headers) + 1):
        sheet.cell(column=col_no, row=row_no, value = row_dict[col_no - 1])
    # This is kind of a hack, but back calculate how much was added from the
    # sit-out bonus.
    if len(s.board_aps) < max_rounds:
      row_no += 1
      row_dict = [SIT_OUT_BONUS_TEXT,
                  s.aps - s.aps * len(s.board_aps) / max_rounds]
      for col_no in range(1, len(headers) + 1):
        sheet.cell(column=col_no, row=row_no, value = row_dict[col_no - 1])
        SetAlignment(sheet.cell(column=col_no, row=row_no),
                     Alignment(horizontal='right'))

    SetDataTableStyle(sheet, start_row, 1,
                      len(s.board_aps) + 1 if len(s.board_aps) < max_rounds else len(s.board_aps),
                      len(headers))
    # Space before the next set of scores.
    sheet.append([])
    row_no += 1

  # Write a summary table with just the totals.
  summary_header = [RANK_TEXT, TEAM_TEXT, APS_TEXT]
  SetSectionHeaderStyleAndText(sheet, 2, len(headers) + SUMMARY_TABLE_OFFSET,
                               len(summary_header), summary_header)
  for i in range(len(scores)):
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET, row=3 + i,
       value = i + 1)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 1, row=3 + i,
       value = scores[i].team_no)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 2, row=3 + i,
       value = scores[i].aps)
  SetDataTableStyle(sheet, 3, len(headers) + SUMMARY_TABLE_OFFSET, len(scores),
                    len(summary_header), SUMMARY_TABLE_COLOR)

  # Stylistic things to make floats fit into columns.
  SetColumnStyle(sheet, 'A', lambda x: SetNumberFormat(x, '0'))
  SetColumnStyle(sheet, 'B', lambda x: SetNumberFormat(x, '0.0'))
  SetColumnStyle(sheet, 'G', lambda x: SetNumberFormat(x, '0.0'))
  sheet.column_dimensions['A'].width = 13
  sheet.column_dimensions['B'].width = 10
  sheet.row_dimensions[1].height = 15

def WriteXlsxTeamSummaries(max_rounds, scores, sheet):
  """ Writes a summary of play for each team to sheet.

  Two main components of the sheet. Starting at column 1, there will be a list
  of data tables for each team, with the MPs and RPs for each board in order of
  descending MPs. To the right on top of the page will be a list of all teams
  ranked by total MPs.

  Args:
    max_rounds: Max number of rounds expected for each team. Teams that played
        fewer rounds will have an extra field with a bonus sit-out offset.
    scores: TeamSummaries listed in decreasing order of aggressiveness.
    sheet: sheet in which the summaries will be written.
  """

  sheet.title = 'Summary by Team'

  headers = [BOARD_NO_TEXT, MPS_TEXT, RPS_TEXT, LPS_TEXT]
  sheet.append(headers)
  SetSheetHeaders(sheet)

  # Write a table for each team represented in scores.
  row_no = 1
  for s in scores:
    row_no += 1
    SetSectionHeaderStyleAndText(
        sheet, row_no, 1, len(headers),
        ["Place {1}. Team {0}: MPs {2:.1f} RPs {3:.2f} LPs {4:.2f}".format(
            s.team_no, s.mp_rank, s.mps, s.rps, s.lps)])
    start_row = row_no + 1
    keys = sorted(s.board_mps.keys())
    for key in keys:
      row_no+= 1
      row_dict = {BOARD_NO_TEXT: key, MPS_TEXT: s.board_mps[key],
                  RPS_TEXT: s.board_rps[key], LPS_TEXT: s.board_lps[key]}
      for col_no in xrange(1, len(headers) + 1):
        sheet.cell(column=col_no, row=row_no, value=row_dict[headers[col_no - 1]])

    if len(keys) < max_rounds:
      row_no += 1
      row_dict = {BOARD_NO_TEXT : SIT_OUT_BONUS_TEXT,
                  MPS_TEXT: s.mps - s.mps * len(keys) / max_rounds,
                  RPS_TEXT: s.rps - s.rps * len(keys) / max_rounds,
                  LPS_TEXT: s.lps - s.lps * len(keys) / max_rounds}
      for col_no in xrange(1, len(headers) + 1):
        sheet.cell(column=col_no, row=row_no,
                   value=row_dict[headers[col_no - 1]])
        SetAlignment(sheet.cell(column=col_no, row=row_no),
                     Alignment(horizontal='right'))
    SetDataTableStyle(sheet, start_row, 1,
                      len(keys) + 1 if len(keys) < max_rounds else len(keys),
                      len(headers))
    row_no += 1
    sheet.append([])

  # Write a summary table with just the total scores.
  summary_header = [RANK_TEXT, TEAM_TEXT, MPS_TEXT, RPS_TEXT, LPS_TEXT]
  SetSectionHeaderStyleAndText(sheet, 2, len(headers) + SUMMARY_TABLE_OFFSET,
                               len(summary_header), summary_header)
  for i in range(len(scores)):
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET, row=3 + i,
       value = i + 1)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 1, row=3 + i,
       value = scores[i].team_no)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 2, row=3 + i,
       value = scores[i].mps)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 3, row=3 + i,
       value = scores[i].rps)
    sheet.cell(column=len(headers) + SUMMARY_TABLE_OFFSET + 4, row=3 + i,
       value = scores[i].lps)
  SetDataTableStyle(sheet, 3, len(headers) + SUMMARY_TABLE_OFFSET, len(scores),
                    len(summary_header), SUMMARY_TABLE_COLOR)

  # Stylistic things to make floats fit into columns.
  SetColumnStyle(sheet, 'A', lambda x: SetNumberFormat(x, '0'))
  SetColumnStyle(sheet, 'B', lambda x: SetNumberFormat(x, '0.0'))
  SetColumnStyle(sheet, 'C', lambda x: SetNumberFormat(x, '0.00'))
  SetColumnStyle(sheet, 'D', lambda x: SetNumberFormat(x, '0'))
  SetColumnStyle(sheet, 'H', lambda x: SetNumberFormat(x, '0'))
  SetColumnStyle(sheet, 'I', lambda x: SetNumberFormat(x, '0.0'))
  SetColumnStyle(sheet, 'J', lambda x: SetNumberFormat(x, '0.00'))
  SetColumnStyle(sheet, 'K', lambda x: SetNumberFormat(x, '0'))
  sheet.column_dimensions['A'].width = 13
  sheet.column_dimensions['B'].width = 10
  sheet.column_dimensions['C'].width = 10
  sheet.column_dimensions['D'].width = 10
  sheet.row_dimensions[1].height = 15

def WriteXlsxBoardSummaries(board_list, sheet):
  """ Writes a summary of play organized by board.

  Args:
    board_list: A list of Board objects in ascending order.
    sheet: sheet in which the summaries will be written.
  """

  sheet.title = 'Summary by Board'

  NS_TEAM_TEXT = 'NS Team'
  EW_TEAM_TEXT = 'EW Team'
  CALLS_TEXT = 'Calls'
  NS_SCORE_TEXT = 'NS Score'
  EW_SCORE_TEXT = 'EW Score'
  NS_MPS_TEXT = 'NS MPs'
  EW_MPS_TEXT = 'EW MPs'
  NS_RPS_TEXT = 'NS RPs'
  EW_RPS_TEXT = 'EW RPs'
  NS_LPS_TEXT = 'NS LPs'
  EW_LPS_TEXT = 'EW LPs'
  NS_APS_TEXT = 'NS APs'
  EW_APS_TEXT = 'EW APs'

  headers = [NS_TEAM_TEXT, EW_TEAM_TEXT, CALLS_TEXT, NS_SCORE_TEXT,
             EW_SCORE_TEXT, NS_MPS_TEXT, EW_MPS_TEXT, NS_RPS_TEXT,
             EW_RPS_TEXT, NS_LPS_TEXT, EW_LPS_TEXT, NS_APS_TEXT, EW_APS_TEXT]
  sheet.append(headers)
  SetSheetHeaders(sheet)

  row_no = 1
  for b in board_list:
    row_no += 1
    SetSectionHeaderStyleAndText(sheet, row_no, 1, len(headers),
                                 ['Board {0}'.format(b._board_no)])
    start_row = row_no + 1
    for bs in b._board_score:
      row_no += 1
      row_dict = { NS_TEAM_TEXT: bs._hr.ns_pair_no(),
                   EW_TEAM_TEXT: bs._hr.ew_pair_no(),
                   CALLS_TEXT: str(bs._hr.calls()),
                   NS_SCORE_TEXT: bs._hr.ns_score(),
                   EW_SCORE_TEXT: bs._hr.ew_score(),
                   NS_MPS_TEXT: "{0:.1f}".format(bs.ns_mps),
                   EW_MPS_TEXT: "{0:.1f}".format(bs.ew_mps),
                   NS_RPS_TEXT: "{0:.2f}".format(bs.ns_rps),
                   EW_RPS_TEXT: "{0:.2f}".format(bs.ew_rps),
                   NS_LPS_TEXT: "{0:.2f}".format(bs.ns_lps),
                   EW_LPS_TEXT: "{0:.2f}".format(bs.ew_lps),
                   NS_APS_TEXT: "{0}".format(bs.ns_aps),
                   EW_APS_TEXT: "{0}".format(bs.ew_aps),}
      for col_no in range(1, len(headers)+1):
        sheet.cell(column=col_no, row=row_no,
                   value = row_dict[headers[col_no - 1]])
    SetDataTableStyle(sheet, start_row, 1, len(b._board_score), len(headers))
    row_no += 1
    sheet.append([])

  sheet.column_dimensions['C'].width = 20

def WriteHandNames(name_list, sheet):
  ''' Writes down players names for reference.
  Args:
    hand_list: List of pairs of hand in team numbr order. If a player name is
               unknown, must be None.
  '''
  sheet.append(["Team"])
  for i in range(len(name_list)):
    sheet.append([str(i + 1), name_list[i][0], name_list[i][1]])
  SetSheetHeaders(sheet)

  for row_no in xrange(2, len(name_list) + 2):
    cell = sheet.cell(row=row_no, column=1)
    SetAlignment(cell, Alignment(horizontal='right'))

def WriteXlsxRawScores(board_list, sheet):
  """ Writes down raw scores.

  Args:
    board_list: A list of Board objects in ascending order.
    sheet: sheet in which the summaries will be written.
  """

  sheet.title =  'Raw Hand Scores'

  BOARD_TEXT = 'Board'
  NS_TEAM_TEXT = 'NS Team'
  EW_TEAM_TEXT = 'EW Team'
  N_CALL = "N Call"
  S_CALL = "S Call"
  E_CALL = "E Call"
  W_CALL = "W Call"
  CALLS_TEXT = 'Calls'
  NS_SCORE_TEXT = 'NS Score'
  EW_SCORE_TEXT = 'EW Score'

  headers = [BOARD_TEXT, NS_TEAM_TEXT, EW_TEAM_TEXT, N_CALL, S_CALL,
             E_CALL, W_CALL, NS_SCORE_TEXT, EW_SCORE_TEXT]
  sheet.append(headers)
  SetSheetHeaders(sheet)

  row_no = 1
  for b in board_list:
    for bs in b._board_score:
      row_no += 1
      row_dict = { BOARD_TEXT: b._board_no,
                   NS_TEAM_TEXT: bs._hr.ns_pair_no(),
                   EW_TEAM_TEXT: bs._hr.ew_pair_no(),
                   N_CALL: bs._hr.calls().n_call(),
                   S_CALL: bs._hr.calls().s_call(),
                   E_CALL: bs._hr.calls().e_call(),
                   W_CALL: bs._hr.calls().w_call(),
                   NS_SCORE_TEXT: bs._hr.ns_score(),
                   EW_SCORE_TEXT: bs._hr.ew_score(),}
      for col_no in range(1, len(headers)+1):
          sheet.cell(column=col_no, row=row_no,
                     value = row_dict[headers[col_no - 1]])

def CopySheet(from_sheet, to_sheet):
  """ Copies all data from from_sheet to to_sheet. """

  for row in from_sheet.rows:
    row_list = []
    for cell in row:
      row_list.append(cell.value)
    to_sheet.append(row_list)

def WriteResultsToXlsx(max_rounds, mp_scores, ap_scores, board_list,
                       name_list=None, input_wb=None):
  """ Creates an Xlx workbook with all the information about a tournament.

      Args:
        max_rounds: Max number of rounds expected for each team. Teams that
          played fewer rounds have their scores adjusted to match the maximum
          possible number of rounds played.
        mp_scores: TeamSummary objects ordered in descending total MP order.
        ap_scores: TeamSummary objects ordered in descending total AP order.
        board_list: List of boards in ascending board number order.
        name_list: List of player name pairs in ascending team number order.
          If no name exists for a player, must be None.
        input_wb: The input workbook as it was read in. Used to copy raw hand
          and team details into the output workbook. If None, raw scores and
          team details will not be present in the output.
      Returns:
        formatted workbook
  """

  wb = Workbook()
  OrderBy(mp_scores, "MP")
  WriteXlsxTeamSummaries(max_rounds, mp_scores, wb.worksheets[0])
  board_sheet = wb.create_sheet()
  WriteXlsxBoardSummaries(board_list, board_sheet)
  aggro_sheet = wb.create_sheet()
  OrderBy(ap_scores, "AP")
  WriteXlsxAggressivenessSummaries(max_rounds, ap_scores, aggro_sheet)
  raw_scores_sheet = wb.create_sheet()
  WriteXlsxRawScores(board_list, raw_scores_sheet)
  # Copy the input sheets into the newly created workbook.
  TEAM_NAMES_TEXT = "Team Names"
  if name_list:
      name_sheet = wb.create_sheet(TEAM_NAMES_TEXT)
      WriteHandNames(name_list, name_sheet)
  elif input_wb:
      CopySheet(input_wb[TEAM_NAMES_TEXT], wb.create_sheet(TEAM_NAMES_TEXT))
      SetSheetHeaders(wb[TEAM_NAMES_TEXT])

  return wb

def OutputWorkbookAsBytesIO(wb):
  """ Writes the Xlx workbook to a BytesIO stream. """
  return BytesIO(save_virtual_workbook(wb))


text:
package net.kyori.adventure.nbt;

import java.util.stream.Stream;
import net.kyori.examination.ExaminableProperty;
import org.jetbrains.annotations.Debug;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * A binary tag holding a {@link String} value.
 *
 * @since 4.0.0
 */
public interface StringBinaryTag extends BinaryTag {
  /**
   * Creates a binary tag holding a {@link String} value.
   *
   * @param value the value
   * @return a binary tag
   * @since 4.0.0
   */
  static @NotNull StringBinaryTag of(final @NotNull String value) {
    return new StringBinaryTagImpl(value);
  }

  @Override
  default @NotNull BinaryTagType<StringBinaryTag> type() {
    return BinaryTagTypes.STRING;
  }

  /**
   * Gets the value.
   *
   * @return the value
   * @since 4.0.0
   */
  @NotNull String value();
}

@Debug.Renderer(text = "\"\\\"\" + this.value + \"\\\"\"", hasChildren = "false")
final class StringBinaryTagImpl extends AbstractBinaryTag implements StringBinaryTag {
  private final String value;

  StringBinaryTagImpl(final String value) {
    this.value = value;
  }

  @Override
  public @NotNull String value() {
    return this.value;
  }

  @Override
  public boolean equals(final @Nullable Object other) {
    if (this == other) return true;
    if (other == null || this.getClass() != other.getClass()) return false;
    final StringBinaryTagImpl that = (StringBinaryTagImpl) other;
    return this.value.equals(that.value);
  }

  @Override
  public int hashCode() {
    return this.value.hashCode();
  }

  @Override
  public @NotNull Stream<? extends ExaminableProperty> examinableProperties() {
    return Stream.of(ExaminableProperty.of("value", this.value));
  }
}


text:
#ifndef OXS_ENCRYPTION_H
#define OXS_ENCRYPTION_H

/**
  * @file oxs_encryption.h
  * @brief Provides data encryption and decryption functionalities of the OMXMLSec.
  */

/**
 * @defgroup oxs_encryption Encryption
 * @ingroup oxs
 * @{
 */
#include <axis2_defines.h>
#include <oxs_ctx.h>
#include <oxs_asym_ctx.h>
#include <axutil_env.h>
#include <axiom_node.h>
#include <axiom_element.h>
#include <axutil_qname.h>

#ifdef __cplusplus
extern "C"
{
#endif
    /**
     * En/Decrypts given data buffer depending on the information avalable in the encryption context using
     * a symmetric key.
     * The resulted data will be placed on the result buffer.
     * Data are not valid only if the method returns 	AXIS2_SUCCESS
     * @enc_ctx pointer to the OMXMLSec symmetric encryption context struct
     * @env pointer to environment struct
     * @input the input buffer
     * @result the ouput or the ressulted data buffer
     * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
     */
    AXIS2_EXTERN  axis2_status_t AXIS2_CALL
    oxs_encryption_symmetric_crypt(const axutil_env_t *env,
                                   oxs_ctx_t * enc_ctx,
                                   oxs_buffer_t *input,
                                   oxs_buffer_t *result);

    /**
     * En/Decrypts given data buffer deoending on the information avalable in the encryption context using an
     * asymmetric key, which can be a publik key extracted from a certificate or a private key.
     * The resulted data will be placed on the result buffer.
     * Data are not valid only if the method returns 	AXIS2_SUCCESS
     * @asym_ctx pointer to the OMXMLSec asymmetric encryption context struct
     * @env pointer to environment struct
     * @input the input buffer
     * @result the ouput or the ressulted data buffer
     * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
     */
    AXIS2_EXTERN  axis2_status_t AXIS2_CALL
    oxs_encryption_asymmetric_crypt(const axutil_env_t *env,
                                    oxs_asym_ctx_t * asym_ctx,
                                    oxs_buffer_t *input,
                                    oxs_buffer_t *result);

    /** @} */
#ifdef __cplusplus
}
#endif

#endif                          /* OXS_ENCRYPTION_H */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/util
	http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<bean id="server.exchanger.tracer.si" class="com.sissi.server.exchange.impl.MongoTracerContext">
		<constructor-arg ref="server.exchanger.tracer.si.config" />
	</bean>
	<bean id="server.exchanger.tracer.si.config" class="com.sissi.config.impl.MongoProxyConfig">
		<constructor-arg ref="mongo" />
		<constructor-arg index="1" value="${mongo.db}" />
		<constructor-arg index="2" value="${mongo.collection.exchanger.tracer}" />
	</bean>
</beans>


text:
Template.export.onRendered( function() {
    $('#export-panel-content').collapse('toggle');
});

Template.export.events({
    'click .export-data' (event, template) {
        var expBtn = $(event.target);
        expBtn.button('loading');

        var codes = Codes.find().map(function(q) {
                return {
                    code: q.code,
                    company: q.name,//name: q.name,
                    industry: q.description,//description: q.description,
                    seen: q.seen,
                }
        });
            //console.log(questions);
        var result = json2csv(codes);
//        var result = JSON.stringify(codes);

//        console.log(result);
        var blob = new Blob([result], {type: "text/plain;charset=utf-8"});
        var d = new Date();
        saveAs(blob, d.getDate()+'-'+(d.getMonth()+1)+'-'+d.getFullYear()+".csv");
        expBtn.button('reset');
    }

});


text:
namespace BudgetAnalyser.Engine
{
    /// <summary>
    ///     Describes an interface that will allow consumers to detect data state changes compared with other instances of the
    ///     same type.
    /// </summary>
    public interface IDataChangeDetection
    {
        /// <summary>
        ///     Calcuates a hash that represents a data state for the current instance.  When the data state changes the hash will
        ///     change.
        /// </summary>
        long SignificantDataChangeHash();
    }
}


text:
"""
Python money class with optional CLDR-backed locale-aware formatting
and an extensible currency exchange solution.
"""
from .money import Money, XMoney
from .exchange import xrates

# RADAR: version
__version__ = '1.4.0-dev'


text:
package br.com.alinesoftware.model.domain.produto;

public class Produto {

	private String descricao;
	private Double valorCusto;
	private Double valorVenda;

}


text:
'''
This module contains methods to verify ELF files and help extract data
from ELF files such as the architecture, sections, symbols, and so on.

Note: some vendors run sstrip on the binaries. There are versions of the
sstrip tool that are buggy and create files with a section header that is
actually incorrect and will for example confuse readelf:

https://dev.openwrt.org/ticket/6847
https://bugs.busybox.net/show_bug.cgi?id=729
'''

import sys
import os
import subprocess
import os.path
import struct
import math
import tempfile
import re

# information about ELF was collected from the following places:
#
# https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
# https://docs.oracle.com/cd/E19683-01/816-1386/chapter6-43405/index.html
# https://refspecs.linuxbase.org/elf/elf.pdf
# https://android.googlesource.com/platform/art/+/master/runtime/elf.h
#
# mappings of architectures to names
architecturemapping = { 0: None
                     , 1: "AT&T WE 32100"
                     , 2: "SPARC"
                     , 3: "Intel 80386"
                     , 4: "Motorola 68000"
                     , 5: "Motorola 88000"
                     , 6: "Intel 80486"
                     , 7: "Intel 80860"
                     , 8: "MIPS R3000"
                     , 9: "IBM System/370"
                     , 10: "MIPS RS3000 Little-endian"
                     , 15: "Hewlett-Packard PA-RISC"
                     , 17: "Fujitsu VPP500"
                     , 18: "SPARC32+" # // Enhanced instruction set SPARC
                     , 19: "Intel 80960"
                     , 20: "PowerPC"
                     , 21: "PowerPC64"
                     , 22: "IBM System/390"
                     , 23: "IBM SPU/SPC"
                     , 36: "NEC V800"
                     , 37: "Fujitsu FR20"
                     , 38: "TRW RH-32"
                     , 39: "Motorola RCE"
                     , 40: "ARM"
                     , 41: "DEC Alpha"
                     , 42: "Hitachi SH"
                     , 43: "SPARC V9"
                     , 44: "Siemens TriCore"
                     , 45: "Argonaut RISC Core"
                     , 46: "Hitachi H8/300"
                     , 47: "Hitachi H8/300H"
                     , 48: "Hitachi H8S"
                     , 49: "Hitachi H8/500"
                     , 50: "Intel IA-64"
                     , 51: "Stanford MIPS-X"
                     , 52: "Motorola ColdFire"
                     , 53: "Motorola M68HC12"
                     , 54: "Fujitsu MMA Multimedia Accelerator"
                     , 55: "Siemens PCP"
                     , 56: "Sony nCPU embedded RISC processor"
                     , 57: "Denso NDR1 microprocessor"
                     , 58: "Motorola Star*Core processor"
                     , 59: "Toyota ME16 processor"
                     , 60: "STMicroelectronics ST100 processor"
                     , 61: "Advanced Logic Corp. TinyJ"
                     , 62: "AMD X86-64"
                     , 63: "Sony DSP Processor"
                     , 64: "Digital Equipment Corp. PDP-10"
                     , 65: "Digital Equipment Corp. PDP-11"
                     , 66: "Siemens FX66 microcontroller"
                     , 67: "STMicroelectronics ST9+ 8/16 bit microcontroller"
                     , 68: "STMicroelectronics ST7 8-bit microcontroller"
                     , 69: "Motorola MC68HC16 Microcontroller"
                     , 70: "Motorola MC68HC11 Microcontroller"
                     , 71: "Motorola MC68HC08 Microcontroller"
                     , 72: "Motorola MC68HC05 Microcontroller"
                     , 73: "Silicon Graphics SVx"
                     , 74: "STMicroelectronics ST19 8-bit microcontroller"
                     , 75: "Digital VAX"
                     , 76: "ETRAX CRIS"
                     , 77: "Javelin"
                     , 78: "Element 14 64-bit DSP Processor"
                     , 79: "ZSP LSI Logic 16-bit DSP Processor"
                     , 80: "MMIX (Donald Knuth's educational 64-bit processor)"
                     , 81: "Harvard University machine-independent object files"
                     , 82: "SiTera Prism"
                     , 83: "Atmel AVR 8-bit microcontroller"
                     , 84: "Fujitsu FR30"
                     , 85: "Mitsubishi D10V"
                     , 86: "Mitsubishi D30V"
                     , 87: "NEC v850"
                     , 88: "Mitsubishi M32R"
                     , 89: "Matsushita MN10300"
                     , 90: "Matsushita MN10200"
                     , 91: "picoJava"
                     , 92: "OpenRISC 32-bit embedded processor"
                     , 93: "ARC International ARCompact processor"
                     , 94: "Tensilica Xtensa Architecture"
                     , 95: "Alphamosaic VideoCore processor"
                     , 96: "Thompson Multimedia General Purpose Processor"
                     , 97: "National Semiconductor 32000 series"
                     , 98: "Tenor Network TPC processor"
                     , 99: "Trebia SNP 1000 processor"
                     , 100: "STMicroelectronics ST200"
                     , 101: "Ubicom IP2xxx"
                     , 102: "MAX Processor"
                     , 103: "National Semiconductor CompactRISC microprocessor"
                     , 104: "Fujitsu F2MC16"
                     , 105: "Texas Instruments embedded microcontroller msp430"
                     , 106: "Analog Devices Blackfin (DSP) processor"
                     , 107: "S1C33 Family of Seiko Epson processors"
                     , 108: "Sharp embedded microprocessor"
                     , 109: "Arca RISC Microprocessor"
                     , 110: "MPRC UniCore"
                     , 111: "eXcess: 16/32/64-bit configurable embedded CPU"
                     , 112: "Icera Semiconductor Inc. Deep Execution Processor"
                     , 113: "Altera Nios II soft-core processor"
                     , 114: "National Semiconductor CompactRISC CRX"
                     , 115: "Motorola XGATE embedded processor"
                     , 116: "Infineon C16x/XC16x processor"
                     , 117: "Renesas M16C series microprocessors"
                     , 118: "Microchip Technology dsPIC30F Digital Signal Controller"
                     , 119: "Freescale Communication Engine RISC core"
                     , 120: "Renesas M32C series microprocessors"
                     , 131: "Altium TSK3000 core"
                     , 132: "Freescale RS08 embedded processor"
                     , 133: "Analog Devices SHARC"
                     , 134: "Cyan Technology eCOG2 microprocessor"
                     , 135: "Sunplus S+core7 RISC processor"
                     , 136: "New Japan Radio (NJR) 24-bit DSP Processor"
                     , 137: "Broadcom VideoCore III processor"
                     , 138: "RISC processor for Lattice FPGA architecture"
                     , 139: "Seiko Epson C17"
                     , 140: "Texas Instruments TMS320C6000"
                     , 141: "Texas Instruments TMS320C2000"
                     , 142: "Texas Instruments TMS320C55x"
                     , 160: "STMicroelectronics 64bit VLIW Data Signal Processor"
                     , 161: "Cypress M8C microprocessor"
                     , 162: "Renesas R32C series microprocessors"
                     , 163: "NXP Semiconductors TriMedia"
                     , 164: "Qualcomm Hexagon processor"
                     , 165: "Intel 8051"
                     , 166: "STMicroelectronics STxP7x RISC processor"
                     , 167: "Andes Technology compact code size embedded RISC"
                     , 168: "Cyan Technology eCOG1X"
                     , 169: "Dallas Semiconductor MAXQ30 Core Micro-controllers"
                     , 170: "New Japan Radio (NJR) 16-bit DSP Processor"
                     , 171: "M2000 Reconfigurable RISC Microprocessor"
                     , 172: "Cray Inc. NV2 vector architecture"
                     , 173: "Renesas RX"
                     , 174: "Imagination Technologies META"
                     , 175: "MCST Elbrus"
                     , 176: "Cyan Technology eCOG16"
                     , 177: "National Semiconductor CompactRISC CR16"
                     , 178: "Freescale Extended Time Processing Unit"
                     , 179: "Infineon Technologies SLE9X core"
                     , 180: "Intel L10M"
                     , 181: "Intel K10M"
                     , 183: "ARM AArch64"
                     , 185: "Atmel Corporation AVR32"
                     , 186: "STMicroeletronics STM8"
                     , 187: "Tilera TILE64"
                     , 188: "Tilera TILEPro"
                     , 190: "NVIDIA CUDA architecture"
                     , 191: "Tilera TILE-Gx"
                     , 192: "CloudShield"
                     , 193: "KIPO-KAIST Core-A 1st generation"
                     , 194: "KIPO-KAIST Core-A 2nd generation"
                     , 195: "Synopsys ARCompact V2"
                     , 196: "Open8 8-bit RISC soft processor core"
                     , 197: "Renesas RL78"
                     , 198: "Broadcom VideoCore V processor"
                     , 199: "Renesas 78KOR"
                     , 200: "Freescale 56800EX"
                     }

# read the architecture of a (validated) ELF file
def getArchitecture(filename, tags):
    # return if the file is not a valid ELF file
    if not 'elf' in tags:
        return
    elffile = open(filename, 'rb')

    # first read the ELF header
    elffile.seek(0)
    elfbytes = elffile.read(64)

    # then check if this is a little endian or big endian binary
    littleendian = True
    if struct.unpack('>B', elfbytes[5])[0] != 1:
        littleendian = False

    # extract the machine type from the right place in the binary
    if littleendian:
        elfmachinebyte = struct.unpack('<H', elfbytes[0x12:0x12+2])[0]
    else:
        elfmachinebyte = struct.unpack('>H', elfbytes[0x12:0x12+2])[0]

    # then look up the machine type in the list of architectures
    if elfmachinebyte in architecturemapping:
        architecture = architecturemapping[elfmachinebyte]
    else:
        architecture = "UNKNOWN"
    elffile.close()
    return architecture

# extract information about a section given a section name
def getSection(filename, sectionname, debug=False):
    (totalelf, elfresult) = parseELF(filename, 0, debug)
    returnsection = None
    if elfresult == None:
        return
    for i in elfresult['sections']:
        if elfresult['sections'][i]['name'] == sectionname:
            returnsection = i
            break
    if returnsection != None:
        return elfresult['sections'][returnsection]

# get all the symbols from an ELF binary.
# This is similar to "readelf -s"
# For most binaries (stripped) this is equivalent to
# getting the dynamic symbol table.
# In case the file has not been stripped this also
# includes the debugging symbols.
def getAllSymbols(filename, debug=False):
    (totalelf, elfresult) = parseELF(filename, 0, debug)
    symres = []
    symbolres = getSymbols(filename, elfresult, debug)
    if symbolres != None:
        symres += symbolres
    symbolres = getDynamicSymbols(filename, elfresult, debug)
    if symbolres != None:
        symres += symbolres
    return symres

# similar to readelf -s but only regular symbols (not dynamic)
# This will only return results on binaries that are not stripped
def getSymbols(filename, elfresult=None, debug=False):
    return getSymbolsAbstraction(filename, 'symbol', elfresult, debug)

# similar to readelf --dyn-syms (just the dynamic section)
def getDynamicSymbols(filename, elfresult=None, debug=False):
    return getSymbolsAbstraction(filename, 'dynamic', elfresult, debug)

# A generic method to get symbols from either the dynamic symbol
# table or the symbol table (non-stripped binaries)
def getSymbolsAbstraction(filename, symboltype, elfresult, debug=False):
    if elfresult == None:
        (totalelf, elfresult) = parseELF(filename, 0, debug)
        if not totalelf:
            return

    symsection = None
    strsection = None
    for i in elfresult['sections']:
        if symboltype == 'dynamic':
            if elfresult['sections'][i]['sectiontype'] == 11:
                symsection = i
        elif symboltype == 'symbol':
            if elfresult['sections'][i]['sectiontype'] == 2:
                symsection = i
        if symboltype == 'dynamic':
            if elfresult['sections'][i]['name'] == '.dynstr':
                if elfresult['sections'][i]['sectiontype'] == 3:
                    strsection = i
        else:
            if elfresult['sections'][i]['name'] == '.strtab':
                if elfresult['sections'][i]['sectiontype'] == 3:
                    strsection = i

    # no need to continue if both the symsection
    # and strsection are None (most likely indicating a corrupt ELF file)
    if symsection == None:
        return

    if strsection == None:
        return

    bit32 = elfresult['bit32']
    littleendian = elfresult['littleendian']

    # first, get the dynamic symbol section
    elffile = open(filename, 'rb')
    elffile.seek(elfresult['sections'][symsection]['sectionoffset'])
    elfbytes = elffile.read(elfresult['sections'][symsection]['sectionsize'])

    # then get the string section from the binary
    elffile.seek(elfresult['sections'][strsection]['sectionoffset'])
    strbytes = elffile.read(elfresult['sections'][strsection]['sectionsize'])
    elffile.close()

    dynamicsymbols = []

    # Then process all the symbol entries.
    # Various pieces of information are extracted, such as type,
    # binding and visibility. The name of the symbol is extracted
    # from the string section using an offset defined in the symbol
    # entry.
    if bit32:
        # for 32 bit binaries each entry takes up 16 bytes
        entrysize = 16
    else:
        # for 64 bit binaries each entry takes up 24 bytes
        entrysize = 24
    for i in xrange(0, len(elfbytes)/entrysize):
        dynsymres = {}
        dynsymres['index'] = i
        if bit32:
            if littleendian:
                st_name = struct.unpack('<I', elfbytes[i*entrysize:i*entrysize+4])[0]
                st_value = struct.unpack('<I', elfbytes[i*entrysize+4:i*entrysize+8])[0]
                st_size = struct.unpack('<I', elfbytes[i*entrysize+8:i*entrysize+12])[0]
                st_info = ord(elfbytes[i*entrysize+12])
                st_other = ord(elfbytes[i*entrysize+13])
                st_shndx = struct.unpack('<H', elfbytes[i*entrysize+14:i*entrysize+16])[0]
            else:
                st_name = struct.unpack('>I', elfbytes[i*entrysize:i*entrysize+4])[0]
                st_value = struct.unpack('>I', elfbytes[i*entrysize+4:i*entrysize+8])[0]
                st_size = struct.unpack('>I', elfbytes[i*entrysize+8:i*entrysize+12])[0]
                st_info = ord(elfbytes[i*entrysize+12])
                st_other = ord(elfbytes[i*entrysize+13])
                st_shndx = struct.unpack('>H', elfbytes[i*entrysize+14:i*entrysize+16])[0]
        else:
            if littleendian:
                st_name = struct.unpack('<I', elfbytes[i*entrysize:i*entrysize+4])[0]
                st_info = ord(elfbytes[i*entrysize+4])
                st_other = ord(elfbytes[i*entrysize+5])
                st_shndx = struct.unpack('<H', elfbytes[i*entrysize+6:i*entrysize+8])[0]
                st_value = struct.unpack('<Q', elfbytes[i*entrysize+8:i*entrysize+16])[0]
                st_size = struct.unpack('<Q', elfbytes[i*entrysize+16:i*entrysize+24])[0]
            else:
                st_name = struct.unpack('>I', elfbytes[i*entrysize:i*entrysize+4])[0]
                st_info = ord(elfbytes[i*entrysize+4])
                st_other = ord(elfbytes[i*entrysize+5])
                st_shndx = struct.unpack('>H', elfbytes[i*entrysize+6:i*entrysize+8])[0]
                st_value = struct.unpack('>Q', elfbytes[i*entrysize+8:i*entrysize+16])[0]
                st_size = struct.unpack('>Q', elfbytes[i*entrysize+16:i*entrysize+24])[0]

        endofname = strbytes.find('\x00', st_name)
        dynsymres['name'] = strbytes[st_name:endofname]
        dynsymres['section'] = st_shndx
        dynsymres['size'] = st_size
        dynsymres['value'] = st_value
        binding = st_info >> 4
        if binding == 0:
            dynsymres['binding'] = 'local'
        elif binding == 1:
            dynsymres['binding'] = 'global'
        elif binding == 2:
            dynsymres['binding'] = 'weak'
        elif binding == 10:
            dynsymres['binding'] = 'unique' # STB_LOOS according to ELF specs, so might be Linux specific
        else:
            # by default ignore, TODO
            dynsymres['binding'] = 'ignore'

        # extract the symbol type
        dyntype = st_info%16
        if dyntype == 0:
            dynsymres['type'] = 'notype'
        elif dyntype == 1:
            # symbol is an object (variable)
            dynsymres['type'] = 'object'
        elif dyntype == 2:
            # symbol is a function
            dynsymres['type'] = 'func'
        elif dyntype == 3:
            # symbol is a section
            dynsymres['type'] = 'section'
        elif dyntype == 4:
            # symbol is a file name
            dynsymres['type'] = 'file'
        elif dyntype == 6:
            dynsymres['type'] = 'tls' # thread local storage
        elif dyntype == 10:
            # symbol is an ifunc (GNU extension)
            dynsymres['type'] = 'ifunc' # STT_LOOS according to ELF specs, so might be Linux specific
        else:
            # by default ignore, TODO
            dynsymres['type'] = 'ignore'

        # extract the visibility
        if st_other & 0x03 == 0:
            dynsymres['visibility'] = 'default'
        elif st_other & 0x03 == 1:
            dynsymres['visibility'] = 'internal'
        elif st_other & 0x03 == 2:
            dynsymres['visibility'] = 'hidden'
        elif st_other & 0x03 == 3:
            dynsymres['visibility'] = 'protected'
        dynsymres['symboltype'] = symboltype
        dynamicsymbols.append(dynsymres)
    return dynamicsymbols

# similar to readelf -d
def getDynamicLibs(filename, debug=False):
    (totalelf, elfresult) = parseELF(filename, 0, debug)
    if not totalelf:
        return

    if not 'dynamic' in elfresult:
        return

    dynamicsection = None
    dynstrsection = None
    for i in elfresult['sections']:
        if elfresult['sections'][i]['name'] == '.dynstr':
            dynstrsection = i
        if elfresult['sections'][i]['name'] == '.dynamic':
            dynamicsection = i

    if dynamicsection == None:
        return

    if elfresult['sections'][dynamicsection]['sectiontype'] != 6:
        return

    if elfresult['sections'][dynstrsection]['sectiontype'] != 3:
        return

    bit32 = elfresult['bit32']
    littleendian = elfresult['littleendian']

    # first, get the dynamic section
    elffile = open(filename, 'rb')
    elffile.seek(elfresult['sections'][dynamicsection]['sectionoffset'])
    elfbytes = elffile.read(elfresult['sections'][dynamicsection]['sectionsize'])

    elffile.seek(elfresult['sections'][dynstrsection]['sectionoffset'])
    dynstrbytes = elffile.read(elfresult['sections'][dynstrsection]['sectionsize'])
    elffile.close()

    # then process the entries
    if bit32:
        tagsize = 4
    else:
        tagsize = 8

    needed_names = []
    sonames = []
    rpathname = None
    for i in xrange(0, len(elfbytes)/tagsize, 2):
        tagbytes = elfbytes[i*tagsize:i*tagsize+tagsize]
        if littleendian:
            if bit32:
                d_tag = struct.unpack('<I', tagbytes)[0]
            else:
                d_tag = struct.unpack('<Q', tagbytes)[0]
        else:
            if bit32:
                d_tag = struct.unpack('>I', tagbytes)[0]
            else:
                d_tag = struct.unpack('>Q', tagbytes)[0]

        if d_tag == 1:
            # equivalent to NEEDED in readelf output
            offsetbytes = elfbytes[i*tagsize+tagsize:i*tagsize+tagsize*2]
            if littleendian:
                if bit32:
                    d_needed_offset = struct.unpack('<I', offsetbytes)[0]
                else:
                    d_needed_offset = struct.unpack('<Q', offsetbytes)[0]
            else:
                if bit32:
                    d_needed_offset = struct.unpack('>I', offsetbytes)[0]
                else:
                    d_needed_offset = struct.unpack('>Q', offsetbytes)[0]
            endofneededname = dynstrbytes.find('\x00', d_needed_offset)
            needed_names.append(dynstrbytes[d_needed_offset:endofneededname])
        elif d_tag == 14:
            # equivalent to SONAME in readelf output
            offsetbytes = elfbytes[i*tagsize+tagsize:i*tagsize+tagsize*2]
            if littleendian:
                if bit32:
                    soname_offset = struct.unpack('<I', offsetbytes)[0]
                else:
                    soname_offset = struct.unpack('<Q', offsetbytes)[0]
            else:
                if bit32:
                    soname_offset = struct.unpack('>I', offsetbytes)[0]
                else:
                    soname_offset = struct.unpack('>Q', offsetbytes)[0]
            endofsoname = dynstrbytes.find('\x00', soname_offset)
            soname = dynstrbytes[soname_offset:endofsoname]
            sonames.append(soname)
        elif d_tag == 15:
            # equivalent to RPATH in readelf output
            offsetbytes = elfbytes[i*tagsize+tagsize:i*tagsize+tagsize*2]
            if littleendian:
                if bit32:
                    rpath_offset = struct.unpack('<I', offsetbytes)[0]
                else:
                    rpath_offset = struct.unpack('<Q', offsetbytes)[0]
            else:
                if bit32:
                    rpath_offset = struct.unpack('>I', offsetbytes)[0]
                else:
                    rpath_offset = struct.unpack('>Q', offsetbytes)[0]
            endofrpathname = dynstrbytes.find('\x00', rpath_offset)
            rpathname = dynstrbytes[rpath_offset:endofrpathname]

    dynamic_res = {}

    if rpathname != None:
        dynamic_res['rpathname'] = rpathname
    if sonames != []:
        dynamic_res['sonames'] = sonames
    if needed_names != []:
        dynamic_res['needed_libs'] = needed_names
    return dynamic_res

# method to verify if a file is a valid ELF file
#
# Use several specifications:
# http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
# https://refspecs.linuxbase.org/elf/elf.pdf
# https://www.uclibc.org/docs/elf-64-gen.pdf (important for 64 bit offsets)
#
# For these checks the ELF header, the program header and the section
# headers are looked at.
#
def verifyELF(filename, tempdir=None, tags=[], offsets={}, scanenv={}, debug=False, unpacktempdir=None):
    offset = 0
    if not 'binary' in tags:
        return []
    if 'compressed' in tags or 'graphics' in tags or 'xml' in tags:
        return []
    elffile = open(filename, 'rb')
    elffile.seek(offset)
    elfbytes = elffile.read(4)
    if elfbytes != '\x7f\x45\x4c\x46':
        elffile.close()
        return []

    newtags = []
    filesize = os.stat(filename).st_size

    (totalelf, elfresult) = parseELF(filename, 0, debug)

    if not totalelf:
        return []

    if not elfresult['dynamic']:
        newtags.append("static")
    else:
        newtags.append("dynamic")

    newtags.append(elfresult['elftype'])

    if "__ksymtab_strings" in elfresult['sectionnames']:
        # some Linux kernel specific data is stored in a
        # separate section, so it is easy to recognize
        newtags.append('linuxkernel')
    elif "oat_patches" in elfresult['sectionnames'] or '.text.oat_patches' in elfresult['sectionnames']:
        # newer Android programs are actually ELF files, with
        # the dex opcodes stored in the .rodata section
        newtags.append('oat')
        newtags.append('android')
    newtags.append('elf')
    return newtags

# method to parse an ELF file
# returns the following data:
# * endianness
# * 32 bit or 64 bit
# * ELF type
# * architecture
# * section names
# * section meta data
# * is ELF file dynamically linked (or could be)?
#
# First the ELF header is checked, then the program header
# table, then the section header table
#
# For thorough documentation of each of the parts consult
# the ELF documentation referred above.
def parseELF(filename, offset=0, debug=False):
    elffile = open(filename, 'rb')

    elfresult = {}
    filesize = os.stat(filename).st_size

    # read 64 bytes for the header
    elffile.seek(offset)
    elfbytes = elffile.read(64)
    if len(elfbytes) != 64:
        elffile.close()
        return (False, None)

    if elfbytes[0:4] != '\x7f\x45\x4c\x46':
        elffile.close()
        return (False, None)

    iself = False

    # just set some default values: little endian, 32 bit
    littleendian = True
    bit32 = True

    # first check if this is a 32 bit or 64 bit binary
    if struct.unpack('>B', elfbytes[4])[0] != 1:
        bit32 = False
    # then check if this is a little endian or big endian binary
    if struct.unpack('>B', elfbytes[5])[0] != 1:
        littleendian = False

    elfresult['bit32'] = bit32
    elfresult['littleendian'] = littleendian

    # first determine the size of the ELF header
    if bit32:
        elfunpackbytes = elfbytes[0x28:0x28+2]
    else:
        elfunpackbytes = elfbytes[0x34:0x34+2]
    if littleendian:
        elfheadersize = struct.unpack('<H', elfunpackbytes)[0]
    else:
        elfheadersize = struct.unpack('>H', elfunpackbytes)[0]

    if not (elfheadersize == 52 or elfheadersize == 64):
        elffile.close()
        return (False, None)

    # ELF header cannot extend past the end of the file
    if offset + elfheadersize > filesize:
        elffile.close()
        return (False, None)

    if elfheadersize == 0:
        elffile.close()
        return (False, None)

    # then read the actual ELF header
    elffile.seek(offset)
    elfbytes = elffile.read(elfheadersize)

    # check the ELF type.
    if littleendian:
        elftypebyte = struct.unpack('<H', elfbytes[0x10:0x10+2])[0]
    else:
        elftypebyte = struct.unpack('>H', elfbytes[0x10:0x10+2])[0]
    if elftypebyte == 0:
        elftype = 'elftypenone'
    elif elftypebyte == 1:
        elftype = 'elfrelocatable'
    elif elftypebyte == 2:
        elftype = 'elfexecutable'
    elif elftypebyte == 3:
        elftype = 'elfdynamic'
    elif elftypebyte == 4:
        elftype = 'elfcore'
    else:
        return (False, None)

    elfresult['elftype'] = elftype

    # check the machine type
    if littleendian:
        elfmachinebyte = struct.unpack('<H', elfbytes[0x12:0x12+2])[0]
    else:
        elfmachinebyte = struct.unpack('>H', elfbytes[0x12:0x12+2])[0]
    if elfmachinebyte in architecturemapping:
        architecture = architecturemapping[elfmachinebyte]
    else:
        architecture = "UNKNOWN"

    elfresult['architecture'] = architecture

    # the start of program headers
    if bit32:
        elfunpackbytes = elfbytes[0x1C:0x20]
    else:
        elfunpackbytes = elfbytes[0x20:0x28]
    if littleendian:
        if bit32:
            startprogramheader = struct.unpack('<I', elfunpackbytes)[0]
        else:
            startprogramheader = struct.unpack('<Q', elfunpackbytes)[0]
    else:
        if bit32:
            startprogramheader = struct.unpack('>I', elfunpackbytes)[0]
        else:
            startprogramheader = struct.unpack('>Q', elfunpackbytes)[0]

    # program header cannot be outside of the file
    if offset + startprogramheader > filesize:
        elffile.close()
        return (False, None)

    # the start of section headers
    if bit32:
        elfunpackbytes = elfbytes[0x20:0x20+4]
    else:
        elfunpackbytes = elfbytes[0x28:0x28+8]
    if littleendian:
        if bit32:
            startsectionheader = struct.unpack('<I', elfunpackbytes)[0]
        else:
            startsectionheader = struct.unpack('<Q', elfunpackbytes)[0]
    else:
        if bit32:
            startsectionheader = struct.unpack('>I', elfunpackbytes)[0]
        else:
            startsectionheader = struct.unpack('>Q', elfunpackbytes)[0]

    # section header cannot be outside of the file
    if offset + startsectionheader > filesize:
        elffile.close()
        return (False, None)

    # the size of the program headers
    if bit32:
        elfunpackbytes = elfbytes[0x2A:0x2A+2]
    else:
        elfunpackbytes = elfbytes[0x36:0x36+2]
    if littleendian:
        programheadersize = struct.unpack('<H', elfunpackbytes)[0]
    else:
        programheadersize = struct.unpack('>H', elfunpackbytes)[0]

    # program header cannot extend past the file
    if offset + startprogramheader + programheadersize > filesize:
        elffile.close()
        return (False, None)

    # the amount of program headers
    if bit32:
        elfunpackbytes = elfbytes[0x2C:0x2C+2]
    else:
        elfunpackbytes = elfbytes[0x38:0x38+2]
    if littleendian:
        numberprogramheaders = struct.unpack('<H', elfunpackbytes)[0]
    else:
        numberprogramheaders = struct.unpack('>H', elfunpackbytes)[0]

    if numberprogramheaders != 0:
        # program header cannot be inside the ELF header
        if offset + startprogramheader + programheadersize < offset + elfheadersize:
            elffile.close()
            return (False, None)

    # the size of the section headers
    if bit32:
        elfunpackbytes = elfbytes[0x2E:0x2E+2]
    else:
        elfunpackbytes = elfbytes[0x3A:0x3A+2]
    if littleendian:
        sectionheadersize = struct.unpack('<H', elfunpackbytes)[0]
    else:
        sectionheadersize = struct.unpack('>H', elfunpackbytes)[0]

    # section header cannot extend past the end of the file
    if offset + startsectionheader + sectionheadersize > filesize:
        elffile.close()
        return (False, None)

    # the amount of section headers
    if bit32:
        elfunpackbytes = elfbytes[0x30:0x30+2]
    else:
        elfunpackbytes = elfbytes[0x3C:0x3C+2]
    if littleendian:
        numbersectionheaders = struct.unpack('<H', elfunpackbytes)[0]
    else:
        numbersectionheaders = struct.unpack('>H', elfunpackbytes)[0]

    # the start of section header index
    if bit32:
        elfunpackbytes = elfbytes[0x32:0x32+2]
    else:
        elfunpackbytes = elfbytes[0x3E:0x3E+2]
    if littleendian:
        sectionheaderindex = struct.unpack('<H', elfunpackbytes)[0]
    else:
        sectionheaderindex = struct.unpack('>H', elfunpackbytes)[0]

    # section header cannot be inside the ELF header
    if numbersectionheaders != 0:
        if offset + startsectionheader + sectionheadersize < offset + elfheadersize:
            elffile.close()
            return (False, None)

    # First process the program header table
    brokenelf = False
    maxendofprogramsegments = 0
    for i in range(0,numberprogramheaders):
        elffile.seek(offset + startprogramheader + i*programheadersize)
        elfbytes = elffile.read(programheadersize)
        if len(elfbytes) != programheadersize:
            brokenelf = True
            break
        # first the segmenttype
        if littleendian:
            segmenttype = struct.unpack('<I', elfbytes[:4])[0]
        else:
            segmenttype = struct.unpack('>I', elfbytes[:4])[0]

        # PT_NULL is unused, so ignore
        if segmenttype == 0:
            continue

        # then the offset in the file
        if littleendian:
            if bit32:
                segmentoffset = struct.unpack('<I', elfbytes[4:8])[0]
            else:
                segmentoffset = struct.unpack('<Q', elfbytes[8:16])[0]
        else:
            if bit32:
                segmentoffset = struct.unpack('>I', elfbytes[4:8])[0]
            else:
                segmentoffset = struct.unpack('>Q', elfbytes[8:16])[0]

        # segment cannot be outside of the file
        if offset + segmentoffset > filesize:
            brokenelf = True
            break

        # then the virtual address in memory (skip for now) -- 4 bytes (32 bit) or 8 bytes
        # then the physical address in memory (skip for now) -- 4 bytes (32 bit) or 8 bytes
        # then the size in bytes in the file image
        if littleendian:
            if bit32:
                segmentsize = struct.unpack('<I', elfbytes[16:20])[0]
            else:
                segmentsize = struct.unpack('<Q', elfbytes[32:40])[0]
        else:
            if bit32:
                segmentsize = struct.unpack('>I', elfbytes[16:20])[0]
            else:
                segmentsize = struct.unpack('>Q', elfbytes[32:40])[0]

        # segment cannot extend past the end of the file
        if offset + segmentoffset + segmentsize > filesize:
            brokenelf = True
            break
        maxendofprogramsegments = max(offset + segmentoffset + segmentsize, maxendofprogramsegments)

        # then the size in bytes in memory image
        if littleendian:
            if bit32:
                memsegmentsize = struct.unpack('<I', elfbytes[16:20])[0]
            else:
                memsegmentsize = struct.unpack('<Q', elfbytes[32:40])[0]
        else:
            if bit32:
                memsegmentsize = struct.unpack('>I', elfbytes[16:20])[0]
            else:
                memsegmentsize = struct.unpack('>Q', elfbytes[32:40])[0]
        # PT_LOAD
        if segmenttype == 1:
            # memory size cannot be smaller than the
            # segment to be loaded into memory.
            if memsegmentsize < segmentsize:
                brokenelf = True
                break
        # then the segment dependent flags (skip for now) -- 4 bytes
        # then the alignment
        if littleendian:
            if bit32:
                alignment = struct.unpack('<I', elfbytes[28:32])[0]
            else:
                alignment = struct.unpack('<I', elfbytes[52:60])[0]

        else:
            if bit32:
                alignment = struct.unpack('>I', elfbytes[28:32])[0]
            else:
                alignment = struct.unpack('>I', elfbytes[52:60])[0]
        if alignment != 0 and alignment != 1:
            # alignment has to be a power of 2
            if alignment != pow(2,int(math.log(alignment, 2))):
                brokenelf = True
                break
            # TODO: check if certain parts are properly aligned

    if brokenelf:
        elffile.close()
        return (False, None)

    dynamic = False

    sections = {}

    # process the section headers
    maxendofsection = 0
    dynamiccount = 0
    for i in xrange(0,numbersectionheaders):
        elffile.seek(offset+startsectionheader + i * sectionheadersize)
        elfbytes = elffile.read(sectionheadersize)
        if len(elfbytes) != sectionheadersize:
            elffile.close()
            return (False, None)
        if littleendian:
            sh_name = struct.unpack('<I', elfbytes[0:4])[0]
        else:
            sh_name = struct.unpack('>I', elfbytes[0:4])[0]
        if littleendian:
            sh_type = struct.unpack('<I', elfbytes[4:8])[0]
        else:
            sh_type = struct.unpack('>I', elfbytes[4:8])[0]
        if sh_type == 6:
            dynamiccount += 1
        # then the flags (4 byte or 8 byte) -- skip for now
        if littleendian:
            if bit32:
                sh_flags = struct.unpack('<I', elfbytes[8:12])[0]
            else:
                sh_flags = struct.unpack('<Q', elfbytes[8:16])[0]
        else:
            if bit32:
                sh_flags = struct.unpack('>I', elfbytes[8:12])[0]
            else:
                sh_flags = struct.unpack('>Q', elfbytes[8:16])[0]

        # then the virtual address (4 byte or 8 byte) -- skip for now
        if littleendian:
            if bit32:
                sh_addr = struct.unpack('<I', elfbytes[12:16])[0]
            else:
                sh_addr = struct.unpack('<Q', elfbytes[16:24])[0]
        else:
            if bit32:
                sh_addr = struct.unpack('>I', elfbytes[12:16])[0]
            else:
                sh_addr = struct.unpack('>Q', elfbytes[16:24])[0]
        # then the offset
        if littleendian:
            if bit32:
                sectionoffset = struct.unpack('<I', elfbytes[16:20])[0]
            else:
                sectionoffset = struct.unpack('<Q', elfbytes[24:32])[0]
        else:
            if bit32:
                sectionoffset = struct.unpack('>I', elfbytes[16:20])[0]
            else:
                sectionoffset = struct.unpack('>Q', elfbytes[24:32])[0]

        # section offset cannot be outside of the file
        if offset + sectionoffset > filesize:
            brokenelf = True
            break

        # then the size in bytes in the file image
        if littleendian:
            if bit32:
                sectionsize = struct.unpack('<I', elfbytes[20:24])[0]
            else:
                sectionsize = struct.unpack('<Q', elfbytes[32:40])[0]
        else:
            if bit32:
                sectionsize = struct.unpack('>I', elfbytes[20:24])[0]
            else:
                sectionsize = struct.unpack('>Q', elfbytes[32:40])[0]

        # segment cannot extend past the end of the file.
        # This check only makes sense if the section has a different
        # type than NOBITS
        if sh_type != 8:
            if offset + sectionoffset + sectionsize > filesize:
                brokenelf = True
                break
            maxendofsection = max(offset + sectionoffset + sectionsize, maxendofsection)

        sections[i] = {'sectionoffset': sectionoffset, 'sectionsize': sectionsize, 'nameoffset': sh_name, 'sectiontype': sh_type}

    if brokenelf:
        elffile.close()
        return (False, None)

    # dynamic count cannot be larger than 1
    if dynamiccount == 1:
        dynamic = True

    # for each section find the name in the table with section names
    sectionnames = []
    if sectionheaderindex in sections:
        elffile.seek(sections[sectionheaderindex]['sectionoffset'])
        sectionnamebytes = elffile.read(sections[sectionheaderindex]['sectionsize'])
        sectionnames = sectionnamebytes.split('\x00')
        for i in sections:
            endofsectionname = sectionnamebytes.find('\x00', sections[i]['nameoffset'])
            sections[i]['name'] = sectionnamebytes[sections[i]['nameoffset']:endofsectionname]

    # finally close the file
    elffile.close()

    # Now some extra checks so files can be tagged as ELF
    if maxendofprogramsegments == filesize:
        iself = True
        totalsize = filesize
    elif maxendofsection == filesize:
        iself = True
        totalsize = filesize
    else:
        # This does not work well for some Linux kernel modules as well as other files
        # (architecture dependent?)
        # One architecture where this sometimes seems to happen is ARM.
        totalsize = startsectionheader + sectionheadersize * numbersectionheaders

        # there are files where the number of section headers is zero, but
        # which are valid ELF files. An example is the bootloader on certain
        # Android devices. TODO.
        if totalsize == 0:
            pass
        if totalsize == filesize:
            iself = True
        else:
            # If it is a signed kernel module then the key is appended to the ELF data
            elffile = open(filename, 'rb')
            elffile.seek(-28, os.SEEK_END)
            elfbytes = elffile.read()
            if elfbytes == "~Module signature appended~\n":
                # The metadata of the signing data can be found in 12 bytes
                # preceding the 'magic'
                # According to 'scripts/sign-file' in the Linux kernel
                # the last 4 bytes are the size of the signature data
                # three bytes before that are 0x00
                # The byte before that is the length of the key identifier
                # The byte before that is the length of the "signer's name"
                totalsiglength = 40
                elffile.seek(-40, os.SEEK_END)
                elfbytes = elffile.read(12)
                signaturelength = struct.unpack('>I', elfbytes[-4:])[0]
                totalsiglength += signaturelength
                keyidentifierlen = ord(elfbytes[4])
                signernamelen = ord(elfbytes[3])
                totalsiglength += keyidentifierlen
                totalsiglength += signernamelen
                if totalsiglength + totalsize == filesize:
                    iself = True
                totalsize += totalsiglength
            elffile.close()
            # check if the max end of section happens to be later than
            # the totalsize, as this happens as well in non-stripped binaries
            totalsize = max(maxendofsection, totalsize)

    elfresult['dynamic'] = dynamic
    elfresult['sectionnames'] = sectionnames
    elfresult['sections'] = sections
    elfresult['size'] = totalsize

    if not iself:
        return (False, elfresult)

    return (True, elfresult)


text:
import balanced

balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')

cards = balanced.Card.query


text:
case class Foo(bar: String, foo: String)
case class Bar(bar: String)

object FooBar {
  def crash(): Unit = {
    val foo = Foo("foo", "bar").copy(foo = "foo")
    val bar = Bar(foo.bar)
  }
}


text:
package org.sklsft.generator.components.metadata.factory.impl;

import org.sklsft.generator.components.metadata.factory.interfaces.TableFactory;
import org.sklsft.generator.components.resolvers.DatabaseHandlerDiscovery;
import org.sklsft.generator.model.domain.Model;
import org.sklsft.generator.model.domain.Package;
import org.sklsft.generator.model.domain.database.Column;
import org.sklsft.generator.model.domain.database.Index;
import org.sklsft.generator.model.domain.database.Table;
import org.sklsft.generator.model.domain.database.UniqueConstraint;
import org.sklsft.generator.model.metadata.ColumnMetaData;
import org.sklsft.generator.model.metadata.DataType;
import org.sklsft.generator.model.metadata.IndexMetaData;
import org.sklsft.generator.model.metadata.RelationType;
import org.sklsft.generator.model.metadata.TableMetaData;
import org.sklsft.generator.model.metadata.TextFilterType;
import org.sklsft.generator.model.metadata.UniqueConstraintMetaData;
import org.sklsft.generator.model.metadata.Visibility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TableFactoryImpl implements TableFactory {

	private static final Logger logger = LoggerFactory.getLogger(TableFactory.class);

	@Override
	public Table scanTable(TableMetaData tableMetaData, Package myPackage) {
		Table table = new Table();
		table.myPackage = myPackage;
		table.originalName = tableMetaData.getName();
		table.name = DatabaseHandlerDiscovery.getDatabaseHandler(myPackage.model.project).rename(table.originalName);
		if (tableMetaData.getIdType() != null) {
			table.idType = tableMetaData.getIdType();
		} else {
			table.idType = DataType.LONG;
		}
		if (table.idGeneratorType != null) {
			table.idGeneratorType = tableMetaData.getIdGeneratorType();
		} else {
			table.idGeneratorType = table.idType.getDefaultGenerator();
		}
		table.cardinality = tableMetaData.getCardinality();
		table.sequenceName = table.name + "_SEQ";
		logger.trace("Table found : " + tableMetaData.getName());

        return table;
	}

	@Override
	public Table fillTable(TableMetaData tableMetaData, Model model) {
		Table table = model.findTable(tableMetaData.getName());

        for (ColumnMetaData columnMetaData : tableMetaData.getColumns()) {
            Column column = new Column();
            column.originalName = columnMetaData.getName();
            column.name = DatabaseHandlerDiscovery.getDatabaseHandler(model.project).rename(column.originalName);
            if (columnMetaData.getDataType() != null) {
            	column.dataType = columnMetaData.getDataType();
            }

            if (columnMetaData.getReferenceTableRelation() != null) {
            	column.relation = columnMetaData.getReferenceTableRelation();
            } else {
            	column.relation = RelationType.PROPERTY;
            }

            column.deleteCascade = (column.relation.equals(RelationType.MANY_TO_ONE_COMPONENT));
            column.referenceTable = model.findTable(columnMetaData.getReferenceTableName());

            if (column.referenceTable != null) {
            	column.dataType = column.referenceTable.idType;
            }

            column.unique = columnMetaData.getUnique() || column.relation.isUnique();
            column.nullable = columnMetaData.getNullable();
            if (column.relation.isNotNullable()) {
            	column.nullable = false;
            }
            column.editable = columnMetaData.getEditable();
            column.filterable = columnMetaData.getFilterable();
            if (columnMetaData.getTextFilterType()!=null) {
            	column.textFilterType = columnMetaData.getTextFilterType();
            } else {
            	column.textFilterType = TextFilterType.STARTS_WITH;
            }
            if (columnMetaData.getVisibility()!=null) {
            	column.visibility = columnMetaData.getVisibility();
            } else {
            	column.visibility = Visibility.VISIBLE;
            }
            column.rendering = columnMetaData.getRendering();
            column.annotations = columnMetaData.getAnnotations();
            table.columns.add(column);
        }

        createConstraintsAndIndexes(tableMetaData, table);

        return table;
	}

	private void createConstraintsAndIndexes(TableMetaData tableMetaData, Table table) {
		// unique constraint corresponding to the business key
        if (table.cardinality > 0) {
        	UniqueConstraint uniqueConstraint = new UniqueConstraint();
        	Index index = new Index();
        	uniqueConstraint.index = index;
        	index.uniqueConstraint = uniqueConstraint;
    		uniqueConstraint.name = "UC_" + table.name;
    		index.name = "IDX_" + table.name + "_UC";
    		for (int i = 0; i < table.cardinality; i++) {
    			uniqueConstraint.columns.add(table.columns.get(i));
    			index.columns.add(table.columns.get(i));
    		}
    		table.uniqueConstraints.add(uniqueConstraint);
    		table.indexes.add(index);
        }
        // unique constraints on fields declared as unique or indexes on fk
        for (int i = 0;i<table.columns.size();i++) {
        	Column column = table.columns.get(i);
        	if (column.unique) {
        		UniqueConstraint uniqueConstraint = new UniqueConstraint();
        		Index index = new Index();
        		uniqueConstraint.index = index;
            	index.uniqueConstraint = uniqueConstraint;

        		uniqueConstraint.name = "UC_" + table.name + "_C" + i;
        		uniqueConstraint.columns.add(column);

        		index.name = "IDX_" + table.name + "_C" + i;
        		index.columns.add(column);

        		table.uniqueConstraints.add(uniqueConstraint);
        		table.indexes.add(index);
        	} else {
        		if (column.referenceTable != null) {
        			Index index = new Index();
            		index.name = "IDX_" + table.name + "_C" + i;
            		index.columns.add(column);
            		table.indexes.add(index);
        		}
        	}
        }

        // declared unique constraints
        if (tableMetaData.getUniqueConstraints()!=null) {
        	for (UniqueConstraintMetaData uniqueConstraintMetaData:tableMetaData.getUniqueConstraints()) {
        		UniqueConstraint uniqueConstraint = new UniqueConstraint();
        		Index index = new Index();
        		uniqueConstraint.index = index;
            	index.uniqueConstraint = uniqueConstraint;

            	index.name = "IDX_" + uniqueConstraintMetaData.getName();
            	uniqueConstraint.name = "UC_" + uniqueConstraintMetaData.getName();

        		for (String columnName:uniqueConstraintMetaData.getFields()) {
        			Column column = table.findColumnByName(columnName);
        			uniqueConstraint.columns.add(column);
        			index.columns.add(column);
        		}
        		table.uniqueConstraints.add(uniqueConstraint);
        		table.indexes.add(index);
        	}
        }

        // declared indexes
        if (tableMetaData.getIndexes()!=null) {
        	for (IndexMetaData indexMetaData:tableMetaData.getIndexes()) {

        		Index index = new Index();

            	index.name = "IDX_" + indexMetaData.getName();

        		for (String columnName:indexMetaData.getFields()) {
        			Column column = table.findColumnByName(columnName);
        			index.columns.add(column);
        		}
        		table.indexes.add(index);
        	}
        }
	}
}