text:
(function (bingo) {
    //version 1.0.1
    "use strict";

    /*
        //1. 添加或设置路由'view'
        bingo.route('view', {
            //优先级, 越大越前, 默认100
            priority: 100,
            //路由地址
            url: 'view/{module}/{controller}/{action}',
            //路由转发到地址
            toUrl: 'modules/{module}/views/{controller}/{action}.html',
            //默认值
            defaultValue: { module: '', controller: '', action: '' }
        });

        //2. 根据url生成目标url;
            var url = bingo.route('view/system/user/list');
                返回结果==>'modules/system/views/user/list.html'
    */
    //路由
    bingo.route = function (p, context) {
        if (arguments.length == 1)
            return bingo.routeContext(p).toUrl;
        else
            p && context && _routes.add(p, context);
    };

    /*
        //根据url生成routeContext;
        var routeContext = bingo.routeContext('view/system/user/list');
            返回结果==>{
                url:'view/system/user/list',
                toUrl:'modules/system/views/user/list.html',
                params:{ module: 'system', controller: 'user', action: 'list' }
            }
    */
    //
    bingo.routeContext = function (url) {
        return _routes.getRouteByUrl(url);
    };

    /*
        //生成路由地址
        bingo.routeLink('view', { module: 'system', controller: 'user', action: 'list' });
            返回结果==>'view/system/user/list'
    */
    bingo.routeLink = function (name, p) {
        var r = _routes.getRuote(name);
        return r ? _paramToUrl(r.context.url, p, 1) : '';
    };

    /*
        //生成路由地址query
        bingo.routeLinkQuery('view/system/user/list', { id: '1111' });
            返回结果==>'view/system/user/list$id:1111'
    */
    bingo.routeLinkQuery = function (url, p) {
        url || (url = '');
        var urlPath = '';
        if (url.indexOf('$') >= 0 || url.indexOf('?') >= 0) {
            var routeContext = bingo.routeContext(url);
            p = bingo.extend({}, p, routeContext.params.queryParams);
            var sp = url.indexOf('$') >= 0 ? '$' : '?';
            url = url.split(sp)[0];
        }
        bingo.eachProp(p, function (item, n) {
            item = encodeURIComponent(item || '');
            //route参数形式, $aaa:1$bbb=2
            urlPath = [urlPath, '$', n, ':', item].join('');
        });
        return [url, urlPath].join('');
    };

    var _tranAttrRex = /\{([^}]+)\}/gi;
    var _urlToParams = function (url, routeContext) {
        //匹配url, 并生成url参数
        // 如'view/{module}/{contrller}/{action}' ==> {module:'', contrller:'', action:''}
        if (!url || !routeContext.url) return null;
        var matchUrl = routeContext.url;

        //如果包函*符号, 直接认为没有参数, 返回空object
        //if (matchUrl.indexOf('*') >= 0) {
        //    routeContext._reg || (routeContext._reg = new RegExp(matchUrl.replace('*', '.*')));
        //    return routeContext._reg.test(url) ? {} : null;
        //}

        //是否有?*匹配模式
        var isRegMod = bingo.isRegexMapPath(matchUrl);
        if (isRegMod) {
            //去除$后面部分内容, 作为查询条件
            var urlTest = matchUrl.indexOf('$') >= 0 ? matchUrl.split('$')[0] : matchUrl;
            _tranAttrRex.lastIndex = 0;
            urlTest = urlTest.replace(_tranAttrRex, '*');
            routeContext._reg || (routeContext._reg = bingo.makeRegexMapPath(urlTest));
            if (!routeContext._reg.test(url)) return null;
        }

        //url参数部分由$分开, 如aaaa/ssss.html$aaa:1$bb:2
        var urlParams = url.split('$');

        //解释url变量, 如:{module}/{action}/
        var urlList = urlParams[0].split('/'),
            matchUrlList = (routeContext._matchUrlList || (routeContext._matchUrlList = matchUrl.split('/')));
        if (urlList.length != matchUrlList.length) {
            return isRegMod ? {} : null;
        }
        var obj = {},//保存url变量
            isOk = true,//是否全匹配,如果不匹配, 返回null
            sTemp;
        bingo.each(matchUrlList, function (item, index) {
            sTemp = urlList[index];

            //如果没有?和*查询符,
            if (!(isRegMod && bingo.isRegexMapPath(item))) {
                _tranAttrRex.lastIndex = 0;
                if (_tranAttrRex.test(item)) {
                    obj[item.replace(_tranAttrRex, '$1')] = decodeURIComponent(sTemp || '');
                } else {
                    isOk = (item == sTemp);
                    if (!isOk) return false;
                }

            }
        });

        var queryParams = obj.queryParams = {};

        //如果url匹配,
        //生成多余参数
        if (isOk && urlParams.length > 1) {
            urlParams = bingo.sliceArray(urlParams, 1);
            bingo.each(urlParams, function (item, index) {
                var list = item.split(':'),
                    name = list[0],
                    val = decodeURIComponent(list[1] || '');
                name && (obj[name] = queryParams[name] = val);
            });
        }

        return isOk ? obj : null;
    }, _getActionContext = function () {
        var context = { app: null, module: null, controller: null, action: null };
        var params = this.params;
        if (params) {
            var appName = params.app;
            var moduleName = params.module;

            var appIn = bingo.isNullEmpty(appName) ? bingo.defaultApp() : bingo.app(appName);
            var moduleIn = bingo.isNullEmpty(moduleName) ? appIn.defaultModule()
                : appIn.module(moduleName);

            var controller = moduleIn ? moduleIn.controller(params.controller) : null;
            var action = controller ? controller.action(params.action) : (moduleIn ? moduleIn.action(params.action) : null);
            context.app = appIn;
            context.module = moduleIn;
            context.controller = controller;
            context.action = action;
        }
        return context;
    }, _makeRouteContext = function (name, url, toUrl, params) {
        //生成 routeContext
        return { name: name, params: params, url: url, toUrl: toUrl, actionContext: _getActionContext };
    }, _paramToUrl = function (url, params, paramType) {
        //_urlToParams反操作, paramType:为0转到普通url参数(?a=1&b=2), 为1转到route参数($a:1$b:2), 默认为0
        _tranAttrRex.lastIndex = 0;
        if (!url || !params) return bingo.path(url);
        var otherP = '', attr = '', val = '';
        bingo.eachProp(params, function (item, n) {
            attr = ['{', n, '}'].join('');
            val = encodeURIComponent(item || '');

            if (url.indexOf(attr) >= 0) {
                //如果是url变量参数, 如/{module}/{aciont}/aa.txt
                url = bingo.replaceAll(url, attr, val);
            } else if (n != 'module' && n != 'controller' && n != 'action' && n != 'service' && n != 'app' && n != 'queryParams') {
                //如果是其它参数
                if (paramType == 1) {
                    //route参数形式, $aaa:1$bbb=2
                    otherP = [otherP, '$', n, ':', val].join('');
                } else {
                    //普通url参数, ?aaa=1&bbb=2
                    otherP = [otherP, '&', n, '=', val].join('');
                }
            }
        });

        if (otherP) {
            //如果有其它参数, 组装到url参数中
            if (paramType == 1) {
                url = [url, otherP].join('');
            } else {
                if (url.indexOf('?') >= 0)
                    url = [url, otherP].join('');
                else
                    url = [url, otherP.substr(1)].join('?');
            }
        }

        return bingo.path(url);
    };

    var _routes = {
        datas: [],
        defaultRoute: {
            url: '**',
            toUrl: function (url, param) { return url; }
        },
        add: function (name, context) {
            var route = this.getRuote(name);
            if (bingo.isUndefined(context.priority))
                context.priority = 100;
            if (route) {
                route.context = context;
            } else {
                this.datas.push({
                    name: name,
                    context: context
                });
            }
            this.datas = bingo.linq(this.datas).sort(function (item1, item2) { return item2.context.priority - item1.context.priority; }).toArray()
        },
        getRuote: function (name) {
            var item = null;
            bingo.each(this.datas, function () {
                if (this.name == name) { item = this; return false; }
            });
            return item;
        },
        getRouteByUrl: function (url) {
            if (!url) return '';

            var querys = url.split('?');
            if (querys.length > 1) url = querys[0];
            var routeContext = null, name='';
            var params = null;
            bingo.each(this.datas, function () {
                routeContext = this.context;
                params = _urlToParams(url, routeContext);
                //如果params不为null, 认为是要查找的url
                if (params) { name = this.name; return false; }
            });

            //再找组装参数
            if (!params){
                routeContext = _routes.defaultRoute;
                name = 'defaultRoute';
            }
            if (params || routeContext.defaultValue)
                params = bingo.extend({}, routeContext.defaultValue, params);

            if (bingo.isFunction(routeContext.toUrl))
                routeContext.toUrl;

            var toUrl = bingo.isFunction(routeContext.toUrl) ?
                routeContext.toUrl.call(routeContext, url, params)
                : routeContext.toUrl;

            if (querys.length > 1) {
                params || (params = {});
                querys[1].replace(/([^=&]+)\=([^=&]*)/g, function (find, name, value) {
                    params[name] = value;
                });
            }

            var toUrl = _paramToUrl(toUrl, params);

            return _makeRouteContext(name, url,  toUrl, params);
        }
    };

    //设置view资源路由
    bingo.route('view', {
        //优先级, 越大越前, 默认100
        priority: 100,
        //路由url, 如: view/system/user/list
        url: 'view/{module}/{controller}/{action}',
        //路由到目标url, 生成:modules/system/views/user/list.html
        toUrl: 'modules/{module}/views/{controller}/{action}.html',
        //变量默认值, 框架提供内部用的变量: module, controller, action, service
        defaultValue: { module: 'system', controller: 'user', action: 'list' }
    });

    //设置action资源路由
    bingo.route('action', {
        url: 'action/{module}/{controller}/{action}',
        toUrl: 'modules/{module}/controllers/{controller}.js',
        defaultValue: { module: 'system', controller: 'user', action: 'list' }
    });

    //设置viewS资源路由
    bingo.route('viewS', {
        //路由url, 如: view/system/user/list
        url: 'view/{module}/{action}',
        //路由到目标url, 生成:modules/system/views/user/list.html
        toUrl: 'modules/{module}/{action}.html',
        //变量默认值, 框架提供内部用的变量: module, controller, action, service
        defaultValue: { module: 'system', action: 'list' }
    });

    //设置actionS资源路由
    bingo.route('actionS', {
        url: 'action/{module}/{action}',
        toUrl: 'modules/{module}/scripts/{action}.js',
        defaultValue: { module: 'system', action: 'list' }
    });

    //设置service资源路由
    bingo.route('service', {
        url: 'service/{module}/{service}',
        toUrl: 'modules/{module}/services/{service}.js',
        defaultValue: { module: 'system', service: 'user' }
    });

    //设置service资源路由
    bingo.route('serviceS', {
        url: 'service/{service}',
        toUrl: 'modules/services/{service}.js',
        defaultValue: { module: 'system', service: 'user' }
    });

    ////设置src资源路由
    //bingo.route('srv', {
    //    url: 'srv?/{module}/{service}',
    //    defaultValue: { module: 'system', service: 'user' },
    //    toUrl: function (url, params) {
    //        return ['srv', params.module, params.service].join('/');
    //    },
    //});

})(bingo);


text:
@interface AboutViewController ()<UITableViewDataSource, UITableViewDelegate>
@end

@implementation AboutViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColorTableSectionBg;
    self.title = @"关于我们";

    CGFloat logoViewTop, logoLabelTop, versionLabelTop, infoLabelBottom;
    NSString *icon_user_monkey;
    if (kDevice_Is_iPhone6Plus) {
        logoViewTop = 80;
        logoLabelTop = 40;
        versionLabelTop = 35;
        infoLabelBottom = 35;
        icon_user_monkey = @"icon_user_monkey_i6p";
    }else if (kDevice_Is_iPhone6){
        logoViewTop = 65;
        logoLabelTop = 25;
        versionLabelTop = 20;
        infoLabelBottom = 20;
        icon_user_monkey = @"icon_user_monkey_i6";
    }else{
        logoViewTop = 40;
        logoLabelTop = 20;
        versionLabelTop = 20;
        infoLabelBottom = 20;
        icon_user_monkey = @"icon_user_monkey";
    }

    UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:icon_user_monkey]];
    [self.view addSubview:logoView];

    UILabel *logoLabel = [[UILabel alloc] init];
    logoLabel.font = [UIFont boldSystemFontOfSize:17];
    logoLabel.textColor = kColor222;
    logoLabel.textAlignment = NSTextAlignmentCenter;
    logoLabel.text = @"Coding-让开发更简单";
    [self.view addSubview:logoLabel];

    UILabel *versionLabel = [[UILabel alloc] init];
    versionLabel.font = [UIFont systemFontOfSize:12];
    versionLabel.textColor = kColor666;
    versionLabel.textAlignment = NSTextAlignmentCenter;
    versionLabel.text = [NSString stringWithFormat:@"版本:V%@", kVersionBuild_Coding];
    [self.view addSubview:versionLabel];

    UILabel *infoLabel = [[UILabel alloc] init];
    infoLabel.numberOfLines = 0;
    infoLabel.backgroundColor = [UIColor clearColor];
    infoLabel.font = [UIFont systemFontOfSize:12];
    infoLabel.textColor = kColor666;
    infoLabel.textAlignment = NSTextAlignmentCenter;
    infoLabel.text = [NSString stringWithFormat:@"官网:https://coding.net \nE-mail:link@coding.net \n微博:Coding \n微信:扣钉Coding"];
    [self.view addSubview:infoLabel];

    [logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(logoViewTop);
        make.centerX.equalTo(self.view.mas_centerX);
    }];

    [logoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoView.mas_bottom).offset(logoLabelTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(logoLabel.font.pointSize);
    }];

    [versionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoLabel.mas_bottom).offset(versionLabelTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(versionLabel.font.pointSize);
    }];

    [infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-infoLabelBottom);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(5*infoLabel.font.pointSize);
    }];

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.scrollEnabled = NO;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[TitleDisclosureCell class] forCellReuseIdentifier:kCellIdentifier_TitleDisclosure];
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(versionLabel.mas_bottom).offset(44);
    }];
}

#pragma mark Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TitleDisclosureCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleDisclosure forIndexPath:indexPath];
    [cell setTitleStr:indexPath.row == 0? @"去评分": @"推荐 Coding"];
    [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kPaddingLeftWidth];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {//评分
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kAppReviewURL]];
    }else{//推荐 Coding
        [CodingShareView showShareViewWithObj:nil];
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
import json
from StringIO import StringIO

from django.http import HttpResponse

import openpyxl
from openpyxl.formatting import CellIsRule
from openpyxl.styles import PatternFill
from openpyxl.utils import get_column_letter

from corehq.apps.userreports.reports.view import CustomConfigurableReport
from corehq.util.soft_assert import soft_assert

# Copied from custom/abt/reports/data_sources/supervisory.json
MAX_LOCATION_COLUMNS = 350
_soft_assert_location_columns = soft_assert('{}@{}'.format('npellegrino', 'dimagi.com'))

def _invert_table(table):
    return [
        [row[column_index] for row in table]
        for column_index in range(len(table[0]))
    ]

class FormattedSupervisoryReport(CustomConfigurableReport):

    @property
    def export_table(self):
        data = super(FormattedSupervisoryReport, self).export_table

        # remove zeroes
        table = data[0][1]
        for row in range(1, len(table) - 1):
            for column in range(2, len(table[row])):
                if table[row][column] == 0:
                    table[row][column] = ''

        # remove hyphen prefixes from location column headers
        for column_index in range(2, len(table[0])):
            table[0][column_index] = table[0][column_index][1:]

        # sort columns by location
        inverted_table = _invert_table(table)
        inverted_incident_and_total_columns = inverted_table[:2]
        inverted_location_columns = inverted_table[2:]
        sorted_inverted_location_columns = sorted(
            inverted_location_columns,
            key=lambda inverted_location_column: inverted_location_column[0].lower()
        )
        data[0][1] = _invert_table(
            inverted_incident_and_total_columns + sorted_inverted_location_columns
        )

        _soft_assert_location_columns(
            len(sorted_inverted_location_columns) < MAX_LOCATION_COLUMNS,
            'Must increase number of allowed location columns in '
            'custom/abt/reports/data_sources/supervisory.json'
        )

        return data

    @property
    def excel_response(self):
        unformatted_excel_file = super(FormattedSupervisoryReport, self).excel_response

        workbook = openpyxl.load_workbook(unformatted_excel_file)
        worksheet = workbook.get_active_sheet()

        red = PatternFill(
            start_color='FFEE1111',
            end_color='FFEE1111',
            fill_type='solid',
        )

        max_row = worksheet.max_row
        max_column = get_column_letter(worksheet.max_column)

        def percentile_fill(start_column, start_row, end_column, end_row,
                            percentile, fill):
            format_range = {
                'start_column': start_column,
                'start_row': start_row,
                'end_column': end_column,
                'end_row': end_row,
            }
            worksheet.conditional_formatting.add(
                "%(start_column)s%(start_row)d:%(end_column)s%(end_row)d" % format_range,
                CellIsRule(
                    operator='greaterThan',
                    formula=[(
                        'PERCENTILE($%(start_column)s$%(start_row)d:'
                        '$%(end_column)s$%(end_row)d,{})'
                    ).format(percentile) % format_range],
                    fill=fill
                )
            )

        # total column
        percentile_fill('B', 2, 'B', max_row - 1, 0.95, red)

        # total row
        percentile_fill('C', max_row, max_column, max_row, 0.90, red)

        # body
        percentile_fill('C', 2, max_column, max_row - 1, 0.90, red)

        f = StringIO()
        workbook.save(f)
        return f

    @property
    def email_response(self):
        return HttpResponse(json.dumps({
            'report': '',
        }))


text:
require 'open-uri'
require 'nokogiri'

module Currency
  module Icons
    class Scraper
      def self.code_to_symbol
        new.perform
      end

      def initialize
        @lookup = {}
      end

      def perform
        doc = Nokogiri::HTML(open('http://www.xe.com/symbols.php'))

        doc.css('.cSmbl_Fnt_C2000').each do |column|
          @lookup[column.parent.children[1].content] = column.content
        end

        @lookup
      end
    end
  end
end


text:
import os
os.environ['LD_LIBRARY_PATH'] = "/usr/local/lib64:/home/libyang/build"

YANGGRE_PATH = "/home/libyang/build/yangre"
W3CGREP_PATH = "/home/w3cgrep/w3cgrep"
PREFIX = "/yangre"  # changing this will break things, as it is also used in ajax calls
APIPREFIX = "/yangre/v1"


text:
from PyQuante.shell import Shell

from PyQuante.Ints import sym2powerlist
from PyQuante.Basis.Tools import get_basis_data

from PyQuante.CGBF import CGBF

class BasisSet(object):
    """
    """
    def __init__(self, atoms, basis_data = None, **kwargs):
        """

        """
        # Option to omit f basis functions from imported basis sets
        omit_f = kwargs.get('omit_f',False)
        if not basis_data:
            from PyQuante.Basis.p631ss import basis_data
        elif type(basis_data) == type(''):
            # Assume this is a name of a basis set, e.g. '6-31g**'
            #  and import dynamically
            basis_data = get_basis_data(basis_data)

        # Creating the function lists, by shell and by arbitrary order
        bfs = []   # Basis list
        shells = []# Shell list
        for atom in atoms:
            bs = basis_data[atom.atno]
            for sym,prims in bs: # Shell Symbol S,P,D,F
                if omit_f and sym == "F": continue
                shell = Shell(sym)
                for power in sym2powerlist[sym]:
                    cgbf = CGBF(atom.pos(), power, atom.atid)

                    #exps,coefs = zip(*prims)
                    #primlist = [PrimitiveGTO(alpha,atom.pos(),power) for alpha in exps]

                    #bf = ContractedGTO(primlist,coefs)
                    #bf.normalize()
                    [cgbf.add_primitive(alpha,coef) for alpha,coef in prims]
                    cgbf.normalize()
                    bfs.append(cgbf) # Normal ordering

                    # Shell ordering
                    bfs_index = len(bfs)-1 # last added
                    shell.append(cgbf, bfs_index)
                shells.append(shell)

        self.bfs = bfs
        self.shells = shells
        #for index,func in enumerate(self.__iter__()):
        #    func.index = index
    def __len__(self):
        return len(self.bfs)
    def __iter__(self):
        return self.bfs
    def __getitem__(self, item):
        return self.bfs[item]


text:
package com.kunsoftware.entity;

import java.util.Date;

public class FlightChedule {
    private Integer id;

    private Integer productResourceId;

    private Date startDate;

    private String valid;

    private String audit;

    private String status;

    private Date lastReservationDate;

    private Integer count;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getProductResourceId() {
        return productResourceId;
    }

    public void setProductResourceId(Integer productResourceId) {
        this.productResourceId = productResourceId;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public String getValid() {
        return valid;
    }

    public void setValid(String valid) {
        this.valid = valid;
    }

    public String getAudit() {
        return audit;
    }

    public void setAudit(String audit) {
        this.audit = audit;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getLastReservationDate() {
        return lastReservationDate;
    }

    public void setLastReservationDate(Date lastReservationDate) {
        this.lastReservationDate = lastReservationDate;
    }

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}

}


text:
export const getStateStyles = (theme, props) => {
  if (props.primary) {
    return theme.primary;
  }
  if (props.secondary) {
    return theme.secondary;
  }
  if (props.disabled) {
    return theme.disabled;
  }

  return false;
};


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

package org.chromium.ui.display;

/**
 * Contains all of the command line switches that are specific to the display.
 */
public abstract class DisplaySwitches {
    // Native switch - display_switches::kForceDeviceScaleFactor
    public static final String FORCE_DEVICE_SCALE_FACTOR = "force-device-scale-factor";

    // Prevent instantiation.
    private DisplaySwitches() {}
}


text:
title: MySQL
menu:
  docs_0.11.0:
    identifier: mysql-db
    name: MySQL
    parent: databases
    weight: 25
menu_name: docs_0.11.0
section_menu_id: concepts
---

> New to KubeDB? Please start [here](/docs/concepts/README.md).

# MySQL

## What is MySQL

`MySQL` is a Kubernetes `Custom Resource Definitions` (CRD). It provides declarative configuration for [MySQL](https://www.mysql.com/) in a Kubernetes native way. You only need to describe the desired database configuration in a MySQL object, and the KubeDB operator will create Kubernetes objects in the desired state for you.

## MySQL Spec

As with all other Kubernetes objects, a MySQL needs `apiVersion`, `kind`, and `metadata` fields. It also needs a `.spec` section. Below is an example MySQL object.

```yaml
apiVersion: kubedb.com/v1alpha1
kind: MySQL
metadata:
  name: m1
  namespace: demo
spec:
  version: "8.0-v2"
  databaseSecret:
    secretName: m1-auth
  storageType: "Durable"
  storage:
    storageClassName: "standard"
    accessModes:
    - ReadWriteOnce
    resources:
      requests:
        storage: 1Gi
  init:
    scriptSource:
      configMap:
        name: mg-init-script
  backupSchedule:
    cronExpression: "@every 2m"
    storageSecretName: ms-snap-secret
    gcs:
      bucket: kubedb-qa
      prefix: demo
  monitor:
    agent: prometheus.io/coreos-operator
    prometheus:
      namespace: demo
      labels:
        app: kubedb
      interval: 10s
  configSource:
    configMap:
      name: my-custom-config
  podTemplate:
    annotations:
      passMe: ToDatabasePod
    controller:
      annotations:
        passMe: ToStatefulSet
    spec:
      schedulerName: my-scheduler
      nodeSelector:
        disktype: ssd
      imagePullSecrets:
      - name: myregistrykey
      args:
      - --character-set-server=utf8mb4
      env:
      - name: MYSQL_DATABASE
        value: myDB
      resources:
        requests:
          memory: "64Mi"
          cpu: "250m"
        limits:
          memory: "128Mi"
          cpu: "500m"
  serviceTemplate:
    annotations:
      passMe: ToService
    spec:
      type: NodePort
      ports:
      - name:  http
        port:  9200
        targetPort: http
  terminationPolicy: Pause
  updateStrategy:
    type: RollingUpdate
```

### spec.version

`spec.version` is a required field specifying the name of the [MySQLVersion](/docs/concepts/catalog/mysql.md) crd where the docker images are specified. Currently, when you install KubeDB, it creates the following `MySQLVersion` crd,

- `8.0-v2`, `8.0`, `8-v1`, `8`
- `5.7-v1`, `5.7`, `5-v1`, `5`

### spec.databaseSecret

`spec.databaseSecret` is an optional field that points to a Secret used to hold credentials for `mysql` root user. If not set, KubeDB operator creates a new Secret `{mysql-object-name}-auth` for storing the password for `mysql` root user for each MySQL object. If you want to use an existing secret please specify that when creating the MySQL object using `spec.databaseSecret.secretName`.

This secret contains a `user` key and a `password` key which contains the `username` and `password` respectively for `mysql` root user. Here, the value of `user` key is fixed to be `root`.

Example:

```console
$ kubectl create secret generic m1-auth -n demo \
--from-literal=user=root \
--from-literal=password=6q8u_2jMOW-OOZXk
secret "m1-auth" created
```

```yaml
apiVersion: v1
data:
  password: NnE4dV8yak1PVy1PT1pYaw==
  user: cm9vdA==
kind: Secret
metadata:
  ...
  name: m1-auth
  namespace: demo
  ...
type: Opaque
```

### spec.storageType

`spec.storageType` is an optional field that specifies the type of storage to use for database. It can be either `Durable` or `Ephemeral`. The default value of this field is `Durable`. If `Ephemeral` is used then KubeDB will create MySQL database using [emptyDir](https://kubernetes.io/docs/concepts/storage/volumes/#emptydir) volume. In this case, you don't have to specify `spec.storage` field.

### spec.storage

Since 0.9.0-rc.0, If you set `spec.storageType:` to `Durable`, then  `spec.storage` is a required field that specifies the StorageClass of PVCs dynamically allocated to store data for the database. This storage spec will be passed to the StatefulSet created by KubeDB operator to run database pods. You can specify any StorageClass available in your cluster with appropriate resource requests.

- `spec.storage.storageClassName` is the name of the StorageClass used to provision PVCs. PVCs don't necessarily have to request a class. A PVC with its storageClassName set equal to "" is always interpreted to be requesting a PV with no class, so it can only be bound to PVs with no class (no annotation or one set equal to ""). A PVC with no storageClassName is not quite the same and is treated differently by the cluster depending on whether the DefaultStorageClass admission plugin is turned on.
- `spec.storage.accessModes` uses the same conventions as Kubernetes PVCs when requesting storage with specific access modes.
- `spec.storage.resources` can be used to request specific quantities of storage. This follows the same resource model used by PVCs.

To learn how to configure `spec.storage`, please visit the links below:

- https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims

### spec.init

`spec.init` is an optional section that can be used to initialize a newly created MySQL database. MySQL databases can be initialized in one of two ways:

  1. Initialize from Script
  2. Initialize from Snapshot

#### Initialize via Script

To initialize a MySQL database using a script (shell script, sql script etc.), set the `spec.init.scriptSource` section when creating a MySQL object. It will execute files alphabetically with extensions `.sh` , `.sql`  and `.sql.gz` that are found in the repository. The scripts inside child folders will be skipped. ScriptSource must have following information:

- [VolumeSource](https://kubernetes.io/docs/concepts/storage/volumes/#types-of-volumes): Where your script is loaded from.

Below is an example showing how a script from a configMap can be used to initialize a MySQL database.

```yaml
apiVersion: kubedb.com/v1alpha1
kind: MySQL
metadata:
  name: m1
spec:
  version: 8.0-v2
  init:
    scriptSource:
      configMap:
        name: mysql-init-script
```

In the above example, KubeDB operator will launch a Job to execute all js script of `mysql-init-script` in alphabetical order once StatefulSet pods are running. For more details tutorial on how to initialize from script, please visit [here](/docs/guides/mysql/initialization/script-source.md).

#### Initialize from Snapshots

To initialize from prior snapshots, set the `spec.init.snapshotSource` section when creating a MySQL object. In this case, SnapshotSource must have following information:

- `name:` Name of the Snapshot
- `namespace:` Namespace of the Snapshot

```yaml
apiVersion: kubedb.com/v1alpha1
kind: MySQL
metadata:
  name: m1
spec:
  version: 8.0-v2
  init:
    snapshotSource:
      name: "snapshot-xyz"
      namespace: "demo"
```

In the above example, MySQL database will be initialized from Snapshot `snapshot-xyz` in `demo` namespace. Here, KubeDB operator will launch a Job to initialize MySQL once StatefulSet pods are running.

When initializing from Snapshot, root user credentials must have to match with the previous one. For example, let's say, Snapshot `snapshot-xyz` is for MySQL `mysql-old`. In this case, new MySQL `mysql-db` should use the same credentials for root user of `mysql-old`. Otherwise, the restoration process will fail.

For more details tutorial on how to initialize from snapshot, please visit [here](/docs/guides/mysql/initialization/snapshot-source.md).

### spec.backupSchedule

KubeDB supports taking periodic snapshots for MySQL database. This is an optional section in `.spec`. When `spec.backupSchedule` section is added, KubeDB operator immediately takes a backup to validate this information. After that, at each tick kubeDB operator creates a [Snapshot](/docs/concepts/snapshot.md) object. This triggers operator to create a Job to take backup. If used, set the various sub-fields accordingly.

- `spec.backupSchedule.cronExpression` is a required [cron expression](https://github.com/robfig/cron/blob/v2/doc.go#L26). This specifies the schedule for backup operations.
- `spec.backupSchedule.{storage}` is a required field that is used as the destination for storing snapshot data. KubeDB supports cloud storage providers like S3, GCS, Azure and OpenStack Swift. It also supports any locally mounted Kubernetes volumes, like NFS, Ceph, etc. Only one backend can be used at a time. To learn how to configure this, please visit [here](/docs/concepts/snapshot.md).

You can also specify a template for pod of backup job through `spec.backupSchedule.podTemplate`. KubeDB will use the information you have provided in `podTemplate` to create the backup job. KubeDB accept following fields to set in `spec.backupSchedule.podTemplate`:

- metadata:
  - annotations (pod's annotation)
- controller:
  - annotations (job's annotation)
- spec:
  - args
  - env
  - resources
  - imagePullSecrets
  - initContainers
  - nodeSelector
  - affinity
  - schedulerName
  - tolerations
  - priorityClassName
  - priority
  - securityContext
  - livenessProbe
  - readinessProbe
  - lifecycle

### spec.monitor

MySQL managed by KubeDB can be monitored with builtin-Prometheus and CoreOS-Prometheus operator out-of-the-box. To learn more,

- [Monitor MySQL with builtin Prometheus](/docs/guides/mysql/monitoring/using-builtin-prometheus.md)
- [Monitor MySQL with CoreOS Prometheus operator](/docs/guides/mysql/monitoring/using-coreos-prometheus-operator.md)

### spec.configSource

`spec.configSource` is an optional field that allows users to provide custom configuration for MySQL. This field accepts a [`VolumeSource`](https://github.com/kubernetes/api/blob/release-1.11/core/v1/types.go#L47). So you can use any kubernetes supported volume source such as `configMap`, `secret`, `azureDisk` etc. To learn more about how to use a custom configuration file see [here](/docs/guides/mysql/configuration/using-custom-config.md).

### spec.podTemplate

KubeDB allows providing a template for database pod through `spec.podTemplate`. KubeDB operator will pass the information provided in `spec.podTemplate` to the StatefulSet created for MySQL database.

KubeDB accept following fields to set in `spec.podTemplate:`

- metadata:
  - annotations (pod's annotation)
- controller:
  - annotations (statefulset's annotation)
- spec:
  - args
  - env
  - resources
  - initContainers
  - imagePullSecrets
  - nodeSelector
  - affinity
  - schedulerName
  - tolerations
  - priorityClassName
  - priority
  - securityContext
  - livenessProbe
  - readinessProbe
  - lifecycle

Uses of some field of `spec.podTemplate` is described below,

#### spec.podTemplate.spec.args

`spec.podTemplate.spec.args` is an optional field. This can be used to provide additional arguments to database installation. To learn about available args of `mysqld`, visit [here](https://dev.mysql.com/doc/refman/8.0/en/server-options.html).

#### spec.podTemplate.spec.env

`spec.podTemplate.spec.env` is an optional field that specifies the environment variables to pass to the MySQL docker image. To know about supported environment variables, please visit [here](https://hub.docker.com/_/mysql/).

Note that, KubeDB does not allow `MYSQL_ROOT_PASSWORD`, `MYSQL_ALLOW_EMPTY_PASSWORD`, `MYSQL_RANDOM_ROOT_PASSWORD`, and `MYSQL_ONETIME_PASSWORD` environment variables to set in `spec.env`. If you want to set the root password, please use `spec.databaseSecret` instead described earlier.

If you try to set any of the forbidden environment variables i.e. `MYSQL_ROOT_PASSWORD` in MySQL crd, Kubed operator will reject the request with following error,

```ini
Error from server (Forbidden): error when creating "./mysql.yaml": admission webhook "mysql.validators.kubedb.com" denied the request: environment variable MYSQL_ROOT_PASSWORD is forbidden to use in MySQL spec
```

Also note that KubeDB does not allow to update the environment variables as updating them does not have any effect once the database is created.  If you try to update environment variables, KubeDB operator will reject the request with following error,

```ini
Error from server (BadRequest): error when applying patch:
...
for: "./mysql.yaml": admission webhook "mysql.validators.kubedb.com" denied the request: precondition failed for:
...At least one of the following was changed:
    apiVersion
    kind
    name
    namespace
    spec.databaseSecret
    spec.init
    spec.storageType
    spec.storage
    spec.podTemplate.spec.nodeSelector
    spec.podTemplate.spec.env
```

#### spec.podTemplate.spec.imagePullSecrets

`KubeDB` provides the flexibility of deploying MySQL database from a private Docker registry. `spec.podTemplate.spec.imagePullSecrets` is an optional field that points to secrets to be used for pulling docker image if you are using a private docker registry. To learn how to deploy MySQL from a private registry, please visit [here](/docs/guides/mysql/private-registry/using-private-registry.md).

#### spec.podTemplate.spec.nodeSelector

`spec.podTemplate.spec.nodeSelector` is an optional field that specifies a map of key-value pairs. For the pod to be eligible to run on a node, the node must have each of the indicated key-value pairs as labels (it can have additional labels as well). To learn more, see [here](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector) .

#### spec.podTemplate.spec.resources

`spec.podTemplate.spec.resources` is an optional field. This can be used to request compute resources required by the database pods. To learn more, visit [here](http://kubernetes.io/docs/user-guide/compute-resources/).

### spec.serviceTemplate

You can also provide a template for the services created by KubeDB operator for MySQL database through `spec.serviceTemplate`. This will allow you to set the type and other properties of the services.

KubeDB allows following fields to set in `spec.serviceTemplate`:

- metadata:
  - annotations
- spec:
  - type
  - ports
  - clusterIP
  - externalIPs
  - loadBalancerIP
  - loadBalancerSourceRanges
  - externalTrafficPolicy
  - healthCheckNodePort

### spec.updateStrategy

You can specify [update strategy](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#update-strategies) of StatefulSet created by KubeDB for MySQL database thorough `spec.updateStrategy` field. The default value of this field is `RollingUpdate`. In future, we will use this field to determine how automatic migration from old KubeDB version to new one should behave.

### spec.terminationPolicy

`terminationPolicy` gives flexibility whether to `nullify`(reject) the delete operation of `MySQL` crd or which resources KubeDB should keep or delete when you delete `MySQL` crd. KubeDB provides following four termination policies:

- DoNotTerminate
- Pause (`Default`)
- Delete
- WipeOut

When, `terminationPolicy` is `DoNotTerminate`, KubeDB takes advantage of `ValidationWebhook` feature in Kubernetes 1.9.0 or later clusters to implement `DoNotTerminate` feature. If admission webhook is enabled, `DoNotTerminate` prevents users from deleting the database as long as the `spec.terminationPolicy` is set to `DoNotTerminate`.

Following table show what KubeDB does when you delete MySQL crd for different termination policies,

|              Behaviour              | DoNotTerminate |  Pause   |  Delete  | WipeOut  |
| ----------------------------------- | :------------: | :------: | :------: | :------: |
| 1. Block Delete operation           |    ✓    | ✗ | ✗ | ✗ |
| 2. Create Dormant Database          |    ✗    | ✓ | ✗ | ✗ |
| 3. Delete StatefulSet               |    ✗    | ✓ | ✓ | ✓ |
| 4. Delete Services                  |    ✗    | ✓ | ✓ | ✓ |
| 5. Delete PVCs                      |    ✗    | ✗ | ✓ | ✓ |
| 6. Delete Secrets                   |    ✗    | ✗ | ✗ | ✓ |
| 7. Delete Snapshots                 |    ✗    | ✗ | ✗ | ✓ |
| 8. Delete Snapshot data from bucket |    ✗    | ✗ | ✗ | ✓ |

If you don't specify `spec.terminationPolicy` KubeDB uses `Pause` termination policy by default.

## Next Steps

- Learn how to use KubeDB to run a MySQL database [here](/docs/guides/mysql/README.md).
- See the list of supported storage providers for snapshots [here](/docs/concepts/snapshot.md).
- Want to hack on KubeDB? Check our [contribution guidelines](/docs/CONTRIBUTING.md).


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:materialdesign="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="144dp"
    android:layout_margin="8dp"
    android:background="@drawable/ic_background"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/recommendfragment_item_book_image"
        android:layout_width="144dp"
        android:layout_height="144dp"
        android:layout_gravity="center_vertical"
        android:layout_marginRight="4dp"
        android:contentDescription="@string/image_contentdescription"
        android:src="@drawable/bookpricture" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/recommendfragment_item_book_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:textColor="#000000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/recommendfragment_item_book_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <com.gc.materialdesign.views.ButtonFlat
                android:id="@+id/recommendfragment_item_book_online"
                android:layout_width="wrap_content"
                android:layout_height="48dp"
                android:background="#afafaf"
                android:text="@string/recommendfragment_item_book_online" />

            <com.gc.materialdesign.views.ButtonFlat
                android:id="@+id/recommendfragment_item_book_download"
                android:layout_width="wrap_content"
                android:layout_height="48dp"
                android:background="#afafaf"
                android:text="@string/recommendfragment_item_book_download" />
        </LinearLayout>

        <com.gc.materialdesign.views.Slider
            android:id="@+id/recommendfragment_item_book_slider"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:background="#1E88E5"
            materialdesign:max="50"
            materialdesign:min="0"
            materialdesign:showNumberIndicator="true" />
    </LinearLayout>

</LinearLayout>


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// Script to control Menus in Business Finances Menu

public class BusinessFinancesMenuControl : MonoBehaviour {

	/*===================== GameObjects =====================================================================================*/

	// Menus

	public GameObject maintenanceMenu;
	public GameObject fundingMenu;
	public GameObject employeeSalMenu;

	/*===================== UI Elements =====================================================================================*/

	// Buttons

	public Button maintenanceButton;
	public Button fundingButton;
	public Button employeeSalButton;

	// Text

	public Text headingText;

	/*===================== Methods =====================================================================================*/

	/*===================== maintenanceButtonControl() =====================================================================================*/

	// Fires when maintenanceButton is Clicked
	public void maintenanceButtonControl(){

		// Turn off other menus
		fundingMenu.SetActive (false);
		employeeSalMenu.SetActive (false);

		// Update Heading Text
		headingText.text = "Building Maintenance";

		// Turn on Menu
		maintenanceMenu.SetActive (true);

		// Disable button to show it was selected
		maintenanceButton.interactable = false;

		// Activate other menu buttons
		fundingButton.interactable = true;
		employeeSalButton.interactable = true;

	} // maintenanceControl()

	/*===================== fundingButtonControl() =====================================================================================*/

	// Fires when fundingButton is Clicked
	public void fundingButtonControl(){

		// Turn off other menus
		maintenanceMenu.SetActive (false);
		employeeSalMenu.SetActive (false);

		// Update Heading Text
		headingText.text = "Funding";

		// Turn on Menu
		fundingMenu.SetActive (true);

		// Disable button to show it was selected
		fundingButton.interactable = false;

		// Activate other menu buttons
		maintenanceButton.interactable = true;
		employeeSalButton.interactable = true;

	} // fundingButtonControl()

	/*===================== employeeSalaryButtonControl() =====================================================================================*/

	// Fires when employeeSalButton is Clicked
	public void employeeSalaryButtonControl(){

		// Turn off other menus
		maintenanceMenu.SetActive (false);
		fundingMenu.SetActive (false);

		// Update Heading Text
		headingText.text = "Employee Salary";

		// Turn on Menu
		employeeSalMenu.SetActive (true);

		// Disable button to show it was selected
		employeeSalButton.interactable = false;

		// Activate other menu buttons
		maintenanceButton.interactable = true;
		fundingButton.interactable = true;

	} // employeeSalaryButtonControl()

} // class


text:
<?php

namespace jlandfried\ReadTime\Counter;

use QueryPath\Query;

interface QueryCounterInterface {
  public function count(Query $query, $selector);
}


text:
`npm install -g reveal-md`

`npm start`

---

Security

### with

#### hello@cjr.co.de
#### CJ on Denver Devs

---

## Agenda

* whoami
* Why security?
* Security with Node.JS/Express

---

# `whoami`

----

CJ

Lead Instructor, Sr. Full Stack Developer

at

---

# Why security?

----

# Show  of hands:
## Who here develops web applications?

----

# Show  of hands:
## Who here is a security engineer?

----

### If you are a web developer you probably don't think of yourself as a security engineer.

>"Our clients don't pay us for security; they want it pretty, they want it feature-complete, and most importantly they want it done yesterday."

[A Gentle Introduction to Application Security](https://paragonie.com/blog/2015/08/gentle-introduction-application-security)

----

# Fact:
### The second your code is deployed in production, your code is the front line of defense for that entire system and quite possibly the entire network.

----

### Logically, that means the software you produce must be made reasonably secure.

----

## Application Security is Every Developer's Responsibility

You _don't_ have to be an expert.

Anything you develop with security in mind will still move the needle in your organization as well as any clients you work with.

---

The topics discussed in this talk are heavily influenced by the [Web Application Security Testing Cheat Sheet](https://www.owasp.org/index.php/Web_Application_Security_Testing_Cheat_Sheet) maintained by [OWASP - Open Web Application Security Project](https://www.owasp.org/index.php/Main_Page) and the [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/) by RisingStack.

---

Security with Node.JS/Express

Mitigate common attacks by setting security related headers

Protect against brute force authentication attacks

Manage sessions using cookie best practices

Mitigate CSRF attacks

Validate Data to prevent XSS, SQL Injection and Command Injection

Ensure secure transmission by testing SSL and HSTS

Check NPM dependencies for known vulnerabilities

---

## Mitigate common attacks by setting security related headers

----

## Headers

Setting headers from the server is easy and often doesn't require any code changes. Once set, they can restrict modern browsers from running into easily preventable vulnerabilities.

[OWASP Secure Headers Project](https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#tab=Headers)

----

## Helmet

[Helmet](https://github.com/helmetjs/helmet) helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help!

Helmet is a collection of 10 smaller middleware functions that set HTTP headers:

- [contentSecurityPolicy](https://github.com/helmetjs/csp) for setting Content Security Policy
- [dnsPrefetchControl](https://github.com/helmetjs/dns-prefetch-control) controls browser DNS prefetching
- [frameguard](https://github.com/helmetjs/frameguard) to prevent clickjacking
- [hidePoweredBy](https://github.com/helmetjs/hide-powered-by) to remove the X-Powered-By header
- [hpkp](https://github.com/helmetjs/hpkp) for HTTP Public Key Pinning
- [hsts](https://github.com/helmetjs/hsts) for HTTP Strict Transport Security
- [ieNoOpen](https://github.com/helmetjs/ienoopen) sets X-Download-Options for IE8+
- [noCache](https://github.com/helmetjs/nocache) to disable client-side caching
- [noSniff](https://github.com/helmetjs/dont-sniff-mimetype) to keep clients from sniffing the MIME type
- [xssFilter](https://github.com/helmetjs/x-xss-protection) adds some small XSS protections

----

## Helmet Usage

```sh
npm install -S helmet
```

```js
const express = require('express');
const helmet = require('helmet');

const app = express();

app.use(helmet());
```

Running `app.use(helmet())` will include 7 of the 10, leaving out `contentSecurityPolicy`, `hpkp`, and `noCache`. You can also use each module individually.

---

## Protect against brute force authentication attacks

----

## Brute Force

In cryptography, a brute-force attack consists of an attacker trying many passwords or passphrases with the hope of eventually guessing correctly. The attacker systematically checks all possible passwords and passphrases until the correct one is found.

[via Wikipedia](https://en.wikipedia.org/wiki/Brute-force_attack)

https://github.com/vanhauser-thc/thc-hydra

----

## Rate Limiting

Limiting the number of requests a user can make can protect your application from brute force attacks.

----

## [express-bouncer](https://github.com/dkrutsko/express-bouncer)

A simple and standalone middleware for express routes which attempts to mitigate brute-force attacks. It works by increasing the delay with each failed request using a Fibonacci formula. Requests are tracking via IP address and can be white-listed or reset on demand.

```js
// Creates a new instance of our bouncer (args optional)
var bouncer = require ("express-bouncer")(500, 900000);

// Add white-listed addresses (optional)
bouncer.whitelist.push ("127.0.0.1");

// In case we want to supply our own error (optional)
bouncer.blocked = function (req, res, next, remaining) {
    res.send (429, "Too many requests have been made, " +
        "please wait " + remaining / 1000 + " seconds");
};

// Route we wish to protect with bouncer middleware
app.post ("/login", bouncer.block, function (req, res) {
    if (LoginFailed) {
        // Login failed
    } else {
        bouncer.reset (req);
        // Login succeeded
    }
});

// Clear all logged addresses
// (Usually never really used)
bouncer.addresses = { };
```

----

## ratelimiter

ratelimiter is an abstract rate limiter for Node.js backed by redis.

`npm install -S ratelimiter`

### Options

 - `id` - the identifier to limit against (typically a user id)
 - `db` - redis connection instance
 - `max` - max requests within `duration` [2500]
 - `duration` - of limit in milliseconds [3600000]

----

## ratelimiter usage

Can be used as a middleware to protect ALL routes.

```js
app.use((req, res, next) => {
  var id = req.user._id;
  var limit = new Limiter({ id: id, db: db });
  limit.get(function(err, limit){
    if (err) return next(err);

    res.set('X-RateLimit-Limit', limit.total);
    res.set('X-RateLimit-Remaining', limit.remaining - 1);
    res.set('X-RateLimit-Reset', limit.reset);

    // all good
    debug('remaining %s/%s %s', limit.remaining - 1, limit.total, id);
    if (limit.remaining) return next();

    // not good
    var delta = (limit.reset * 1000) - Date.now() | 0;
    var after = limit.reset - (Date.now() / 1000) | 0;
    res.set('Retry-After', after);
    res.send(429, 'Rate limit exceeded, retry in ' + ms(delta, { long: true }));
  });
});
```

---

Manage sessions using cookie best practices

----

## Cookie Flags

There are several attributes that can be set on a cookie:
* `secure` - this attribute tells the browser to only send the cookie if the request is being sent over HTTPS.
* `HttpOnly` - this attribute is used to help prevent attacks such as cross-site scripting, since it does not allow the cookie to be accessed via JavaScript.

----

## Cookie Scope

* `domain` - this attribute is used to compare against the domain of the server in which the URL is being requested. If the domain matches or if it is a sub-domain, then the path attribute will be checked next.
* `path` - in addition to the domain, the URL path that the cookie is valid for can be specified. If the domain and path match, then the cookie will be sent in the request.
* `expires` - this attribute is used to set persistent cookies, since the cookie does not expire until the set date is exceeded

----

## cookies in Express

In a newly generated express app, all options are off _by default_

```js
app.use(cookieParser())
```

Set some sensible defaults:

```js
app.use(cookieParser(process.env.COOKIE_SECRET, {
  secure: true,
  httpOnly: true,
  domain: process.env.DOMAIN,
  expires:
}));
```

[cookie-parser on npm](https://www.npmjs.com/package/cookie-parser)

[cookie on npm](https://www.npmjs.com/package/cookie)

---

## Mitigate CSRF attacks

----

## CSRF

Cross-Site Request Forgery is an attack that forces a user to execute unwanted actions on a web application in which they're currently logged in. These attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.

via OWASP

[NodeGoat](https://github.com/OWASP/NodeGoat) - an environment to learn how OWASP Top 10 security risks apply to Node.js

[NodeGoat CSRF demo](https://nodegoat.herokuapp.com/tutorial/a8)

----

## csurf

Node.js CSRF protection middleware.

`npm install -S csurf`

----

## csurf usage

```js
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')

var app = express()
app.use(cookieParser())

var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })

app.get('/form', csrfProtection, function(req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
})

app.post('/process', parseForm, csrfProtection, function(req, res) {
  res.send('data is being processed')
})
```

----

## csurf usage

```html
<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">

  Favorite color: <input type="text" name="favoriteColor">
  <button type="submit">Submit</button>
</form>
```

---

## Validate Data to prevent XSS, SQL Injection and Command Injection

----

# Always filter and sanitize user input.

----

## Input comes from _many_ places
* Query parameters
* URL path
* PUT/POST parameters
* Cookies
* Headers
* File uploads
* Emails
* Form fields
* etc.

----

## XSS

There are 2 types of XSS attacks:

### Reflected Cross site scripting

The attacker injects executable JavaScript code into the HTML response with specially crafted links.

```
http://example.com/?user=<script>alert('pwned')</script>
```

### Stored Cross site scripting

The application stores user input which is not correctly filtered. It runs within the user's browser under the privileges of the web application.

[NodeGoat Stored XSS Demo](https://nodegoat.herokuapp.com/tutorial/a3)

----

## SQL Injection

Injection of a partial or complete SQL query via user input. It can read sensitive information or be destructive as well.

```SQL
select title, author from books where id=$id
```

`$id` is coming from the user - what if the user enters 2 or 1=1? The query becomes the following:

```SQL
select title, author from books where id=2 or 1=1
```

The easiest way to defend against these kind of attacks is to use parameterized queries or prepared statements.

If you are using PostgreSQL from Node.js then you probably using the node-postgres module. To create a parameterized query:

```js
var q = 'SELECT name FROM books WHERE id = $1';
client.query(q, ['3'], function(err, result) {});
```

----

## SQL Injection Testing

http://sqlmap.org/

----

## Command Injection

A technique used by an attacker to run OS commands on the remote web server.

For example:

`https://example.com/downloads?file=user1.txt`

`https://example.com/downloads?file=%3Bcat%20/etc/passwd`

In this example %3B becomes the semicolon, so multiple OS commands can be run.

----

## A few take aways for data validation:

----

#### Always filter and sanitize user input.

----

### Always filter and sanitize user input.

----

## Always filter and sanitize user input.

----

# Always filter and sanitize user input.

---

## Ensure secure transmission by testing SSL and HSTS

----

## Secure Transmission

### SSL Version, Algorithms, Key length

As HTTP is a clear-text protocol it must be secured via SSL/TLS tunnel, known as HTTPS. Nowadays high grade ciphers are normally used, misconfiguration in the server can be used to force the use of a weak cipher - or at worst no encryption.

You have to test:

* ciphers, keys and renegotiation is properly configured
* certificate validity

----

## Checking for Certificate information

#### [nmap](https://nmap.org/)

```sh
nmap --script ssl-cert,ssl-enum-ciphers -p 443,465,993,995 www.example.com
```

----

## Testing SSL/TLS vulnerabilities with sslyze

#### [sslyze](https://github.com/iSECPartners/sslyze)

```sh
./sslyze.py --regular example.com:443
```

----

## HSTS

The `Strict-Transport-Security` header enforces secure (HTTP over SSL/TLS) connections to the server. Take the following example from Twitter:

`strict-transport-security:max-age=631138519`

Here the max-age defines the number of seconds that the browser should automatically convert all HTTP requests to HTTPS.

Testing for it is pretty straightforward:

`curl -s -D- https://twitter.com/ | grep -i Strict`

---

## Check NPM dependencies for known vulnerabilities

----

> Any dildo can publish something to npm.

-Kyle Coberly

----

## NPM

With great power comes great responsibility - NPM has lots of packages what you can use instantly, but that comes with a cost: you should check what you are requiring to your applications. They may contain security issues that are critical.

----

## Node Security Platform

Check your npm dependencies for known vulnerabilities.

```sh
npm install -g nsp
nsp check # audit package.json
```

----

## Snyk

Snyk is similar to the Node Security Platform, but its aim is to provide a tool that can not just detect, but fix security related issues in your codebase.

```sh
npm install -g snyk
snyk test # audit node_modules directory
```

---

# Review

----

## Mitigate common attacks by setting security related headers

----

## Protect against brute force authentication attacks

----

## Manage sessions using cookie best practices

----

## Mitigate CSRF attacks

----

## Validate Data to prevent XSS, SQL Injection and Command Injection

----

## Ensure secure transmission by testing SSL and HSTS

----

## Check NPM dependencies for known vulnerabilities

---

# Final Thoughts

----

## Knowing is half the battle!

----

## Application Security is Every Developer's Responsibility

This doesn't mean you have to be an expert. You can take one step forward on the path towards expertise and stop, and it will still move the needle in your organization as well as any clients you work with.

----

## Security is a mindset, checklist/Top 10 is a place to start, but don't stop there!

---

# Resources

* [reveal-md for slides](https://github.com/webpro/reveal-md)
* [Animations](https://flixel.com/cinemagraphs/fresh/)
* [Node.js Security Checklist](https://blog.risingstack.com/node-js-security-checklist/)
* [OWASP - Open Web Application Security Project](https://www.owasp.org/index.php/Main_Page)
* [Web Application Security Testing Cheat Sheet](https://www.owasp.org/index.php/Web_Application_Security_Testing_Cheat_Sheet)
* [NodeGoat](https://github.com/OWASP/NodeGoat)
* [Node.js Security Tips](https://blog.risingstack.com/node-js-security-tips/)
* [A Gentle Introduction to Application Security](https://paragonie.com/blog/2015/08/gentle-introduction-application-security)
* [Top Overlooked Security Threats To Node.js Web Applications](http://conferences.oreilly.com/fluent/fluent2014/public/schedule/detail/32664)

---

is Hiring!

gjobs.link/ByTeam

---

Thank you!

Security

##### with

#### hello@cjr.co.de
#### CJ on Denver Devs


text:
;(function(){
	$.fn.ImageZoom = function(settings){
		var arr = [];
		$(this).each(function(){
			var options = $.extend({target: $(this)}, settings);
			var imageZoom = new ImageZoom();
			imageZoom.init(options);
			arr.push(imageZoom);
		});
		return arr;
	}

	var ImageZoom = function() {};

	ImageZoom.prototype = {
		init: function(args){
			this.settings = $.extend({
				width: 100,
				height: 100,
				times: 2,
				handle: false,
				callback: null
			}, args);
			this.zoomArea = $('#zoomArea');
			this.bindEvent();
		},
		bindEvent: function(){
			this.zoomArea.on('touchmove', function(e){
				return this.event['zoommove'].call(this.zoomArea, e, this);
			}.bind(this));

			var isMouseClicked = false;
			$('body').on('mousedown', $('#zoomArea'), function(e){
				isMouseClicked = true;
			});
			$('body').on('mouseup', $('#zoomArea'), function(e){
				isMouseClicked = false;
				return this.event['mouseup'].call(this.zoomArea, e, this);
			}.bind(this));

			$('body').on('mousemove', $('#zoomArea'), function(e){
				return isMouseClicked && this.event['zoommove'].call(this.zoomArea, e, this);
			}.bind(this));

			$(this.settings.target).on('touchstart', function(e){
				this.event['mousedown'].call(this.settings.target, e, this);
			}.bind(this));

			$(this.settings.target).on('mousedown', function(e){
				this.event['mousedown'].call(this.settings.target, e, this);
			}.bind(this));
			$(this.settings.target).on('touchmove', function(e){
				return this.event['mousemove'].call(this.settings.target, e, this);
			}.bind(this));
			$(this.settings.target).on('mousemove', function(e){
				return isMouseClicked && this.event['mousemove'].call(this.settings.target, e, this);
			}.bind(this));
			$(this.settings.target).on('touchend', function(e) {
				return this.event['mouseup'].call(this.settings.target, e, this);
			}.bind(this));
			$(this.settings.target).on('mouseup', function(e) {
				return this.event['mouseup'].call(this.settings.target, e, this);
			}.bind(this));
			$('body').on('mouseup', function(e){
				if($('#zoomArea').is(':visible')){
					$('#zoomArea').hide();
				}
			});
		},

		event: {
			zoommove: function(e, _this){
				var touch = e.changedTouches ? e.changedTouches : e;
				_this.setPosition(touch.pageX, touch.pageY, _this.settings.target);
				return false;
			},
			mousedown: function(e, _this){
				var touch = e.changedTouches ? e.changedTouches : e;
				_this.createZoom.call(_this, this);
				_this.setPosition(touch.pageX, touch.pageY, this);
			},
			mousemove: function(e, _this){
				var touch = e.changedTouches ? e.changedTouches : e;
				_this.setPosition(touch.pageX, touch.pageY, this);
				return false;
			},
			mouseup: function(e, _this){
				_this.removeZoom();
				return false;
			}
		},

		removeZoom: function(){
			this.zoomArea.hide();
		},

		createZoom: function(pic){
			this.zoomArea = $('<div id="zoomArea" style="position:absolute;background:none;"/>');
			$('body').append(this.zoomArea);
			this.zoomArea.css({
				'position': 'absolute',
				'background': 'url(' + $(pic).attr('src') + ') no-repeat',
				'borderRadius': this.settings.width + 'px ' + this.settings.height + 'px',
				'border': '1px solid #ccc'
			}).width(this.settings.width).height(this.settings.height);
			this.zoomArea.show();
		},

		setPosition: function(x, y, pic){
			var offset = $(pic).offset();
			var picHeight = $(pic).height();
			var picWidth = $(pic).width();

			x = Math.max(Math.min(x, offset.left + picWidth), offset.left);
			y = Math.max(Math.min(y, offset.top + picHeight), offset.top);

			var startPoint = {
				x: x - this.settings.width / 2,
				y: y - this.settings.height / 2
			};
			var zoomSize = {
				height: picHeight * this.settings.times,
				width: picWidth * this.settings.times
			};
			var showPoint = {
				x: (x - offset.left) * this.settings.times - this.settings.width / 2,
				y: (y - offset.top) * this.settings.times - this.settings.height / 2
			};
			this.zoomArea.css({
				left: startPoint.x,
				top: startPoint.y,
				'backgroundPosition': -showPoint.x + 'px ' + (-showPoint.y) + 'px',
				'backgroundSize': zoomSize.width + 'px ' + zoomSize.height + 'px'
			});
		}
	}
})(jQuery);


text:
package com.ait.toolkit.sencha.touch.client.events.spinner;

import com.ait.toolkit.sencha.touch.client.ui.Spinner;
import com.google.gwt.event.dom.client.DomEvent.Type;

public class SpinUpEvent {

	public static String EVENT_NAME = "spindup";

	@SuppressWarnings("rawtypes")
	private Spinner source;
	private int value;

	public SpinUpEvent(@SuppressWarnings("rawtypes") Spinner source, int value) {
		this.source = source;
		this.value = value;
	}

	/**
	 * UiBinder implementations
	 */
	private static Type<SpinUpHandler> TYPE = new Type<SpinUpHandler>(EVENT_NAME, null);

	public static Type<SpinUpHandler> getType() {
		return TYPE;
	}

	public static Type<SpinUpHandler> getAssociatedType() {
		return TYPE;
	}

	@SuppressWarnings("rawtypes")
	public Spinner getSource() {
		return source;
	}

	public int getValue() {
		return value;
	}

}


text:
from networkapiclient.GenericClient import GenericClient
from networkapiclient.utils import get_list_map, is_valid_int_param
from networkapiclient.exception import InvalidParameterError

class AmbienteLogico(GenericClient):

    def __init__(self, networkapi_url, user, password, user_ldap=None):
        """Class constructor receives parameters to connect to the networkAPI.
        :param networkapi_url: URL to access the network API.
        :param user: User for authentication.
        :param password: Password for authentication.
        """
        super(
            AmbienteLogico,
            self).__init__(
            networkapi_url,
            user,
            password,
            user_ldap)

    def listar(self):
        """List all Logical Environment.

        :return: Dictionary with the following structure:

        ::

            {'logical_environment':
            [{'id': < id >,
            'nome': < nome >}, ...more Logical Environment...]}

        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        code, map = self.submit(None, 'GET', 'logicalenvironment/all/')

        key = 'logical_environment'
        return get_list_map(self.response(code, map, [key]), key)

    def inserir(self, name):
        """Inserts a new Logical Environment and returns its identifier.

        :param name: Logical Environment name. String with a minimum 2 and maximum of 80 characters

        :return: Dictionary with the following structure:

        ::

            {'logical_environment': {'id': < id_logical_environment >}}

        :raise InvalidParameterError: Name is null and invalid.
        :raise NomeAmbienteLogicoDuplicadoError: There is already a registered Logical Environment with the value of name.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        logical_environment_map = dict()
        logical_environment_map['name'] = name

        code, xml = self.submit(
            {'logical_environment': logical_environment_map}, 'POST', 'logicalenvironment/')

        return self.response(code, xml)

    def alterar(self, id_logicalenvironment, name):
        """Change Logical Environment from by the identifier.

        :param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero.
        :param name: Logical Environment name. String with a minimum 2 and maximum of 80 characters

        :return: None

        :raise InvalidParameterError: The identifier of Logical Environment or name is null and invalid.
        :raise NomeAmbienteLogicoDuplicadoError: There is already a registered Logical Environment with the value of name.
        :raise AmbienteLogicoNaoExisteError: Logical Environment not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_logicalenvironment):
            raise InvalidParameterError(
                u'The identifier of Logical Environment is invalid or was not informed.')

        url = 'logicalenvironment/' + str(id_logicalenvironment) + '/'

        logical_environment_map = dict()
        logical_environment_map['name'] = name

        code, xml = self.submit(
            {'logical_environment': logical_environment_map}, 'PUT', url)

        return self.response(code, xml)

    def remover(self, id_logicalenvironment):
        """Remove Logical Environment from by the identifier.

        :param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero.

        :return: None

        :raise InvalidParameterError: The identifier of Logical Environment is null and invalid.
        :raise AmbienteLogicoNaoExisteError: Logical Environment not registered.
        :raise DataBaseError: Networkapi failed to access the database.
        :raise XMLError: Networkapi failed to generate the XML response.
        """

        if not is_valid_int_param(id_logicalenvironment):
            raise InvalidParameterError(
                u'The identifier of Logical Environment is invalid or was not informed.')

        url = 'logicalenvironment/' + str(id_logicalenvironment) + '/'

        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)


text:
'use strict';

var should = require('should'),
    app = require('../../../server'),
    mongoose = require('mongoose'),
    request = require('supertest'),
    agent = request.agent(app),
    Event = mongoose.model('Event'),
    Tag = mongoose.model('Tag'),
    User = mongoose.model('User');

describe('Event routing', function() {
    var user,
        email = 'testing@example.com',
        password = 'test password';

    before(function(done) {
        user = new User({
            name: 'Test User',
            email: email,
            username: 'tester',
            password: password
        });
        user.save(done);
    });

    describe('Handle CRUD', function () {
        var tag_foo = new Tag({name: 'foo'}),
            tag_bar = new Tag({name: 'bar'});
        tag_foo.save();
        tag_bar.save();
        var tags = [tag_foo.id, tag_bar.id];

        var author = new User({
            name: 'Some author',
            email: 'foo@bar.com',
            username: 'author',
            password: 'password1234'
        });
        author.save();

        var event = {
            title: 'Event Title',
            tags: tags,
            content: 'This is my event description',
            author: author._id,
            startTime: new Date(),
            endTime: new Date(),
            address: '216 N Mosley, Wichita, KS 67202',
            latlng: [37.68858, -97.32753],
            url: 'http://startupwichita.com/event/1'
        };

        var persistedEvent;

        it('login', function(done) {
            agent
            .post('/users/session')
            .send({email: email, password: password})
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(302);
                done();
            });
        });

        it('should successfully insert a new event', function(done) {
            agent
            .post('/api/v1/events')
            .send(event)
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(201);
                persistedEvent = res.body;
                should.exist(persistedEvent.created_at);
                author._id.toString().should.be.eql(persistedEvent.author);
                tags.should.be.eql(persistedEvent.tags);
                done();
            });
        });

        it('should successfully render an rss feed', function(done) {
            agent
            .get('/api/v1/events.rss')
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(200);

                var xml2js = require('xml2js');
                var parser = new xml2js.Parser();
                parser.parseString(res.text, function(err, result) {
                    result.rss.channel[0].item.length.should.eql(1);

                    var item = result.rss.channel[0].item[0];

                    item.title.should.be.eql(['Event Title']);
                    item.link.should.be.eql(['http://startupwichita.com/event/1']);
                    item.description.should.be.eql(['This is my event description']);
                    item['content:encoded'].should.be.eql(['This is my event description']);

                    done();
                });
            });
        });

        it('should successfully retrieve one event', function(done) {
            agent
            .get('/api/v1/events')
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(200);
                res.body.length.should.eql(1);
                res.body[0].should.be.eql(persistedEvent);
                done();
            });
        });

        it('should successfully retrieve the specified event', function(done) {
            agent
            .get('/api/v1/events/' + persistedEvent._id)
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(200);
                res.body.should.be.eql(persistedEvent);
                done();
            });
        });

        it('should successfully update requested event', function(done) {
            var updatedEvent = persistedEvent;
            updatedEvent.content = 'Updated Content';

            agent
            .put('/api/v1/events/' + persistedEvent._id)
            .send(updatedEvent)
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(200);
                res.body.content.should.be.eql(updatedEvent.content);
                res.body.updated_at.should.not.be.eql(updatedEvent.updated_at);
                done();
            });
        });

        it('should successfully delete the specified event', function(done) {
            var updatedEvent = persistedEvent;
            updatedEvent.content = 'Updated Content';

            agent
            .del('/api/v1/events/' + persistedEvent._id)
            .end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(204);
                done();
            });
        });
    });

    after(function(done) {
        Event.remove({}, function(err) {
            if (err) return done();
            User.remove({}, function (err) {
                if (err) return done();
                Tag.remove({}, done);
            });
        });
    });
});


text:
.class Landroid/support/v4/view/ViewCompatJellybeanMr2;
.super Ljava/lang/Object;
.source "ViewCompatJellybeanMr2.java"

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 25
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getClipBounds(Landroid/view/View;)Landroid/graphics/Rect;
    .locals 1
    .param p0, "view"    # Landroid/view/View;

    .prologue
    .line 28
    invoke-virtual {p0}, Landroid/view/View;->getClipBounds()Landroid/graphics/Rect;

    move-result-object v0

    return-object v0
.end method

.method public static setClipBounds(Landroid/view/View;Landroid/graphics/Rect;)V
    .locals 0
    .param p0, "view"    # Landroid/view/View;
    .param p1, "clipBounds"    # Landroid/graphics/Rect;

    .prologue
    .line 32
    invoke-virtual {p0, p1}, Landroid/view/View;->setClipBounds(Landroid/graphics/Rect;)V

    .line 33
    return-void
.end method


text:
<?php

namespace FIPBank\UserBundle\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseForm;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationFormType extends BaseForm {

    public function buildForm(FormBuilderInterface $builder, array $option) {

        $builder->add('accountNumber', 'text', array(
                    'label' => 'Account Number',
                    'required' => true,
                ))
                ->add('role', 'choice', array(
                    'label' => 'Select Role:',
                    'choices' => array(
                        'ROLE_USER' => 'Customer',
                        'ROLE_ADMIN' => 'Admin',
                    ),
        ));
    }

    public function getParent() {
        return 'fos_user_registration';
    }

    public function getName() {
        return 'FIP_REG_FORM';
    }

}


text:
__author__ = 'Michael Montero <mcmontero@gmail.com>'

# ----- Imports ---------------------------------------------------------------

from tinyAPI.base.exception import tinyAPIException

__all__ = [
    'RDBMSBuilderException'
]

# ----- Public Classes --------------------------------------------------------

class RDBMSBuilderException(tinyAPIException):
    '''Named exception when issues with CLI arise.'''
    pass


text:
/* mammalPsg.h was originally generated by the autoSql program, which also
 * generated mammalPsg.c and mammalPsg.sql.  This header links the database and
 * the RAM representation of objects. */

/* Copyright (C) 2008 The Regents of the University of California
 * See README in this or parent directory for licensing information. */

#ifndef MAMMALPSG_H
#define MAMMALPSG_H

#define MAMMALPSG_NUM_COLS 34

struct mammalPsg
/* Browser extensible data (12 fields) plus the information on mammalian positive selection. */
    {
    struct mammalPsg *next;  /* Next in singly linked list. */
    char *chrom;	/* Chromosome (or contig, scaffold, etc.) */
    unsigned chromStart;	/* Start position in chromosome */
    unsigned chromEnd;	/* End position in chromosome */
    char *name;	/* Name of item */
    unsigned score;	/* 400 for P<0.05 on any test; 700 fdr significant under any test; 1000 fdr significant under test A */
    char strand[2];	/* + or - */
    unsigned thickStart;	/* Start of where display should be thick (start codon) */
    unsigned thickEnd;	/* End of where display should be thick (stop codon) */
    unsigned reserved;	/* Used as itemRgb as of 2004-11-22 */
    int blockCount;	/* Number of blocks */
    int *blockSizes;	/* Comma separated list of block sizes */
    int *chromStarts;	/* Start positions relative to chromStart */
    float lrtAllPValue;	/* A: LRT P-value  on all branches */
    unsigned char lrtAllIsFdr;	/* A: true if FDR significant */
    float lrtPrimateBrPValue;	/* B: LRT P-value  on branch leading to primates */
    unsigned char lrtPrimateBrIsFdr;	/* B: true if FDR significant */
    float lrtPrimateClPValue;	/* C: LRT P-value  on primate clade */
    unsigned char lrtPrimateClIsFdr;	/* C: true if FDR significant */
    float lrtRodentBrPValue;	/* D: LRT P-value  on branch leading to rodents */
    unsigned char lrtRodentBrIsFdr;	/* D: true if FDR significant */
    float lrtRodentClPValue;	/* E: LRT P-value  on rodent clade */
    unsigned char lrtRodentClIsFdr;	/* E: true if FDR significant */
    float lrtHumanPValue;	/* F: LRT P-value  on human lineage */
    unsigned char lrtHumanIsFdr;	/* F: true if FDR significant */
    float lrtChimpPValue;	/* G: LRT P-value  on chimp lineage */
    unsigned char lrtChimpIsFdr;	/* G: true if FDR significant */
    float lrtHominidPValue;	/* H: LRT P-value  on branch leading to hominids */
    unsigned char lrtHominidIsFdr;	/* H: true if FDR significant */
    float lrtMacaquePValue;	/* I: LRT P-value  on human lineage */
    unsigned char lrtMacaqueIsFdr;	/* I: true if FDR significant */
    unsigned bestHist;	/* Most likely history (Bayesian analysis) */
    float bestHistPP;	/* Probability of the most likely history */
    unsigned nextBestHist;	/* 2nd most likely history (Bayesian analysis) */
    float nextBestHistPP;	/* Probability of the 2nd most likely history */
    };

struct mammalPsg *mammalPsgLoad(char **row);
/* Load a mammalPsg from row fetched with select * from mammalPsg
 * from database.  Dispose of this with mammalPsgFree(). */

struct mammalPsg *mammalPsgLoadAll(char *fileName);
/* Load all mammalPsg from whitespace-separated file.
 * Dispose of this with mammalPsgFreeList(). */

struct mammalPsg *mammalPsgLoadAllByChar(char *fileName, char chopper);
/* Load all mammalPsg from chopper separated file.
 * Dispose of this with mammalPsgFreeList(). */

#define mammalPsgLoadAllByTab(a) mammalPsgLoadAllByChar(a, '\t');
/* Load all mammalPsg from tab separated file.
 * Dispose of this with mammalPsgFreeList(). */

struct mammalPsg *mammalPsgCommaIn(char **pS, struct mammalPsg *ret);
/* Create a mammalPsg out of a comma separated string.
 * This will fill in ret if non-null, otherwise will
 * return a new mammalPsg */

void mammalPsgFree(struct mammalPsg **pEl);
/* Free a single dynamically allocated mammalPsg such as created
 * with mammalPsgLoad(). */

void mammalPsgFreeList(struct mammalPsg **pList);
/* Free a list of dynamically allocated mammalPsg's */

void mammalPsgOutput(struct mammalPsg *el, FILE *f, char sep, char lastSep);
/* Print out mammalPsg.  Separate fields with sep. Follow last field with lastSep. */

#define mammalPsgTabOut(el,f) mammalPsgOutput(el,f,'\t','\n');
/* Print out mammalPsg as a line in a tab-separated file. */

#define mammalPsgCommaOut(el,f) mammalPsgOutput(el,f,',',',');
/* Print out mammalPsg as a comma separated list including final comma. */

/* -------------------------------- End autoSql Generated Code -------------------------------- */

#endif /* MAMMALPSG_H */


text:
FOUNDATION_EXPORT double SFrameworkVersionNumber;
FOUNDATION_EXPORT const unsigned char SFrameworkVersionString[];


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
North American Species of Lactarius (Ann Arbor) 182 (1979)

#### Original name
Lactarius piperatus f. fragrans Burl.

### Remarks
null


text:
"""Base class for text tests.
"""

import unittest
import sys

from pyglet import gl
from pyglet import font
from pyglet.window import Window
from pyglet.window.event import key

from unittests.regression import ImageRegressionTestCase

class TextTestBase(ImageRegressionTestCase):
    font_name = ''
    font_size = 24
    text = 'Quickly brown fox'
    window_size = 200, 200

    def on_key_press(self, symbol, modifiers):
        if symbol in (key.ENTER, key.ESCAPE):
            self.window.dispatch_event('on_close')

    def on_expose(self):
        gl.glClearColor(0.5, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        gl.glLoadIdentity()
        self.draw()
        self.window.flip()

        if self.capture_regression_image():
            self.window.exit_handler.has_exit = True

    def render(self):
        fnt = font.load(self.font_name, self.font_size)
        self.label = font.Text(fnt, self.text, 10, 10)

    def draw(self):
        self.label.draw()

    def test_main(self):
        width, height = self.window_size
        self.window = w = Window(width, height, visible=False, resizable=True)
        w.push_handlers(self)

        self.render()

        w.set_visible()
        while not w.has_exit:
            w.dispatch_events()
        w.close()


text:
@interface UIGestureRecognizer (Spec_Private)
- (void) addUnswizzledTarget:(id)target action:(SEL)action;
- (void) removeUnswizzledTarget:(id)target action:(SEL)action;
- (instancetype) initWithoutSwizzledTarget:(id)target action:(SEL)action;
@end

@implementation UIGestureRecognizer (Spec)

#pragma mark - TODO Refactor to use code in Foundation project
+ (void)redirectSelector:(SEL)originalSelector to:(SEL)newSelector andRenameItTo:(SEL)renamedSelector {
    [self redirectSelector:originalSelector
                      forClass:[self class]
                            to:newSelector
                 andRenameItTo:renamedSelector];

}

+ (void)redirectSelector:(SEL)originalSelector forClass:(Class)klass to:(SEL)newSelector andRenameItTo:(SEL)renamedSelector {
    if ([klass instancesRespondToSelector:renamedSelector]) {
        return;
    }

    Method originalMethod = class_getInstanceMethod(klass, originalSelector);
    class_addMethod(klass, renamedSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));

    Method newMethod = class_getInstanceMethod(klass, newSelector);
    class_replaceMethod(klass, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
}

#pragma mark - Setup
+(void)load {
    [self redirectSelector:@selector(addTarget:action:)
                        to:@selector(addSnoopedTarget:action:)
             andRenameItTo:@selector(addUnswizzledTarget:action:)];

    [self redirectSelector:@selector(removeTarget:action:)
                        to:@selector(removeSnoopedTarget:action:)
             andRenameItTo:@selector(removeUnswizzledTarget:action:)];

    [self redirectSelector:@selector(initWithTarget:action:)
                        to:@selector(initWithSwizzledTarget:action:)
             andRenameItTo:@selector(initWithoutSwizzledTarget:action:)];

    whitelistedClasses = [[NSMutableArray alloc] init];
}

-(instancetype)initWithSwizzledTarget:(id)target action:(SEL)action {
    if (self = [self initWithoutSwizzledTarget:target action:action]) {
        if(target && action) {
            [self addSnoopedTarget:target action:action];
        }
    }

    return self;
}

+(void)afterEach {
    [whitelistedClasses removeAllObjects];
}

#pragma mark - Public interface
-(void)recognize {
    if (self.view.hidden) {
        [[NSException exceptionWithName:@"Unrecognizable" reason:@"Can't recognize when in a hidden view" userInfo:nil] raise];
    }
    if (!self.enabled) {
        [[NSException exceptionWithName:@"Unrecognizable" reason:@"Can't recognize when recognizer is disabled" userInfo:nil] raise];
    }

    [self.targetsAndActions enumerateObjectsUsingBlock:^(NSArray *targetSelectorPair, NSUInteger index, BOOL *stop) {
        id target = [targetSelectorPair firstObject];
        SEL action = [[targetSelectorPair lastObject] pointerValue];

        [target performSelector:action withObject:self];
    }];
}

static NSMutableArray *whitelistedClasses;
+(void)whitelistClassForGestureSnooping:(Class)klass {
    [whitelistedClasses addObject:klass];
}

#pragma mark - swizzled methods
-(void)addSnoopedTarget:(id)target action:(SEL)action {
    [self addUnswizzledTarget:target action:action];

    NSMutableArray *targetsAndActions = [self targetsAndActions];

    if (![whitelistedClasses containsObject:[target class]]) {
        return;
    }

    [targetsAndActions addObject:@[target, [NSValue valueWithPointer:action]]];
    [self setTargetsAndActions:targetsAndActions];
}

-(void)removeSnoopedTarget:(id)target action:(SEL)action {
    [self removeUnswizzledTarget:target action:action];

    if (![whitelistedClasses containsObject:[target class]]) {
        return;
    }

    NSMutableArray *targetsAndActions = [self targetsAndActions];
    NSPredicate *targetAndActionPredicate = [NSPredicate predicateWithBlock:^BOOL(NSMutableArray *targetAndActionPair, NSDictionary *bindings) {
        id storedTarget = [targetAndActionPair firstObject];
        SEL storedAction = [[targetAndActionPair lastObject] pointerValue];
        return storedTarget == target && storedAction == action;
    }];

    NSArray *matchingTargetsAndActions = [targetsAndActions filteredArrayUsingPredicate:targetAndActionPredicate];
    [targetsAndActions removeObjectsInArray:matchingTargetsAndActions];
    [self setTargetsAndActions:targetsAndActions];
}

#pragma mark - targetsAndActions
static char const * const targetAndActionsKey = "targetAndActionKey";

-(NSMutableArray *) targetsAndActions {
    NSMutableArray *targetsAndActions = objc_getAssociatedObject(self, &targetAndActionsKey);
    if (!targetsAndActions) {
        targetsAndActions = [[[NSMutableArray alloc] init] autorelease];
        [self setTargetsAndActions:targetsAndActions];
    }
    return targetsAndActions;
}

-(void) setTargetsAndActions:(NSMutableArray *)targetsAndActions {
    objc_setAssociatedObject(self, &targetAndActionsKey, targetsAndActions, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


text:
name "ruby-windows"
default_version "1.9.3-p484"

relative_path "ruby-#{version}-i386-mingw32"

version "1.9.3-p484" do
  source md5: "a0665113aaeea83f1c4bea02fcf16694"
end

version "2.0.0-p451" do
  source md5: "37feadb0230e7f475a8591d1807ecfec"
end

source url: "http://dl.bintray.com/oneclick/rubyinstaller/ruby-#{version}-i386-mingw32.7z?direct"

build do
  # Robocopy's return code is 1 if it succesfully copies over the
  # files and 0 if the files are already existing at the destination
  command "XCOPY /YEH . #{windows_safe_path(install_dir)}\\embedded\\ /MIR"

  # Ruby 2.X dl.rb gives an annoying warning message on Windows:
  # DL is deprecated, please use Fiddle
  # Since we don't have patch on windows we are manually patching the file
  # to turn off the warning message
  # We are only removing dl.rb:8
  # => warn "DL is deprecated, please use Fiddle"
  if version.start_with? "2"
    block do
      require "digest/md5"

      dl_path = File.join(install_dir, "embedded/lib/ruby/2.0.0/dl.rb")
      if Digest::MD5.hexdigest(File.read(dl_path)) == "78c185a3fcc7b5e2c3db697c85110d8f"
        File.open(dl_path, "w") do |f|
          f.print <<-E
  require 'dl.so'

  begin
    require 'fiddle' unless Object.const_defined?(:Fiddle)
  rescue LoadError
  end

  module DL
    # Returns true if DL is using Fiddle, the libffi wrapper.
    def self.fiddle?
      Object.const_defined?(:Fiddle)
    end
  end
  E
        end
      end
    end
  end
end


text:
import unittest
from lz77 import Compressor

class LZ77Test(unittest.TestCase):
    def setUp(self):
        self.textData = "ababassbabasbabbbaababassbababsbasbasbbabbbababababaaaaabbbab"
        self.encodedTextData = "ababassbabasbabbba` '&bs` 1 sb` 4!` . abaaaa` *!"
        self.compressor = Compressor();
    def testCorrectCompressedOutput(self):
        print "testCorrectCompressedOutput:"
        result = self.compressor.compress(self.textData)
        print self.encodedTextData
        print result
        assert result == self.encodedTextData, "must match"
    def testCorrectDecompressedOutput(self):
        print "testCorrectDecompressedOutput:"
        result = self.compressor.decompress(self.encodedTextData)
        print self.textData
        print result
        assert result == self.textData, "must match"

if __name__ == "__main__":
    unittest.main()


text:
require 'spec_helper'

describe Chef::Util::FileEdit do

  let(:starting_content) do
    <<-EOF
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
    EOF
  end

  let(:localhost_replaced) do
    <<-EOF
127.0.0.1       replacement
255.255.255.255 broadcasthost
::1             replacement
fe80::1%lo0     replacement
    EOF
  end

  let(:localhost_line_replaced) do
    <<-EOF
replacement line
255.255.255.255 broadcasthost
replacement line
replacement line
    EOF
  end

  let(:localhost_deleted) do
    # sensitive to deliberate trailing whitespace
    "127.0.0.1       \n255.255.255.255 broadcasthost\n::1             \nfe80::1%lo0     \n"
  end

  let(:localhost_line_deleted) do
    <<-EOF
255.255.255.255 broadcasthost
    EOF
  end

  let(:append_after_all_localhost) do
    <<-EOF
127.0.0.1       localhost
new line inserted
255.255.255.255 broadcasthost
::1             localhost
new line inserted
fe80::1%lo0     localhost
new line inserted
    EOF
  end

  let(:append_after_content) do
    <<-EOF
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost
new line inserted
    EOF
  end

  let(:target_file) do
    f = Tempfile.open('file_edit_spec')
    f.write(starting_content)
    f.close
    f
  end

  let(:fedit) { Chef::Util::FileEdit.new(target_file.path) }

  after(:each) do
    target_file.close!
  end

  describe "initialiize" do
    it "should create a new Chef::Util::FileEdit object" do
      expect(fedit).to be_instance_of(Chef::Util::FileEdit)
    end

    it "should throw an exception if the input file does not exist" do
      expect{Chef::Util::FileEdit.new("nonexistfile")}.to raise_error(ArgumentError)
    end

    # CHEF-5018: people have monkey patched this and it has accidentally been broken
    it "should read the contents into memory as an array" do
      expect(fedit.send(:contents)).to be_instance_of(Array)
    end
  end

  describe "when the file is blank" do
    let(:hosts_content) { "" }

    it "should not throw an exception" do
      expect{ fedit }.not_to raise_error
    end
  end

  def edited_file_contents
    IO.read(target_file.path)
  end

  describe "search_file_replace" do
    it "should accept regex passed in as a string (not Regexp object) and replace the match if there is one" do
      fedit.search_file_replace("localhost", "replacement")
      fedit.write_file
      expect(edited_file_contents).to eq(localhost_replaced)
    end

    it "should accept regex passed in as a Regexp object and replace the match if there is one" do
      fedit.search_file_replace(/localhost/, "replacement")
      fedit.write_file
      expect(edited_file_contents).to eq(localhost_replaced)
    end

    it "should do nothing if there isn't a match" do
      fedit.search_file_replace(/pattern/, "replacement")
      fedit.write_file
      expect(edited_file_contents).to eq(starting_content)
    end
  end

  describe "search_file_replace_line" do
    it "should search for match and replace the whole line" do
      fedit.search_file_replace_line(/localhost/, "replacement line")
      fedit.write_file
      expect(edited_file_contents).to eq(localhost_line_replaced)
    end
  end

  describe "search_file_delete" do
    it "should search for match and delete the match" do
      fedit.search_file_delete(/localhost/)
      fedit.write_file
      expect(edited_file_contents).to eq(localhost_deleted)
    end
  end

  describe "search_file_delete_line" do
    it "should search for match and delete the matching line" do
      fedit.search_file_delete_line(/localhost/)
      fedit.write_file
      expect(edited_file_contents).to eq(localhost_line_deleted)
    end
  end

  describe "insert_line_after_match" do
    it "should search for match and insert the given line after the matching line" do
      fedit.insert_line_after_match(/localhost/, "new line inserted")
      fedit.write_file
      expect(edited_file_contents).to eq(append_after_all_localhost)
    end
  end

  describe "insert_line_if_no_match" do
    it "should search for match and insert the given line if no line match" do
      fedit.insert_line_if_no_match(/pattern/, "new line inserted")
      fedit.write_file
      expect(edited_file_contents).to eq(append_after_content)
    end

    it "should do nothing if there is a match" do
      fedit.insert_line_if_no_match(/localhost/, "replacement")
      fedit.write_file
      expect(edited_file_contents).to eq(starting_content)
    end
  end
end


text:
using System;
using System.Windows.Input;

namespace Dae.ToolDev.Framework
{
	public class DelegateCommand : IDelegateCommand
	{
		public DelegateCommand(Action execute, Func<bool> canExecute = null)
		{
			if (execute == null)
				throw new ArgumentNullException("execute");

			Execute = execute;
			CanExecute = canExecute;
		}

		public Action Execute { get; private set; }

		public Func<bool> CanExecute { get; private set; }

		public event EventHandler CanExecuteChanged;

		/// <summary>
		/// Updates the command by raising the CanExecuteChanged event,
		/// causing re-evaluation of the CanExecute method.
		/// </summary>
		public void Update()
		{
			if (CanExecute != null)
		{
			EventHandler handler = CanExecuteChanged;
			if (handler != null)
				handler(this, EventArgs.Empty);
		}
		}

		bool ICommand.CanExecute(object parameter)
		{
			return CanExecute == null || CanExecute();
		}

		void ICommand.Execute(object parameter)
		{
			Execute();
		}
	}
}


text:
::: equinox.Module
    selection:
        members: false