text:
var Family = require('../models/home');
var sync = require('synchronize')
var request = require('sync-request');
var barcodeCount = 1000000000000;
/*
input JSON
{
	familyName: 'asasda',
	name: 'Apurv',
	socialLoginId: 'dada231121',
	socialLoginType: 'Facebook'
}
*/
exports.login = function(req, res) {
	if(req.body==null){
		res.status(403).json({err:'Invalid Login Information'});
	}
	else{
		Family.find({familyName: req.body.familyName},function(err, data){
			if (err) {console.log(err);res.status(500).json({error:err});}
			else if(data==null || data.length==0){
				/*var newUser = {
					name: req.body.name,
					socialLoginId: req.body.loginId,
					socialLoginType: req.body.loginType
				};
				var users = [];
				users.push(newUser);*/
				console.log(req.body);
				var newFamily = new Family({
					familyName: req.body.familyName
					//users: users
				});
				newFamily.save(function(err){
					if (err) {console.log(err);res.status(500).json({'err':err});}
					else{
						console.log(newFamily);
						res.status(200).json(newFamily);
					}
				});

			}else{
				/*var users = data.users.filter(function(u){
					return (u.socialLoginId==req.body.socialLoginId && u.socialLoginType==req.body.socialLoginType);
				});
				if(users.length==0){
					var newUser = {
						name: req.body.name,
						socialLoginId: req.body.loginId,
						socialLoginType: req.body.loginType
					};
					data.users.push(newUser);
				}*/
				res.status(200).json(data);
			}
		});
	}
}

/* input structure -
{
	itemList: [
		{
			barcode: String
		}
	]
}
*/
exports.addToFridge = function(req, res){
	if(req.body.itemList==null || req.body.itemList.length==0){
		res.status(403).json({error:'Barcodes incorrect'});
		return;
	}else{
		console.log("add to fridge:"+JSON.stringify(req.body.itemList));
		Family.findById(req.params.id, function(err, Family){
			if (err) {console.log(err);res.status(500).json({error:'Family not found'});}
			if(Family!=null){
				//sync()
				sync.fiber(function(){
					var currentDate = new Date();
					var items = req.body.itemList;
					var garbageItemsTobeRemoved=[];
					for(var i=0;i<items.length;i++){
						var product=null;
						if(items[i].quantity!=null){
							items[i].quantity = parseInt(items[i].quantity);
						}
						for(var j=0;j<Family.productList.length;j++){
							if(Family.productList[j].barcode == items[i].barcode){
								product = Family.productList[j];
								if(product.name==''){
									//this is if the user himself enters the name and description for the product
									//when the user enters it manually for the product which only has barcode
									//now scanned by OCR
									product.name = items[i].name;
									product.description = items[i].description;
								}
								Family.productList[j].totalConsumed=Family.productList[j].totalConsumed+1;
							}
						}

						if(product==null){
							if(items[i].barcode!=null){//if the barcode is present
								//first find the product on UPC database
								var upcInfo = request('GET','http://api.upcdatabase.org/json/686805871a799c2b1a0e06e77a544fce/'+items[i].barcode);

								var bodyUPC = JSON.parse(upcInfo.getBody('utf8'));
								if(bodyUPC.valid=='true'){
									var productText = bodyUPC.description;
									if(productText==""){
										productText = bodyUPC.itemname+bodyUPC.alias;
									}
									product = {
										created_date:currentDate,
										updated_date:currentDate,
										name:productText,
										description:productText,
										barcode:items[i].barcode,
										totalConsumed:1
									}
									Family.productList.push(product);
								}else{
									//try once more by adding a 0 to the barcode and hit upc
									upcInfo = request('GET','http://api.upcdatabase.org/json/686805871a799c2b1a0e06e77a544fce/0'+items[i].barcode);
									var bodyUPC = JSON.parse(upcInfo.getBody('utf8'));
									if(bodyUPC.valid=='true'){
										var productText = bodyUPC.description;
										if(productText==""){
											productText = bodyUPC.itemname+bodyUPC.alias;
										}
										product = {
											created_date:currentDate,
											updated_date:currentDate,
											name:productText,
											description:productText,
											barcode:items[i].barcode,
											totalConsumed:1
										}
										Family.productList.push(product);
									}else{
										//if the UPC database does not have information on the barcode
										product = {
											created_date:currentDate,
											updated_date:currentDate,
											name:'',
											description:'',
											barcode:items[i].barcode,
											totalConsumed:1
										}
										Family.productList.push(product);
									}
								}
							}else{
								//if barcode is not present , the data comes from calrifai api after image object detection
								product = {
									created_date:currentDate,
									updated_date:currentDate,
									name:items[i].name,
									description:items[i].name,
									barcode:barcodeCount+1,
									totalConsumed:1
								}
								barcodeCount=barcodeCount+1;
								Family.productList.push(product);
							}

						}

						for(var gi=0;gi<Family.garbageList.length;gi++){
							//console.log("product:"+JSON.stringify(Family.fridgeList[fi]));
							//console.log("fi fridgelIst:"+Family.fridgeList);
							if(Family.garbageList[gi].product.barcode==items[i].barcode){
								Family.garbageList[gi].quantity=Family.garbageList[gi].quantity-1;
								if(Family.garbageList[gi].quantity<0){
									garbageItemsTobeRemoved.push(gi);
								}
								break;
							}/*else if(Family.garbageList[gi].product.name==items[i].name){
								Family.garbageList[gi].quantity=Family.garbageList[gi].quantity-1;
								if(Family.garbageList[gi].quantity){
									garbageItemsTobeRemoved.push(gi);
								}
								break;
							}*/
						}

						var isAFridgeItem = false;
						for(var fi=0;fi<Family.fridgeList.length;fi++){
							if(Family.fridgeList[fi].product.barcode==items[i].barcode){
								var productQuantity = 1;
								if(items[i].quantity!=null){
									product.name = items[i].name;
									product.description = items[i].name;
									productQuantity = 0;
									Family.fridgeList[fi].product.name = items[i].name;
									Family.fridgeList[fi].product.description = items[i].description;
								}

								Family.fridgeList[fi].quantity=Family.fridgeList[fi].quantity+productQuantity;
								isAFridgeItem = true;
								break;
							}/*else if(Family.fridgeList[fi].product.name==items[i].name){
								Family.fridgeList[fi].quantity=Family.fridgeList[fi].quantity+1;
								isAFridgeItem = true;
								break;
							}*/
						}

						if(!isAFridgeItem){
							fridgeItem={
								created_date:currentDate,
								updated_date:currentDate,
								product:product,
								quantity:1
							};
							Family.fridgeList.push(fridgeItem);
						}

					}

					for(var k=0;k<garbageItemsTobeRemoved.length;k++){
						Family.garbageList.splice(garbageItemsTobeRemoved[k],1);
					}
					Family.save(function(err){
						if(err) { console.log(err); res.status(204).json({error:'Some error at the server'})}
						res.status(200).json(Family);
					});

				});
			}
		});
	}
}

/* input structure -
{
	itemList: [
		{
			name: String,
			description: String,
			barcode: String
		}
	]
}
*/
exports.addToGarbage = function(req, res){
	console.log(req.body.itemList);
	if(req.body.itemList==null || req.body.itemList.length==0){
		res.status(403).json({error:'Barcodes incorrect'});
	}else{
		console.log("add to garbage:"+JSON.stringify(req.body.itemList));
		Family.findById(req.params.id, function(err, Family){
			if (err) {console.log(err);res.status(500).json({error:'Family not found'});}
			if(Family!=null){
				var currentDate = new Date();
				var fridgeItemsToBeRemoved=[];
				var items = req.body.itemList;

				for(var i=0;i<items.length;i++){
					if(items[i].quantity!=null){
							items[i].quantity = parseInt(items[i].quantity);
					}
					var product=null;
					for(var j=0;j<Family.productList.length;j++){
						if(Family.productList[j].barcode == items[i].barcode){
							product = Family.productList[j];
						}
					}
					if(product==null){
						console.log("Invalid product while adding to garbage");
						res.status(500).json({error:'Invalid product'});
						return;
					}
					//to find the items to be updated in the fridgeList
					//if the quantity becomes 0 then remove from the fridgelist
					var isPresentInFridge = false;
					for(var gi=0;gi<Family.fridgeList.length;gi++){
						if(Family.fridgeList[gi].product.barcode==items[i].barcode){
							isPresentInFridge=true;
							Family.fridgeList[gi].quantity=Family.fridgeList[gi].quantity-1;
							if(Family.fridgeList[gi].quantity==0){
								fridgeItemsToBeRemoved.push(gi);
							}
							break;
						}/*else if(Family.fridgeList[gi].product.name==items[i].name){
							Family.fridgeList[gi].quantity=Family.fridgeList[gi].quantity-1;
							if(Family.fridgeList[gi].quantity){
								fridgeItemsToBeRemoved.push(gi);
							}
							break;
						}*/
					}
					if(!isPresentInFridge){
						console.log('Item removed was not added to fridge');
						res.status(500).json({error:'Item removed was not added to fridge'});
						return;
					}
					var isAGarbageItem = false;
					for(var fi=0;fi<Family.garbageList.length;fi++){

						if(Family.garbageList[fi].product.barcode==items[i].barcode){
							Family.garbageList[fi].quantity=Family.garbageList[fi].quantity+1;
							isAGarbageItem = true;
							break;
						}/*else if(Family.garbageList[fi].product.name==items[i].name){
							Family.garbageList[fi].quantity=Family.garbageList[fi].quantity+1;
							isAGarbageItem = true;
							break;
						}*/
					}

					if(!isAGarbageItem){
						garbageItem={
							created_date:currentDate,
							updated_date:currentDate,
							product:product,
							quantity:1
						};
						Family.garbageList.push(garbageItem);
					}

				}

				for(var k=0;k<fridgeItemsToBeRemoved.length;k++){
					Family.fridgeList.splice(fridgeItemsToBeRemoved[k],1);
				}
				Family.save(function(err){
					if(err) { console.log(err); res.status(204).json({error:'Some error at the server'})}
					res.status(200).json(Family);
				});
			}
		});
	}
}

exports.getAllData = function(req,res){
	if(req.params.id==null){
		res.status(403).json({error:'Barcodes incorrect'});
	}else{
		Family.findById(req.params.id, function(err, family){
			if (err) {console.log(err);res.status(500).json({error:'Family not found'});}
			if(family!=null){
				res.status(200).json(family);
				return;
			}else{
				res.status(404).json({error:"Could not find Family"});
			}
		});
	}
}

/*
{
	upcCodes:[
		{
			"code":"11231221123",
			"quantity":3
		}
	]
}
*/
exports.amazonCall = function(req,res){
	console.log("upcCodes:"+JSON.stringify(req.body));
	if(req.params.id==null || req.body==null){
		res.status(403).json({error:'Incorrect data sent'});
	}else{
		Family.findById(req.params.id, function(err, Family){
			if (err) {console.log(err);res.status(500).json({error:'Family not found'});}
			var upcCodes = req.body.upcCodes;
			if(Family!=null && upcCodes!=null && upcCodes.length>0){
				var asin = "";

				for(var i=0;i<upcCodes.length;i++){
					console.log("upc:"+upcCodes[i].code);
					var z = request('GET','http://upctoasin.com/'+upcCodes[i].code);
					console.log("output:"+z.getBody('utf8'));
					if(z!=null && z!=''){
						asin = asin+"ASIN."+(i+1)+"="+z.getBody('utf8')+"&"+"Quantity."+(i+1)+"="+upcCodes[i].quantity+"&";
					}
					for(var fi=0;fi<Family.garbageList.length;fi++){

						if(Family.garbageList[fi].product.barcode==z.getBody('utf8').code){
							Family.garbageList.splice(fi,1);
							break;
						}/*else if(Family.garbageList[fi].product.name==items[i].name){
							Family.garbageList[fi].quantity=Family.garbageList[fi].quantity+1;
							isAGarbageItem = true;
							break;
						}*/
					}
				}
				var data = {
					url:'https://www.amazon.com/gp/aws/cart/add.html?'+asin+'AWSAccessKeyId=AKIAJ34LUZETTZFXGMDQ&AssociateTag=aries0a-20'
				}
				res.status(200).json(data);
			}
		});
	}
}


text:
import ofxtools
from pyparsing import CaselessLiteral, Group, LineEnd, Literal, \
    MatchFirst, oneOf, OneOrMore, Optional, Or, restOfLine, SkipTo, \
    White, Word, ZeroOrMore

class QifParser:
    def __init__(self, debug=False):
        account_items       = { 'N' : "Name",
                                'T' : "AccountType",
                                'D' : "Description",
                                'L' : "CreditLimit",
                                'X' : "UnknownField",
                                'B' : "Balance",
                                '/' : "BalanceDate",
                                '$' : "Balance" }

        noninvestment_items = { 'D' : "Date",
                                'T' : "Amount",
                                'U' : "Amount2",
                                'C' : "Cleared",
                                'N' : "Number",
                                'P' : "Payee",
                                'M' : "Memo",
                                'L' : "Category",
                                'A' : "Address",
                                'S' : "SplitCategory",
                                'E' : "SplitMemo",
                                '$' : "SplitAmount",
                                '-' : "NegativeSplitAmount" }

        investment_items    = { 'D' : "Date",
                                'N' : "Action",
                                'Y' : "Security",
                                'I' : "Price",
                                'Q' : "Quantity",
                                'T' : "Amount",
                                'C' : "Cleared",
                                'P' : "Text",
                                'M' : "Memo",
                                'O' : "Commission",
                                'L' : "TransferAccount",
                                '$' : "TransferAmount" }

        category_items      = { 'N' : "Name",
                                'D' : "Description",
                                'T' : "TaxRelated",
                                'I' : "IncomeCategory",
                                'E' : "ExpenseCategory",
                                'B' : "BudgetAmount",
                                'R' : "TaxSchedule" }

        class_items         = { 'N' : "Name",
                                'D' : "Description" }

        options   = Group(CaselessLiteral('!Option:') + restOfLine).suppress()

        banktxns  = Group(CaselessLiteral('!Type:Bank').suppress() +
                          ZeroOrMore(Or([self._items(noninvestment_items),
                                         options]))
                          ).setResultsName("BankTransactions")

        cashtxns  = Group(CaselessLiteral('!Type:Cash').suppress() +
                          ZeroOrMore(Or([self._items(noninvestment_items),
                                         options]))
                          ).setResultsName("CashTransactions")

        ccardtxns = Group(Or([CaselessLiteral('!Type:CCard').suppress(),
                              CaselessLiteral('!Type!CCard').suppress()]) +
                          ZeroOrMore(Or([self._items(noninvestment_items),
                                         options]))
                          ).setResultsName("CreditCardTransactions")

        liabilitytxns = Group(CaselessLiteral('!Type:Oth L').suppress() +
                          ZeroOrMore(Or([self._items(noninvestment_items),
                                         options]))
                          ).setResultsName("CreditCardTransactions")

        invsttxns = Group(CaselessLiteral('!Type:Invst').suppress() +
                          ZeroOrMore(self._items(investment_items))
                          ).setResultsName("InvestmentTransactions")

        acctlist  = Group(CaselessLiteral('!Account').suppress() +
                          ZeroOrMore(Or([self._items(account_items, name="AccountInfo")]))
                          ).setResultsName("AccountList")

        category  = Group(CaselessLiteral('!Type:Cat').suppress() +
                          ZeroOrMore(self._items(category_items))
                          ).setResultsName("CategoryList")

        classlist = Group(CaselessLiteral('!Type:Class').suppress() +
                          ZeroOrMore(self._items(category_items))
                          ).setResultsName("ClassList")

        self.parser = Group(ZeroOrMore(White()).suppress() +
                            ZeroOrMore(acctlist).suppress() +
                            OneOrMore(ccardtxns | cashtxns | banktxns | liabilitytxns | invsttxns) +
                            ZeroOrMore(category | classlist).suppress() +
                            ZeroOrMore(White()).suppress()
                            ).setResultsName("QifStatement")

        if (debug):
            self.parser.setDebugActions(ofxtools._ofxtoolsStartDebugAction,
                                        ofxtools._ofxtoolsSuccessDebugAction,
                                        ofxtools._ofxtoolsExceptionDebugAction)

    def _items(self, items, name="Transaction"):
        item_list = []
        for (code, name) in items.iteritems():
            item = self._item(code, name)
            item_list.append(item)
        return Group(OneOrMore(Or(item_list)) +
                     oneOf('^EUR ^').setResultsName('Currency') +
                     LineEnd().suppress()
                     ).setResultsName(name)

    def _item(self, code, name):
        return CaselessLiteral(code).suppress() + \
               restOfLine.setResultsName(name) + \
               LineEnd().suppress()

    def parse(self, qif):
        return self.parser.parseString(qif)

redpajama_set_name: RedPajamaGithub


text:
/*
 * ForceSniffer.js v1.1.0
 * Device Detect Library for Phone and Tablets and other
 * device include (Amazon Silk, mini-opera and Windows Phone),
 * and any kind of seven inch device, via user agent sniffing.
 * @author: Harshit Pandey (mailtoharshit@gmail.com)
 */

//Forked and Inspired from isMobile.js

//Script to detect all mobile devices
(function (global) {

    var apple_phone         = /iPhone/i,
        apple_ipod          = /iPod/i,
        apple_tablet        = /iPad/i,
        android_phone       = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile'
        android_tablet      = /Android/i,
        amazon_phone        = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i,
        amazon_tablet       = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i,
        windows_phone       = /IEMobile/i,
        windows_tablet      = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM'
        other_blackberry    = /BlackBerry/i,
        other_blackberry_10 = /BB10/i,
        other_opera         = /Opera Mini/i,
        other_chrome        = /(CriOS|Chrome)(?=.*\bMobile\b)/i,
        other_firefox       = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile'
        seven_inch = new RegExp(
            '(?:' +         // Non-capturing group

            'Nexus 7' +     // Nexus 7

            '|' +           // OR

            'BNTV250' +     // B&N Nook Tablet 7 inch

            '|' +           // OR

            'Kindle Fire' + // Kindle Fire

            '|' +           // OR

            'Silk' +        // Kindle Fire, Silk Accelerated

            '|' +           // OR

            'GT-P1000' +    // Galaxy Tab 7 inch

            ')',            // End non-capturing group

            'i');           // Case-insensitive matching

    var match = function(regex, userAgent) {
        return regex.test(userAgent);
    };

    var IsMobileClass = function(userAgent) {
        var ua = userAgent || navigator.userAgent;
        // Facebook mobile app's integrated browser adds a bunch of strings that
        // match everything. Strip it out if it exists.
        var tmp = ua.split('[FBAN');
        if (typeof tmp[1] !== 'undefined') {
            ua = tmp[0];
        }

        this.apple = {
            phone:  match(apple_phone, ua),
            ipod:   match(apple_ipod, ua),
            tablet: !match(apple_phone, ua) && match(apple_tablet, ua),
            device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua)
        };
        this.amazon = {
            phone:  match(amazon_phone, ua),
            tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua),
            device: match(amazon_phone, ua) || match(amazon_tablet, ua)
        };
        this.android = {
            phone:  match(amazon_phone, ua) || match(android_phone, ua),
            tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)),
            device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua)
        };
        this.windows = {
            phone:  match(windows_phone, ua),
            tablet: match(windows_tablet, ua),
            device: match(windows_phone, ua) || match(windows_tablet, ua)
        };
        this.other = {
            blackberry:   match(other_blackberry, ua),
            blackberry10: match(other_blackberry_10, ua),
            opera:        match(other_opera, ua),
            firefox:      match(other_firefox, ua),
            chrome:       match(other_chrome, ua),
            device:       match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua)
        };
        this.seven_inch = match(seven_inch, ua);
        this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch;
        // excludes 'other' devices and ipods, targeting touchscreen phones
        this.phone = this.apple.phone || this.android.phone || this.windows.phone;
        // excludes 7 inch devices, classifying as phone or tablet is left to the user
        this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet;

        if (typeof window === 'undefined') {
            return this;
        }
    };

    var instantiate = function() {
        var IM = new IsMobileClass();
        IM.Class = IsMobileClass;
        return IM;
    };

    if (typeof module != 'undefined' && module.exports && typeof window === 'undefined') {
        //node
        module.exports = IsMobileClass;
    } else if (typeof module != 'undefined' && module.exports && typeof window !== 'undefined') {
        //browserify
        module.exports = instantiate();
    } else if (typeof define === 'function' && define.amd) {
        //AMD
        define('isMobile', [], global.isMobile = instantiate());
    } else {
        global.isMobile = instantiate();
    }

})(this);

//Detect if Salesforce1
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.isSalesforce1 = function() {
        return((typeof sforce != 'undefined') && sforce && (!!sforce.one));
    }
    })(this);
//Detect if LightingX
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.isLightingX = function() {
        return(isLightning() && (!isMobile.any()));
    }
    })(this);

//Detect if Visualforce Inside Saleforce1
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.isVF_In_Salesforce1 = function() {
        return((!isLightning()) && ForceUI.isSalesforce1());
    }
    })(this);

//Detect if Visualforce inside Salesforce Classic
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.isVF_In_SalesforceClassic = function() {
        return((!isLightning()) && !ForceUI.isSalesforce1());
    }
    })(this);

//Detect browser type
(function(myContext) {
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.browserType = function() {
        if (navigator.userAgent.indexOf("OPR") != -1) { // if browser type is Opera
            return 'Opera';
        } else if (navigator.userAgent.indexOf("Chrome") != -1) { // if browser type is Chrome
            return 'Chrome';
        } else if (navigator.userAgent.indexOf("Safari") != -1) { // if browser type is Safari
            return 'Safari';
        } else if (navigator.userAgent.indexOf("Firefox") != -1) { // if browser type is Firefox
            return 'Firefox';
        } else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { // if browser is IE
            return 'IE';
        } else {
            if(ForceUI.isSalesforce1()){return 'Salesforce1';}
            else {return 'unknown';} // if browser is something else
        }
    }
})(this);

//Detects browser version
(function(myContext) {
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.browserVersion = function() {
        var ua = window.navigator.userAgent;
        var browserStartPoint = ua.indexOf(ForceUI.browserType());

        // If browser type is found, return it's version number
        if (ForceUI.browserType() == 'Chrome') // get Chrome browser version
            return ua.substring(browserStartPoint + 7, ua.indexOf(" ", browserStartPoint));
        else if (ForceUI.browserType() == 'IE') { // get IE browser version
            browserStartPoint = navigator.userAgent.indexOf("MSIE");
            return ua.substring(browserStartPoint + 5, ua.indexOf(";", browserStartPoint));
        } else if (ForceUI.browserType() == 'Firefox') // get Firefox browser version
            return ua.substring(browserStartPoint + 8, ua.length);
        else if (ForceUI.browserType() == 'Safari') // get Safari browser version
            return ua.substring(browserStartPoint + 7, ua.length);
        else if (ForceUI.browserType() == 'Opera') { // get Opera browser version
            browserStartPoint = navigator.userAgent.indexOf("OPR");
            return ua.substring(browserStartPoint + 4, ua.length);
        } else // If another browser, return 0
            return 0

    }
})(this);

//Detect browser type with Browser Version
(function(myContext) {

    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.browserTypeWithVersion = function() { // get browser Type along with version
        var result = ForceUI.browserType() + ' ' + ForceUI.browserVersion();
        return result;
    }
})(this);

//Detect OS type
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.osType = function() {
    var os=navigator.platform.toLowerCase();
    var osType="";

    switch(os)
    {
        case "win32" :
        {
            osType="Windows";
            break;
        }
        case "macintel" :
        {
             osType="OSX-Mac";
             break;
        }

        case "iphone" :
        {
             osType="iOS-iPhone";
             break;
        }

        case "ipad" :
        {
             osType="iOS-iPad";
             break;
        }

        default :
        {
             osType="Android";
             break;
        }

    }
    return osType;
   }
})(this);

//Detect OS type with OS Version
(function(myContext){
    myContext.ForceUI = myContext.ForceUI || {};
    myContext.ForceUI.osTypeWithVersion = function() {
    var os = 'unknown';
    var clientStrings = [
            {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 3.11', r:/Win16/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(navigator.userAgent)) {
                os = cs.s;
                break;
            }
        }
        var osVersion = 'unknown';
        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }
        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(navigator.userAgent)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(navigator.userAgent)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;
        }

       return os + ' '+osVersion;
   }
})(this);


text:
#include "yall/test.h"

static void tests_yall_setup(void)
{
	cr_redirect_stderr();
}

static void tests_yall_clean(void)
{

}

TestSuite(yall, .init=tests_yall_setup, .fini=tests_yall_clean);

void tests_call_log_function(struct yall_call_data *d, const void *args)
{
	UNUSED(d);
	UNUSED(args);

	/*
	 * Writing function used in yall_call_log.
	 */
}


text:
package com.github.cloudml.zen.ml.clustering

import java.util.concurrent.ConcurrentLinkedQueue

import breeze.linalg.{DenseVector => BDV, SparseVector => BSV}
import breeze.numerics._
import com.github.cloudml.zen.ml.clustering.LDADefines._
import com.github.cloudml.zen.ml.clustering.LDAPrecalc._
import com.github.cloudml.zen.ml.util.BVDecompressor
import com.github.cloudml.zen.ml.util.Concurrent._
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.graphx2.impl.{ShippableVertexPartition => VertPartition}

import scala.collection.JavaConversions._
import scala.collection.mutable
import scala.concurrent.Future

abstract class LDAMetrics(lda: LDA) extends Serializable {
  def getTotal: Double
  def calc(): LDAMetrics
  def calculated: Boolean
  def output(writer: String => Unit): Unit
}

abstract class LDACondMetrics(lda: LDA) extends LDAMetrics(lda) {
  def getWord: Double
  def getDoc: Double
}

class LDAPerplexity(lda: LDA) extends LDACondMetrics(lda) {
  var _calculated = false
  var pplx = 0.0
  var wpplx = 0.0
  var dpplx = 0.0

  override def getTotal: Double = pplx

  override def getWord: Double = wpplx

  override def getDoc: Double = dpplx

  override def calc(): LDAPerplexity = {
    val edges = lda.edges
    val verts = lda.verts
    val globalCountersBc = lda.globalCountersBc

    val algo = lda.algo
    val numTerms = lda.numTerms
    val numTokens = lda.numTokens
    val alpha = lda.alpha
    val beta = lda.beta
    val alphaAS = lda.alphaAS

    val newEdges = algo.refreshEdgeAssociations(edges, verts)
    val ppf = algo.perplexPartition(globalCountersBc, numTokens, numTerms, alpha, alphaAS, beta) _
    val sumPart = newEdges.partitionsRDD.mapPartitions(_.map { case (_, ep) =>
      ppf(ep)
    })
    val (llht, wllht, dllht) = sumPart.collect().unzip3

    pplx = math.exp(-llht.par.sum / numTokens)
    wpplx = math.exp(-wllht.par.sum / numTokens)
    dpplx = math.exp(-dllht.par.sum / numTokens)
    _calculated = true
    this
  }

  override def calculated: Boolean = _calculated

  override def output(writer: String => Unit): Unit = {
    if (calculated) {
      val o = s"total pplx=$getTotal, word pplx=$getWord, doc pplx=$getDoc"
      writer(o)
    } else {
      new Exception("Perplexity not calculated yet.")
    }
  }
}

class LDALogLikelihood(lda: LDA) extends LDACondMetrics(lda) {
  var _calculated = false
  var wllh = 0.0
  var dllh = 0.0

  override def getTotal: Double = wllh + dllh

  override def getWord: Double = wllh

  override def getDoc: Double = dllh

  override def calc(): LDALogLikelihood = {
    val edges = lda.edges
    val verts = lda.verts
    val globalCountersBc = lda.globalCountersBc

    val numThreads = edges.context.getConf.getInt(cs_numThreads, 1)
    val numTopics = lda.numTopics
    val numTerms = lda.numTerms
    val numDocs = lda.numDocs
    val numTokens = lda.numTokens
    val alpha = lda.alpha
    val beta = lda.beta
    val alphaAS = lda.alphaAS

    val alphaSum = alpha * numTopics
    val betaSum = beta * numTerms
    val lpf = calc_part(globalCountersBc, numTopics, numThreads, numTokens, alpha, beta, alphaAS) _
    val sumPart = verts.partitionsRDD.mapPartitions(_.map(lpf))
    val (wllht, dllht) = sumPart.collect().unzip

    val topicCounters = globalCountersBc.value
    val normWord = Range(0, numTopics).par.map(i => lgamma(topicCounters(i) + betaSum)).sum
    wllh = wllht.par.sum + numTopics * lgamma(betaSum) - normWord
    dllh = dllht.par.sum + numDocs * lgamma(alphaSum)
    _calculated = true
    this
  }

  private def calc_part(globalCountersBc: Broadcast[LDAGlobalCounters],
    numTopics: Int,
    numThreads: Int,
    numTokens: Long,
    alpha: Double,
    beta: Double,
    alphaAS: Double)
    (vp: VertPartition[TC]): (Double, Double) = {
    val topicCounters = globalCountersBc.value
    val alphaSum = alpha * numTopics
    val alphaRatio = calc_alphaRatio(numTopics, numTokens, alphaAS, alphaSum)
    val alphaks = calc_alphaks(topicCounters, alphaAS, alphaRatio)
    val lgamma_alphaks = alphaks.map(lgamma(_))
    val lgamma_beta = lgamma(beta)

    val totalSize = vp.capacity
    val index = vp.index
    val mask = vp.mask
    val values = vp.values
    @volatile var wllhs = 0.0
    @volatile var dllhs = 0.0
    val sizePerthrd = {
      val npt = totalSize / numThreads
      if (npt * numThreads == totalSize) npt else npt + 1
    }

    implicit val es = initExecutionContext(numThreads)
    val all = Future.traverse(Range(0, numThreads).iterator) { thid => withFuture {
      val decomp = new BVDecompressor(numTopics)
      val startPos = sizePerthrd * thid
      val endPos = math.min(sizePerthrd * (thid + 1), totalSize)
      var wllh_th = 0.0
      var dllh_th = 0.0
      var pos = mask.nextSetBit(startPos)
      while (pos < endPos && pos >= 0) {
        val bv = decomp.CV2BV(values(pos))
        if (isTermId(index.getValue(pos))) {
          bv.activeValuesIterator.foreach(cnt =>
            wllh_th += lgamma(cnt + beta)
          )
          wllh_th -= bv.activeSize * lgamma_beta
        } else {
          val docTopics = bv.asInstanceOf[Ndk]
          val used = docTopics.used
          val index = docTopics.index
          val data = docTopics.data
          var nd = 0
          var i = 0
          while (i < used) {
            val topic = index(i)
            val cnt = data(i)
            dllh_th += lgamma(cnt + alphaks(topic)) - lgamma_alphaks(topic)
            nd += cnt
            i += 1
          }
          dllh_th -= lgamma(nd + alphaSum)
        }
        pos = mask.nextSetBit(pos + 1)
      }
      wllhs += wllh_th
      dllhs += dllh_th
    }}
    withAwaitReadyAndClose(all)

    (wllhs, dllhs)
  }

  override def calculated: Boolean = _calculated

  override def output(writer: String => Unit): Unit = {
    if (calculated) {
      val o = s"total llh=$getTotal, word llh=$getWord, doc llh=$getDoc"
      writer(o)
    } else {
      new Exception("Log-likelihood not calculated yet.")
    }
  }
}

class LDACoherence(lda: LDA,
  nTops: Int,
  lastIter: Boolean) extends LDAMetrics(lda) {
  var cohs: Array[Double] = _

  def getTotal: Double = if (cohs != null) cohs.sum / cohs.length else 0.0

  override def calc(): LDACoherence = if (lastIter) {
    val edges = lda.edges
    val verts = lda.verts

    val algo = lda.algo
    val numThreads = edges.context.getConf.getInt(cs_numThreads, 1)
    val numTopics = lda.numTopics
    val storageLevel = lda.storageLevel

    val topicTopWords = verts.partitionsRDD.mapPartitions(_.flatMap { vp =>
      val totalSize = vp.capacity
      val index = vp.index
      val mask = vp.mask
      val values = vp.values
      val topicWords = Array.fill(numTopics)(new ConcurrentLinkedQueue[(Int, Int)])

      val sizePerthrd = {
        val npt = totalSize / numThreads
        if (npt * numThreads == totalSize) npt else npt + 1
      }
      implicit val es = initExecutionContext(numThreads)
      val all = Future.traverse(Range(0, numThreads).iterator) { thid => withFuture {
        val decomp = new BVDecompressor(numTopics)
        val startPos = sizePerthrd * thid
        val endPos = math.min(sizePerthrd * (thid + 1), totalSize)
        var pos = mask.nextSetBit(startPos)
        while (pos < endPos && pos >= 0) {
          val vid = index.getValue(pos)
          if (isTermId(vid)) {
            val wid = vid.toInt
            val termTopics = decomp.CV2BV(values(pos))
            termTopics match {
              case v: BDV[Count] =>
                var k = 0
                while (k < numTopics) {
                  val cnt = v(k)
                  if (cnt > 0) {
                    topicWords(k).add((cnt, wid))
                  }
                  k += 1
                }
              case v: BSV[Count] =>
                val used = v.used
                val index = v.index
                val data = v.data
                var i = 0
                while (i < used) {
                  topicWords(index(i)).add((data(i), wid))
                  i += 1
                }
            }
          }
          pos = mask.nextSetBit(pos + 1)
        }
      }}
      withAwaitReady(all)

      val all2 = Future.traverse(topicWords.iterator.zipWithIndex) { case (q, k) => withFuture {
        val topWords = q.toSeq.sorted.reverse.take(nTops).toArray
        (k, topWords)
      }}
      withAwaitResultAndClose(all2)
    }).reduceByKey((a, b) => (a ++ b).toSeq.sorted.reverse.take(nTops).toArray)
    topicTopWords.persist(storageLevel)

    val wordInParts = topicTopWords.mapPartitionsWithIndex { (pid, iter) =>
      val wordSet = iter.flatMap(_._2.map(_._2)).toSet
      wordSet.iterator.map((_, pid))
    }.aggregateByKey(new mutable.ArrayBuffer[Int])(_ += _, _ ++= _).mapValues(_.toArray)
    wordInParts.persist(storageLevel)

    val candWords = wordInParts.keys.collect().toSet
    val candWordsBc = edges.context.broadcast(candWords)

    val dwpf = algo.docOfWordsPartition(candWordsBc) _
    val docInWords = edges.partitionsRDD.mapPartitions(_.flatMap { case (_, ep) =>
      dwpf(ep)
    }).reduceByKey(_ ++ _).mapValues(_.sorted.toArray)

    val partitioner = topicTopWords.partitioner.get
    val numParts = partitioner.numPartitions
    val cohIndices = topicTopWords.mapPartitionsWithIndex( { case (pid, iter) =>
      val twp = iter.map { case (topic, topWords) => (topic, topWords.map(_._2)) }.toArray
      Iterator.single((pid, twp))
    }, preservesPartitioning=false).partitionBy(partitioner)
    val cohData = wordInParts.zipPartitions(docInWords, preservesPartitioning=false) { (partIter, docIter) =>
      val inParts = partIter.toMap
      val shippedData = Array.fill(numParts)(new ConcurrentLinkedQueue[(Int, Array[Long])])

      implicit val es = initExecutionContext(numThreads)
      val all = Future.traverse(docIter.grouped(numThreads * 5).toIterator) { batch => withFuture {
        batch.foreach { case (wid, docs) =>
          inParts(wid).foreach(shippedData(_).add((wid, docs)))
        }
      }}
      withAwaitReadyAndClose(all)
      shippedData.iterator.zipWithIndex.map { case (q, pid) => (pid, q.toSeq.toArray) }
    }.partitionBy(partitioner)

    val res = cohIndices.zipPartitions(cohData, preservesPartitioning=true) { (idxIter, dataIter) =>
      val inWords = new mutable.HashMap[Int, Array[Long]]
      dataIter.foreach(_._2.foreach(inWords += _))

      implicit val es = initExecutionContext(numThreads)
      val all = Future.traverse(idxIter.flatMap(_._2)) { case (topic, wids) => withFuture {
        val nWords = math.min(nTops, wids.length)
        var coh = 0.0
        var wi = 0
        while (wi < nWords - 1) {
          val datai = inWords(wids(wi))
          val ni = datai.length
          var wj = wi + 1
          while (wj < nWords) {
            val dataj = inWords(wids(wj))
            val nij = commonCount(datai, dataj)
            coh += math.log((nij + 1.0) / ni)
            wj += 1
          }
          wi += 1
        }
        (topic, coh)
      }}
      withAwaitResultAndClose(all)
    }.collect()

    topicTopWords.unpersist(blocking=false)
    wordInParts.unpersist(blocking=false)
    candWordsBc.unpersist(blocking=false)
    cohs = new Array[Double](numTopics)
    res.par.foreach { case (k, coh) => cohs(k) = coh }
    assert(cohs.forall(_ < 0))
    this
  } else {
    this
  }

  private def commonCount(docs1: Array[Long], docs2: Array[Long]): Int = {
    commonCount(docs1, 0, docs1.length, docs2, 0, docs2.length)
  }

  private def commonCount(docs1: Array[Long], s1: Int, e1: Int,
    docs2: Array[Long], s2: Int, e2: Int): Int = {
    if (s1 >= e1 || s2 >= e2) {
      0
    } else {
      val m1 = (s1 + e1) >> 1
      val m2 = (s2 + e2) >> 1
      val d1 = docs1(m1)
      val d2 = docs2(m2)
      if (d1 == d2) {
        commonCount(docs1, s1, m1, docs2, s2, m2) + commonCount(docs1, m1 + 1, e1, docs2, m2 + 1, e2) + 1
      } else if (d1 < d2) {
        commonCount(docs1, s1, m1 + 1, docs2, s2, m2) + commonCount(docs1, m1 + 1, e1, docs2, m2, e2)
      } else {
        commonCount(docs1, s1, m1, docs2, s2, m2 + 1) + commonCount(docs1, m1, e1, docs2, m2 + 1, e2)
      }
    }
  }

  override def calculated: Boolean = cohs != null

  override def output(writer: String => Unit): Unit = {
    if (calculated) {
      val o = s"average topic coherence=$getTotal"
      writer(o)
    } else {
      new Exception("Coherence not calculated yet.")
    }
  }
}

object LDAMetrics {
  def apply(lda: LDA,
    evalMetrics: Array[String],
    lastIter: Boolean): Array[LDAMetrics] = {
    evalMetrics.map { evalMetric =>
      val ldaMetric = evalMetric match {
        case "pplx" =>
          new LDAPerplexity(lda)
        case "llh" =>
          new LDALogLikelihood(lda)
        case "coh" =>
          new LDACoherence(lda, 20, lastIter)
      }
      ldaMetric.calc()
    }
  }
}


text:
using System;
using System.Windows;
using System.Windows.Controls;

namespace JurgekebowhawiNofeerileji
{
    public class GridExtensions
    {
        public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached(
            "Name", typeof(string), typeof(GridExtensions), new PropertyMetadata(default(string)));

        public static void SetName(DependencyObject element, string value)
        {
            element.SetValue(NameProperty, value);
        }

        public static string GetName(DependencyObject element)
        {
            return (string) element.GetValue(NameProperty);
        }

        public static readonly DependencyProperty RowNameProperty = DependencyProperty.RegisterAttached(
            "RowName", typeof(string), typeof(GridExtensions),
            new PropertyMetadata(default(string), RowName_PropertyChanged));

        private static void RowName_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement frameworkElement)
            {
                if (e.NewValue is string rowName)
                {
                    if (string.IsNullOrEmpty(rowName))
                    {
                        return;
                    }

                    if (frameworkElement.Parent is Grid grid)
                    {
                        for (var i = 0; i < grid.RowDefinitions.Count; i++)
                        {
                            var gridRowDefinition = grid.RowDefinitions[i];
                            var gridRowName = GetName(gridRowDefinition);
                            if (!string.IsNullOrEmpty(gridRowName) &&
                                gridRowName.Equals(rowName, StringComparison.Ordinal))
                            {
                                Grid.SetRow(frameworkElement, i);
                                return;
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("只有在Grid容器内才能设置 RowName 附加属性");
                    }
                }
            }
        }

        public static void SetRowName(DependencyObject element, string value)
        {
            element.SetValue(RowNameProperty, value);
        }

        public static string GetRowName(DependencyObject element)
        {
            return (string) element.GetValue(RowNameProperty);
        }

        public static readonly DependencyProperty ColumnNameProperty = DependencyProperty.RegisterAttached(
            "ColumnName", typeof(string), typeof(GridExtensions),
            new PropertyMetadata(default(string), ColumnName_PropertyChanged));

        private static void ColumnName_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement frameworkElement)
            {
                if (e.NewValue is string columnName)
                {
                    if (string.IsNullOrEmpty(columnName))
                    {
                        return;
                    }

                    if (frameworkElement.Parent is Grid grid)
                    {
                        for (var i = 0; i < grid.ColumnDefinitions.Count; i++)
                        {
                            var gridColumnDefinition = grid.ColumnDefinitions[i];
                            var gridColumnName = GetName(gridColumnDefinition);
                            if (!string.IsNullOrEmpty(gridColumnName) &&
                                gridColumnName.Equals(columnName, StringComparison.Ordinal))
                            {
                                Grid.SetColumn(frameworkElement, i);
                                return;
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("只有在Grid容器内才能设置 ColumnName 附加属性");
                    }
                }
            }
        }

        public static void SetColumnName(DependencyObject element, string value)
        {
            element.SetValue(ColumnNameProperty, value);
        }

        public static string GetColumnName(DependencyObject element)
        {
            return (string) element.GetValue(ColumnNameProperty);
        }
    }
}


text:
layout: pattern
title: Chain of responsibility
folder: chain-of-responsibility
categories: pattern_cat
tags: pattern_tag
---

**Intent:** Avoid coupling the sender of a request to its receiver by giving
more than one object a chance to handle the request. Chain the receiving
objects and pass the request along the chain until an object handles it.

![alt text](./chain/etc/chain_1.png "Chain of Responsibility")

**Applicability:** Use Chain of Responsibility when

* more than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically
* you want to issue a request to one of several objects without specifying the receiver explicitly
* the set of objects that can handle a request should be specified dynamically

**Real world examples:**

* [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29)
* [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html)


text:
namespace BuildReportTool.Window
{

public static class Settings
{
	// GUI Settings
	public const string DEFAULT_GUI_SKIN_FILENAME = "BuildReportWindow.guiskin";
	public const string DARK_GUI_SKIN_FILENAME = "BuildReportWindowDark.guiskin";

	// list normal is a list style with normal font size
	public const string LIST_NORMAL_STYLE_NAME = "ListNormal";
	public const string LIST_NORMAL_ALT_STYLE_NAME = "ListAltNormal";

	// list small is a list style with smaller font size (for the asset list)
	public const string LIST_SMALL_STYLE_NAME = "List";
	public const string LIST_SMALL_ALT_STYLE_NAME = "ListAlt";
	public const string LIST_SMALL_SELECTED_NAME = "ListAltSelected";

	public const string TOOLBAR_LEFT_STYLE_NAME = "ToolbarLeft";
	public const string TOOLBAR_MIDDLE_STYLE_NAME = "ToolbarMiddle";
	public const string TOOLBAR_RIGHT_STYLE_NAME = "ToolbarRight";

	public const string TAB_LEFT_STYLE_NAME = "TabLeft";
	public const string TAB_MIDDLE_STYLE_NAME = "TabMiddle";
	public const string TAB_RIGHT_STYLE_NAME = "TabRight";

	public const string STATUS_BAR_LABEL_STYLE_NAME = "StatusBarLabel";

	public const string VERSION_STYLE_NAME = "Version";

	public const string TOP_BAR_LABEL_STYLE_NAME = "TopBarLabel";
	public const string TOP_BAR_BTN_STYLE_NAME = "TopBarButton";
	public const string TOP_BAR_BG_STYLE_NAME = "TopBarBg";

	public const string LIST_COLUMN_HEADER_STYLE_NAME = "ListColumnHeader";
	public const string LIST_COLUMN_HEADER_ASC_STYLE_NAME = "ListColumnHeader-Asc";
	public const string LIST_COLUMN_HEADER_DESC_STYLE_NAME = "ListColumnHeader-Desc";

	public const string FILE_FILTER_POPUP_STYLE_NAME = "TopBarPopup";

	public const string LIST_FILENAME_STYLE = "button";
	public const string LIST_FILEPATH_STYLE = "button";

	public const string HIDDEN_SCROLLBAR_STYLE_NAME = "HiddenScrollbar";

	public const string MAIN_TITLE_STYLE_NAME = "Title";
	public const string MAIN_SUBTITLE_STYLE_NAME = "Subtitle";
	public const string TINY_HELP_STYLE_NAME = "TinyHelp";

	public const string INFO_TITLE_STYLE_NAME = "Big1";

	public const string INFO_SUBTITLE_STYLE_NAME = "Header2";
	public const string INFO_SUBTITLE_BOLD_STYLE_NAME = "Header2Bold";

	public const string BIG_NUMBER_STYLE_NAME = "Big2";

	public const string INFO_TEXT_STYLE_NAME = "TextInfo";

	public const string SETTING_NAME_STYLE_NAME = "TextBold";
	public const string SETTING_VALUE_STYLE_NAME = "Text";

	public const float CATEGORY_VERTICAL_SPACING = 40;
	public const float CATEGORY_HORIZONTAL_SPACING = 30;

	public const string BIG_LEFT_ARROW_ICON_STYLE_NAME = "Icon-ArrowBig-Left";
	public const string BIG_RIGHT_ARROW_ICON_STYLE_NAME = "Icon-ArrowBig-Right";
}

}

#endif


text:
<?php
/**
 * This file belongs to the YIT Plugin Framework.
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 */

/**
 * Select Plugin Admin View
 *
 * @package    Yithemes
 * @author     Emanuela Castorina <emanuela.castorina@yithemes.it>
 * @since      1.0.0
 */

if ( ! defined( 'YIT' ) ) {
    exit;
} // Exit if accessed directly
?>


text:
package org.codehaus.groovy.ast.decompiled;

import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.MixinNode;
import org.codehaus.groovy.classgen.Verifier;

import java.lang.reflect.Modifier;
import java.util.List;

/**
 * A {@link ClassNode} kind representing the classes coming from *.class files decompiled using ASM.
 *
 * @see AsmDecompiler
 * @author Peter Gromov
 */
public class DecompiledClassNode extends ClassNode {
    private final ClassStub classData;
    private final AsmReferenceResolver resolver;
    private boolean supersInitialized = false;
    private boolean membersInitialized = false;

    public DecompiledClassNode(ClassStub data, AsmReferenceResolver resolver) {
        super(data.className, getFullModifiers(data, resolver), null, null, MixinNode.EMPTY_ARRAY);
        classData = data;
        this.resolver = resolver;
        isPrimaryNode = false;
    }

    /**
     * Static inner classes don't have "static" part in their own modifiers. Their containing classes have to be inspected
     * whether they have an inner class with the same name that's static. '$' separator convention is used to search
     * for parent classes.
     */
    private static int getFullModifiers(ClassStub data, AsmReferenceResolver resolver) {
        String className = data.className;
        int bound = className.length();
        while (bound > 0) {
            int idx = className.lastIndexOf('$', bound);
            if (idx > 0) {
                ClassNode outerClass = resolver.resolveClassNullable(className.substring(0, idx));
                if (outerClass instanceof DecompiledClassNode) {
                    Integer outerModifiers = ((DecompiledClassNode) outerClass).classData.innerClassModifiers.get(className.substring(idx + 1));
                    if (outerModifiers != null) {
                        return data.accessModifiers | outerModifiers;
                    }
                }
            }
            bound = idx - 1;
        }
        return data.accessModifiers;
    }

    public long getCompilationTimeStamp() {
        if (classData.fields != null) {
            for (FieldStub field : classData.fields) {
                if (Modifier.isStatic(field.accessModifiers)) {
                    Long timestamp = Verifier.getTimestampFromFieldName(field.fieldName);
                    if (timestamp != null) {
                        return timestamp;
                    }
                }
            }
        }
        return Long.MAX_VALUE;
    }

    @Override
    public GenericsType[] getGenericsTypes() {
        lazyInitSupers();
        return super.getGenericsTypes();
    }

    @Override
    public boolean isUsingGenerics() {
        lazyInitSupers();
        return super.isUsingGenerics();
    }

    @Override
    public List<FieldNode> getFields() {
        lazyInitMembers();
        return super.getFields();
    }

    @Override
    public ClassNode[] getInterfaces() {
        lazyInitSupers();
        return super.getInterfaces();
    }

    @Override
    public List<MethodNode> getMethods() {
        lazyInitMembers();
        return super.getMethods();
    }

    @Override
    public List<ConstructorNode> getDeclaredConstructors() {
        lazyInitMembers();
        return super.getDeclaredConstructors();
    }

    @Override
    public FieldNode getDeclaredField(String name) {
        lazyInitMembers();
        return super.getDeclaredField(name);
    }

    @Override
    public List<MethodNode> getDeclaredMethods(String name) {
        lazyInitMembers();
        return super.getDeclaredMethods(name);
    }

    @Override
    public ClassNode getUnresolvedSuperClass(boolean useRedirect) {
        lazyInitSupers();
        return super.getUnresolvedSuperClass(useRedirect);
    }

    @Override
    public ClassNode[] getUnresolvedInterfaces(boolean useRedirect) {
        lazyInitSupers();
        return super.getUnresolvedInterfaces(useRedirect);
    }

    @Override
    public List<AnnotationNode> getAnnotations() {
        lazyInitSupers();
        return super.getAnnotations();
    }

    @Override
    public List<AnnotationNode> getAnnotations(ClassNode type) {
        lazyInitSupers();
        return super.getAnnotations(type);
    }

    @Override
    public void setRedirect(ClassNode cn) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setGenericsPlaceHolder(boolean b) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setUsingGenerics(boolean b) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String setName(String name) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isResolved() {
        return true;
    }

    @Override
    public Class getTypeClass() {
        return resolver.resolveJvmClass(getName());
    }

    private void lazyInitSupers() {
        synchronized (lazyInitLock) {
            if (!supersInitialized) {
                ClassSignatureParser.configureClass(this, this.classData, this.resolver);
                addAnnotations(classData, this);
                supersInitialized = true;
            }
        }

    }

    private void lazyInitMembers() {
        synchronized (lazyInitLock) {
            if (!membersInitialized) {
                if (classData.methods != null) {
                    for (MethodStub method : classData.methods) {
                        MethodNode node = addAnnotations(method, MemberSignatureParser.createMethodNode(resolver, method));
                        if (node instanceof ConstructorNode) {
                            addConstructor((ConstructorNode) node);
                        } else {
                            addMethod(node);
                        }
                    }
                }

                if (classData.fields != null) {
                    for (FieldStub field : classData.fields) {
                        addField(addAnnotations(field, MemberSignatureParser.createFieldNode(field, resolver, this)));
                    }
                }

                membersInitialized = true;
            }
        }
    }

    private <T extends AnnotatedNode> T addAnnotations(MemberStub stub, T node) {
        List<AnnotationStub> annotations = stub.annotations;
        if (annotations != null) {
            for (AnnotationStub annotation : annotations) {
                AnnotationNode annotationNode = Annotations.createAnnotationNode(annotation, resolver);
                if (annotationNode != null) {
                    node.addAnnotation(annotationNode);
                }
            }
        }
        return node;
    }

}


text:
const io = require('../../infrastructure/socketio');
const controller = require('./controller');

io.use(controller.joinExistingRooms);

io.on('connect', (socket) => {
  socket.on('send_message', controller.sendMessage.bind(undefined, socket));
  socket.on('new_chat', controller.createRoom.bind(undefined, socket));
});


text:
(function() {
  'use strict';

  angular
    .module('storytellingDemo')
    .factory('$storytelling', storytelling);

  /* @ngInject */
  function storytelling(scrollWatcher, $timeout, $rootScope, $q, d3, $document){
    var vm = {};
    vm.currentBreakPoint  = 0;
    vm.currentSlide       = 0;
    vm.bpHasChanged       = false;
    vm.scroll             = initScroll;
    vm.animateElem        = animateElem;
    vm.animateD3          = animateD3;
    vm.zoomTo             = zoomTo;
    vm.resetZoom          = resetZoom;

    /** Init scroll behaviour on .outer and .inner divs
     * @param {string} parent - Name of parent to fixed scroll
     * @param {string} scrollVarName - Specifies name for scrolling accesor
     * @param {integer} slidesNumber - Number of slides outer will be devided by
     * @param {function} callback - Function that will be executed when slide changes
     */
    function initScroll(parent, scrollVarName, slidesNumber, callback) {
      vm[scrollVarName] = 0;
      $timeout(function(){
        scrollWatcher({
          parent: parent,
          onUpdate: function(scrollPercent, parentElement) {
            if(vm[scrollVarName] != scrollPercent) { // scrolling position has changed
              $rootScope.$apply(function(){
                vm[scrollVarName] = (vm[scrollVarName] != scrollPercent) ? scrollPercent : vm[scrollVarName];
                vm.currentBreakPoint = parentElement.selector;
                if(vm.currentSlide !== getSlide(101, 0, slidesNumber, vm[scrollVarName])) {
                  vm.currentSlide = getSlide(101, 0, slidesNumber, vm[scrollVarName]);
                  callback();
                }
              });
            }
          }
        });
      });
    }

    /**
     * Calculate slide number that has to be seen
     * @param {number} end - End percentage
     * @param {number} start - Start percentage
     * @param {number} slidesLength - Quantity of slides defined
     * @param {number} scrollPercent - Current scroll percentage
     */
    function getSlide(end, start, slidesLength, scrollPercent){
      if(slidesLength == 0) {
        return 0;
      }
      var mul = (end - start) / slidesLength;
      return Math.floor((scrollPercent - start) / mul);
    }

    /**
     * Animate element using jQuery functions and animatecss
     * @param {selector} element
     * @param {string} animationName
     */
    function animateElem(element, animationName){
      return $q(function(resolve) { //, reject) {
        var animationEnds = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        angular.element(element).addClass('animated ' + animationName).one(animationEnds, function(){
          angular.element(this).removeClass('animated undefined ' + animationName);
          resolve(true);
        });
      })
    }

    /**
     * Animate elements using D3 and animatecss. It will replace ALL classes
     * @param {selector} element
     * @param {string} animationName
     */
    function animateD3(element, animationName) {
      return $q(function(resolve) { //} reject) {
        d3.selectAll(element).attr('class', null);
        d3.selectAll(element)
          .attr('class', 'animated ' + animationName)
          .on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
            d3.selectAll(element).attr('class', null);
            resolve(true);
          });
      });
    }

    /**
     * Resets group element (SVG) xoom to 0,0 and scale 1
     * @param {d3 selection} groupElement
     */
    function resetZoom(groupElement) {
      groupElement.transition()
        .duration(500)
        .attr('transform', 'translate(0,0) scale(1)')
    }

    /**
     * Zoom group element (SVG) to calculated position of selector
     * Results may vary according to SVG properties
     * @param {d3 selection} groupElement
     * @param {string selector} selector
     */
    function zoomTo(groupElement, selector) {
      if(groupElement && selector && $document[0].querySelector(selector)) {
        $timeout(function(){

          var transform = 'translate(0,0)scale(1)';
          groupElement.attr('transform', null);

          var clientRect = $document[0].querySelector(selector).getBoundingClientRect();
          var bbox = angular.element(selector)[0].getBBox();
          var svg = groupElement._groups[0][0].parentNode.getBoundingClientRect();
          var active_pos = {
              x: bbox.x,
              y: bbox.y,
              width : clientRect.width,
              height : clientRect.height,
              centroidX: bbox.x / 2,
              centroidY: bbox.y
            };

          groupElement.attr('transform', transform);
          var scale = d3.min([svg.height / active_pos.height, svg.width / active_pos.width]);

          active_pos.translateX = -(active_pos.centroidX * scale * 2);
          active_pos.translateY = -(active_pos.centroidY * scale);

          groupElement
            .transition()
              .duration(600)
              .attr('transform', 'translate(' + active_pos.translateX + ',' + active_pos.translateY + ') scale(' + scale + ')')
        });
      }
    }

    function zoomImage(selector) {

    }
    return vm;
  }
})();


text:
from mock import patch
from conf.appconfig import LEVEL_FAILED, LEVEL_FAILED_WARN, \
    LEVEL_SUCCESS
from orchestrator.tasks import notification

@patch('orchestrator.tasks.notification.notify_hipchat')
def test_notify_when_disabled(m_notify_hipchat):
    # Given: Disabled notifications
    notifications = {
        'hipchat': {
            'enabled': False
        }
    }

    # When: I invoke notify
    notification.notify('mockerror', notifications=notifications)

    # Then: No notifications are sent
    m_notify_hipchat.si.assert_not_called()

@patch('orchestrator.tasks.notification.notify_hipchat')
def test_notify_when_level_not_enabled(m_notify_hipchat):
    # Given: Enabled hipchat notifications with level error
    notifications = {
        'hipchat': {
            'enabled': True,
            'level': LEVEL_FAILED
        }
    }

    # When: I invoke notify using level warn
    notification.notify('mockwarn', level=LEVEL_FAILED_WARN,
                        notifications=notifications)

    # Then: No notifications are sent
    m_notify_hipchat.si.assert_not_called()

@patch('orchestrator.tasks.notification.notify_hipchat')
def test_notify_when_notification_type_not_found(m_notify_hipchat):
    # Given: Enabled hipchat notifications with level error
    notifications = {
        'invalid': {
            'enabled': True,
            'level': LEVEL_FAILED
        }
    }

    # When: I invoke notify
    notification.notify('mockerror', notifications=notifications)

    # Then: No notifications are sent
    m_notify_hipchat.si.assert_not_called()

@patch('orchestrator.tasks.notification.notify_hipchat')
def test_notify(m_notify_hipchat):
    # Given: Enabled hipchat notifications with level error
    notifications = {
        'hipchat': {
            'enabled': True,
            'level': LEVEL_FAILED
        }
    }

    # When: I invoke notify using level warn
    notification.notify('mockerror', notifications=notifications)

    # Then: Hipchat notification is sent
    m_notify_hipchat.si.assert_called_once()

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.templatefactory')
@patch('orchestrator.tasks.notification.json')
def test_notify_hipchat(m_json, m_templatefactory, m_requests):
    """
    Should send hipchat notification
    :return:
    """
    # Given: Template factory that renders html template for notification
    m_templatefactory.render_template.return_value = 'mockmsg'

    # And: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send message using hipchat
    notification.notify_hipchat(
        {'message': 'mock'}, {}, LEVEL_FAILED,
        {'token': 'mocktoken', 'room': 'mockroom',
         'colors': {'1': 'red', '3': 'green'}},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_called_once_with(
        'https://api.hipchat.com/v2/room/mockroom/notification',
        headers={
            'content-type': 'application/json',
            'Authorization': 'Bearer mocktoken'},
        data={
            'color': 'red',
            'message': 'mockmsg',
            'notify': True,
            'message_format': 'html'
        })

    m_templatefactory.render_template.assert_called_once_with(
        'hipchat.html',
        notification={'message': 'mock'},
        ctx={'github': True},
        level=LEVEL_FAILED,
    )

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.templatefactory')
@patch('orchestrator.tasks.notification.json')
def test_notify_hipchat_for_level_success(m_json, m_templatefactory,
                                          m_requests):
    """
    Should send hipchat notification
    :return:
    """
    # Given: Template factory that renders html template for notification
    m_templatefactory.render_template.return_value = 'mockmsg'

    # And: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send message using hipchat
    notification.notify_hipchat(
        {'message': 'mock'}, {}, LEVEL_SUCCESS,
        {'token': 'mocktoken', 'room': 'mockroom',
         'colors': {'1': 'red', '3': 'green'}},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_called_once_with(
        'https://api.hipchat.com/v2/room/mockroom/notification',
        headers={
            'content-type': 'application/json',
            'Authorization': 'Bearer mocktoken'},
        data={
            'color': 'green',
            'message': 'mockmsg',
            'notify': False,
            'message_format': 'html'
        })

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.templatefactory')
@patch('orchestrator.tasks.notification.json')
def test_notify_slack(m_json, m_templatefactory, m_requests):
    """
    Should send slack notification
    :return:
    """
    # Given: Template factory that renders html template for notification
    m_templatefactory.render_template.return_value = '{}'

    # And: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send message using slack
    notification.notify_slack(
        {'message': 'mock'}, {}, LEVEL_FAILED,
        {'url': 'http://mockslackurl'},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_called_once_with(
        'http://mockslackurl',
        headers={
            'content-type': 'application/json'
        },
        data='{}')

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.templatefactory')
@patch('orchestrator.tasks.notification.json')
def test_notify_slack_when_url_is_not_set(m_json, m_templatefactory,
                                          m_requests):
    """
    Should not send slack notification
    :return:
    """
    # Given: Template factory that renders html template for notification
    m_templatefactory.render_template.return_value = '{}'

    # And: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send message using slack
    notification.notify_slack(
        {'message': 'mock'}, {}, LEVEL_FAILED,
        {},
        'default')

    # Then: Notification is not sent
    m_requests.post.assert_not_called()

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.json')
def test_github(m_json, m_requests):
    """
    Should send github commit notification
    """

    # Given: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send notification using github
    notification.notify_github(
        {'message': 'mock'},
        {'commit': 'mockcommit', 'ref': 'mockref', 'repo': 'mockrepo',
         'owner': 'mockowner'},
        LEVEL_FAILED,
        {'token': 'mocktoken'},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_called_once_with(
        'https://api.github.com/repos/mockowner/mockrepo/statuses/mockcommit',
        headers={
            'Content-Type': 'application/json',
            'Authorization': 'token mocktoken',
            'Accept': 'application/vnd.github.v3+json'
        },
        data={
            'state': 'failure',
            'description': 'mock',
            'context': 'local::Orchestrator'
        })

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.json')
def test_github_with_no_git_metadata(m_json, m_requests):
    """
    Should not send github commit notification when commit, ref, repo, owner is
    missing.
    """

    # Given: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send notification using github
    notification.notify_github(
        {'message': 'mock'},
        {},
        LEVEL_FAILED,
        {'token': 'mocktoken'},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_not_called()

@patch('orchestrator.tasks.notification.requests')
@patch('orchestrator.tasks.notification.json')
def test_github_with_no_token(m_json, m_requests):
    """
    Should not send github commit notification when GITHUB token is not
    specified.
    """

    # Given: Mock implementation for jsonify (for validating data)
    m_json.dumps.side_effect = lambda data: data

    # When: I send notification using github
    notification.notify_github(
        {'commit': 'mockcommit', 'ref': 'mockref', 'repo': 'mockrepo',
         'owner': 'mockowner'},
        {},
        LEVEL_FAILED,
        {'token': ''},
        'default')

    # Then: Notification gets send successfully
    m_requests.post.assert_not_called()


text:
"""Allows beets to embed album art into file metadata."""
from __future__ import division, absolute_import, print_function

import os.path

from beets.plugins import BeetsPlugin
from beets import ui
from beets.ui import print_, decargs
from beets.util import syspath, normpath, displayable_path, bytestring_path
from beets.util.artresizer import ArtResizer
from beets import config
from beets import art

def _confirm(objs, album):
    """Show the list of affected objects (items or albums) and confirm
    that the user wants to modify their artwork.

    `album` is a Boolean indicating whether these are albums (as opposed
    to items).
    """
    noun = u'album' if album else u'file'
    prompt = u'Modify artwork for {} {}{} (Y/n)?'.format(
        len(objs),
        noun,
        u's' if len(objs) > 1 else u''
    )

    # Show all the items or albums.
    for obj in objs:
        print_(format(obj))

    # Confirm with user.
    return ui.input_yn(prompt)

class EmbedCoverArtPlugin(BeetsPlugin):
    """Allows albumart to be embedded into the actual files.
    """
    def __init__(self):
        super(EmbedCoverArtPlugin, self).__init__()
        self.config.add({
            'maxwidth': 0,
            'auto': True,
            'compare_threshold': 0,
            'ifempty': False,
            'remove_art_file': False,
            'quality': 0,
        })

        if self.config['maxwidth'].get(int) and not ArtResizer.shared.local:
            self.config['maxwidth'] = 0
            self._log.warning(u"ImageMagick or PIL not found; "
                              u"'maxwidth' option ignored")
        if self.config['compare_threshold'].get(int) and not \
                ArtResizer.shared.can_compare:
            self.config['compare_threshold'] = 0
            self._log.warning(u"ImageMagick 6.8.7 or higher not installed; "
                              u"'compare_threshold' option ignored")

        self.register_listener('art_set', self.process_album)

    def commands(self):
        # Embed command.
        embed_cmd = ui.Subcommand(
            'embedart', help=u'embed image files into file metadata'
        )
        embed_cmd.parser.add_option(
            u'-f', u'--file', metavar='PATH', help=u'the image file to embed'
        )
        embed_cmd.parser.add_option(
            u"-y", u"--yes", action="store_true", help=u"skip confirmation"
        )
        maxwidth = self.config['maxwidth'].get(int)
        quality = self.config['quality'].get(int)
        compare_threshold = self.config['compare_threshold'].get(int)
        ifempty = self.config['ifempty'].get(bool)

        def embed_func(lib, opts, args):
            if opts.file:
                imagepath = normpath(opts.file)
                if not os.path.isfile(syspath(imagepath)):
                    raise ui.UserError(u'image file {0} not found'.format(
                        displayable_path(imagepath)
                    ))

                items = lib.items(decargs(args))

                # Confirm with user.
                if not opts.yes and not _confirm(items, not opts.file):
                    return

                for item in items:
                    art.embed_item(self._log, item, imagepath, maxwidth,
                                   None, compare_threshold, ifempty,
                                   quality=quality)
            else:
                albums = lib.albums(decargs(args))

                # Confirm with user.
                if not opts.yes and not _confirm(albums, not opts.file):
                    return

                for album in albums:
                    art.embed_album(self._log, album, maxwidth,
                                    False, compare_threshold, ifempty,
                                    quality=quality)
                    self.remove_artfile(album)

        embed_cmd.func = embed_func

        # Extract command.
        extract_cmd = ui.Subcommand(
            'extractart',
            help=u'extract an image from file metadata',
        )
        extract_cmd.parser.add_option(
            u'-o', dest='outpath',
            help=u'image output file',
        )
        extract_cmd.parser.add_option(
            u'-n', dest='filename',
            help=u'image filename to create for all matched albums',
        )
        extract_cmd.parser.add_option(
            '-a', dest='associate', action='store_true',
            help='associate the extracted images with the album',
        )

        def extract_func(lib, opts, args):
            if opts.outpath:
                art.extract_first(self._log, normpath(opts.outpath),
                                  lib.items(decargs(args)))
            else:
                filename = bytestring_path(opts.filename or
                                           config['art_filename'].get())
                if os.path.dirname(filename) != b'':
                    self._log.error(
                        u"Only specify a name rather than a path for -n")
                    return
                for album in lib.albums(decargs(args)):
                    artpath = normpath(os.path.join(album.path, filename))
                    artpath = art.extract_first(self._log, artpath,
                                                album.items())
                    if artpath and opts.associate:
                        album.set_art(artpath)
                        album.store()
        extract_cmd.func = extract_func

        # Clear command.
        clear_cmd = ui.Subcommand(
            'clearart',
            help=u'remove images from file metadata',
        )
        clear_cmd.parser.add_option(
            u"-y", u"--yes", action="store_true", help=u"skip confirmation"
        )

        def clear_func(lib, opts, args):
            items = lib.items(decargs(args))
            # Confirm with user.
            if not opts.yes and not _confirm(items, False):
                return
            art.clear(self._log, lib, decargs(args))
        clear_cmd.func = clear_func

        return [embed_cmd, extract_cmd, clear_cmd]

    def process_album(self, album):
        """Automatically embed art after art has been set
        """
        if self.config['auto'] and ui.should_write():
            max_width = self.config['maxwidth'].get(int)
            art.embed_album(self._log, album, max_width, True,
                            self.config['compare_threshold'].get(int),
                            self.config['ifempty'].get(bool))
            self.remove_artfile(album)

    def remove_artfile(self, album):
        """Possibly delete the album art file for an album (if the
        appropriate configuration option is enabled).
        """
        if self.config['remove_art_file'] and album.artpath:
            if os.path.isfile(album.artpath):
                self._log.debug(u'Removing album art file for {0}', album)
                os.remove(album.artpath)
                album.artpath = None
                album.store()


text:
@interface SearchBlogViewController ()

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray *bloggerModelArray;

@end

@implementation SearchBlogViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = view;

    [self.tableView registerNib:[UINib nibWithNibName:@"BloggerTableViewCell" bundle:nil] forCellReuseIdentifier:@"BloggerTableViewCell"];

    __weak SearchBlogViewController *weakSelf = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf requestBloggerData];
    }];
}

- (void)requestBloggerData {
    [ProtocolUtil getBloggerListWithSearchText:self.searchBar.text success:^(id data, id identifier) {
        [self.tableView.header endRefreshing];
        self.bloggerModelArray = data;
        [self.tableView reloadData];
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        [self.tableView.header endRefreshing];
    }];
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self.tableView.header beginRefreshing];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bloggerModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BloggerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BloggerTableViewCell" forIndexPath:indexPath];
    BloggerModel *model = self.bloggerModelArray[indexPath.row];
    [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

    }];
    cell.titleLabel.text = model.title;
    cell.updatedLabel.text = [model.updateDate stringWithFormate:yyMMddHHmm];
    cell.postCountLabel.text = [model.postCount stringValue];
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BloggerModel *bloggerModel = self.bloggerModelArray[indexPath.row];
    [self performSegueWithIdentifier:@"SearchToBloggerSegue" sender:bloggerModel];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"SearchToBloggerSegue"]) {
        BloggerTableViewController *viewController = segue.destinationViewController;
        viewController.bloggerModel = sender;
    }
}

@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mysterious Wildwood 84851</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea vinorubens Werner

### Remarks
null


text:
if(APPLE)
	find_package(PkgConfig)
	pkg_check_modules(PC_GLEW QUIET glew)
endif(APPLE)

find_path(GLEW_INCLUDE_DIR
	GL/glew.h
	HINTS ${PC_GLEW_INCLUDEDIR} ${PC_GLEW_INCLUDE_DIRS}
)
find_library(GLEW_LIBRARY
	GLEW
	HINTS ${PC_GLEW_LIBDIR} ${PC_GLEW_LIBRARY_DIRS}
)

set(GLEW_INCLUDE_DIRS ${GLEW_INCLUDE_DIR})
set(GLEW_LIBRARIES ${GLEW_LIBRARY})

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GLEW DEFAULT_MSG
	GLEW_INCLUDE_DIR
	GLEW_LIBRARY
)

mark_as_advanced(
	GLEW_INCLUDE_DIR
	GLEW_LIBRARY
)


text:
package io.cucumber.core.backend;

public class StubStaticHookDefinition implements StaticHookDefinition {

    private static final String STUBBED_LOCATION_WITH_DETAILS = "{stubbed location with details}";
    private final String location;
    private final RuntimeException exception;
    private final Runnable action;

    public StubStaticHookDefinition(String location, RuntimeException exception, Runnable action) {
        this.location = location;
        this.exception = exception;
        this.action = action;
    }

    public StubStaticHookDefinition(String location, Runnable action) {
        this(location, null, action);
    }

    public StubStaticHookDefinition() {
        this(STUBBED_LOCATION_WITH_DETAILS, null, null);
    }

    public StubStaticHookDefinition(Runnable action) {
        this(STUBBED_LOCATION_WITH_DETAILS, null, action);
    }

    public StubStaticHookDefinition(RuntimeException exception) {
        this(STUBBED_LOCATION_WITH_DETAILS, exception, null);
    }

    public StubStaticHookDefinition(String location) {
        this(location, null, null);
    }

    @Override
    public void execute() {
        if (action != null) {
            action.run();
        }
        if (exception != null) {
            throw exception;
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public boolean isDefinedAt(StackTraceElement stackTraceElement) {
        return false;
    }

    @Override
    public String getLocation() {
        return location;
    }

}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import SideBarView from '../SideBarView';
import Search from '../Search';

import LogoImg from '../../assets/images/logo_beta.svg';

import styles from './styles.scss';

function Footer() {
  return (

                Back to the main site

                  Legal

                  Security Policy

                  Privacy Policy

                  Community

                  Blog

              &copy 1999-2017 RingCentral, Inc. All rights reserved.

  );
}

class MainView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fixSidebar: false,
    };
    this.onScroll = () => {
      if (!this.rootBody) {
        return;
      }
      const scrollTop = this.rootBody.scrollTop;
      if (scrollTop > 180) {
        this.setState({ fixSidebar: true });
      } else {
        this.setState({ fixSidebar: false });
      }
    };
  }

  render() {
    return (

 {
          this.rootBody = rootBody;
        }}
      >

                <LogoImg />

RingCentral Widgets

            <Search components={this.props.components} />
            <SideBarView
              components={this.props.components}
              fixed={this.state.fixSidebar}
            >
              {this.props.children}
            </SideBarView>

    );
  }
}

MainView.propTypes = {
  children: PropTypes.node.isRequired,
  components: PropTypes.array.isRequired,
};

export default MainView;


text:
<?php
/*
  * This file is part of the Sulu CMS.
  *
  * (c) MASSIVE ART WebServices GmbH
  *
  * This source file is subject to the MIT license that is bundled
  * with this source code in the file LICENSE.
  */

namespace Sulu\Bundle\Sales\CoreBundle\Widgets;

use Sulu\Bundle\AdminBundle\Widgets\WidgetInterface;
use Sulu\Bundle\AdminBundle\Widgets\WidgetParameterException;
use Sulu\Bundle\AdminBundle\Widgets\WidgetEntityNotFoundException;
use Doctrine\ORM\EntityManager;
use Sulu\Bundle\ContactBundle\Entity\AccountInterface;
use Sulu\Bundle\ContactBundle\Entity\AccountRepository;

/**
 * SimpleAccount widget
 *
 * @package Sulu\Bundle\Sales\CoreBundle\Widgets
 */
class SimpleAccount implements WidgetInterface
{
    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @var string
     */
    protected $widgetName = 'SimpleAccount';

    /**
     * @var AccountRepository
     */
    protected $accountRepository;

    /**
     * @param EntityManager $em
     * @param AccountRepository $accountRepository
     */
    function __construct(EntityManager $em, AccountRepository $accountRepository)
    {
        $this->em = $em;
        $this->accountRepository = $accountRepository;
    }

    /**
     * Return name of widget
     *
     * @return string
     */
    public function getName()
    {
        return 'simple-account';
    }

    /**
     * Returns template name of widget
     *
     * @return string
     */
    public function getTemplate()
    {
        return 'SuluSalesCoreBundle:Widgets:core.account.html.twig';
    }

    /**
     * Returns data to render template
     *
     * @param array $options
     *
     * @throws WidgetEntityNotFoundException
     * @throws WidgetParameterException
     *
     * @return array
     */
    public function getData($options)
    {
        if (!empty($options) &&
            array_key_exists('account', $options) &&
            !empty($options['account'])
        ) {
            $id = $options['account'];
            $account = $this->accountRepository->find($id);

            if (!$account) {
                throw new WidgetEntityNotFoundException(
                    'Entity \'Account\' with id ' . $id . ' not found!',
                    $this->widgetName,
                    $id
                );
            }

            return $this->parseAccount($account);
        } else {
            throw new WidgetParameterException(
                'Required parameter contact not found or empty!',
                $this->widgetName,
                'account'
            );
        }
    }

    /**
     * Parses the account data
     *
     * @param AccountInterface $account
     *
     * @return array
     */
    protected function parseAccount(AccountInterface $account)
    {
        if ($account) {
            $data = [];
            $data['id'] = $account->getId();
            $data['name'] = $account->getName();
            $data['phone'] = $account->getMainPhone();
            $data['email'] = $account->getMainEmail();
            $data['url'] = $account->getMainUrl();

            $accountAddress = $account->getMainAddress();

            if ($accountAddress) {
                $data['address']['street'] = $accountAddress->getStreet();
                $data['address']['number'] = $accountAddress->getNumber();
                $data['address']['zip'] = $accountAddress->getZip();
                $data['address']['city'] = $accountAddress->getCity();
                $data['address']['country'] = $accountAddress->getCountry()->getName();
            }

            return $data;
        } else {
            return null;
        }
    }
}


text:
import Ember from 'ember';
import Sortable from 'ui/mixins/sortable';

export default Ember.Controller.extend(Sortable, {
  processesController : Ember.inject.controller('admin-tab.processes'),
  parentQueryParams   : Ember.computed.alias('processesController.queryParams'),
  showRunning         : Ember.computed.alias('processesController.showRunning'),
  resourceId          : Ember.computed.alias('processesController.resourceId'),
  resourceType        : Ember.computed.alias('processesController.resourceType'),
  processName         : Ember.computed.alias('processesController.processName'),
  // these are here so we can execute the search with the search button
  // so we dont have to do this.refresh in the route. I used this.refresh
  // in the route for something else and it caused other issues so i decided
  // against using it.
  ownResourceId        : null,
  ownResourceType      : null,
  ownProcessName       : null,
  resourceTypeReadable : null,

  sortableContent : Ember.computed.alias('model.processInstance'),
  sortBy          : 'startTime',
  descending      : true,

  sorts: {
    id          : ['id'],
    processName : ['processName', 'id'],
    resource    : ['resourceType', 'resourceId', 'id'],
    startTime   : ['startTime', 'id'],
    endTime     : ['endTime', 'id'],
    runTime     : ['runTime', 'id']
  },

  actions: {
    showRunningProcesses: function() {
      this.toggleProperty('showRunning');
    },
    updateType: function(type) {
      this.set('resourceTypeReadable', type);
      this.set('ownResourceType', type);
    },
    submit: function() {
      this.setProperties({
        resourceId   : this.get('ownResourceId'),
        resourceType : this.get('ownResourceType'),
        processName  : this.get('ownProcessName')
      });
    },
    reset: function() {
      this.setProperties({
        resourceId           : null,
        ownResourceId        : null,
        resourceType         : null,
        resourceTypeReadable : null,
        ownResourceType      : null,
        processName          : null,
        ownProcessName       : null
      });
      Ember.$('#resource-type').val('');
    },
  },

  parseParams: Ember.on('init', function() {
    // This parses the parent query strings since the input values are not bound
    // directly to the querystrings. See this.refresh comment at top of file for
    // more information.
    _.forEach(this.get('parentQueryParams'), (param) => {

      let paramVal = this.get(param);

      if (param !== 'showRunning') {

        if (paramVal) {

          switch (param) {
            case 'resourceId':
              this.set('ownResourceId', paramVal);
              break;
            case 'resourceType':
              this.set('ownResourceType', paramVal);

              Ember.run.later(() => {

                Ember.$('#resource-type').val(_.find(this.get('model.resourceTypes'), (item) =>{
                  return item === this.get(param);
                }));

              });
              break;
            case 'processName':
              this.set('ownProcessName', paramVal);
              break;
            default:
              break;
          }

        }
      }
    });
  }),

  disableId: Ember.computed('ownResourceType', function() {
    if (this.get('ownResourceType')) {
      return false;
    } else {
      return true;
    }
  }),
});


text:
require 'casa/attribute/loader_error'

module CASA
  module Attribute
    class LoaderFileError < LoaderError

    end
  end
end


text:
namespace gamelib
{
    ResourceViewer::ResourceViewer() :
        _open(false),
        _category(0),
        _dialog(FileDialog::Load)
    { }

    ResourceViewer::~ResourceViewer()
    {
        close();
    }

    void ResourceViewer::open()
    {
        if (!_open)
        {
            _open = true;
            _refresh();
        }
    }

    void ResourceViewer::close()
    {
        if (_open)
        {
            _open = false;
            _cache.clear();
            _selected.reset();
        }
    }

    void ResourceViewer::draw()
    {
        if (!_open)
            return;

        if (_dialog.process())
            if (getSubsystem<ResourceManager>()->load(_dialog.getPath()))
                _refresh();

        if (ImGui::Begin("Resource Manager", &_open))
        {
            if (ImGui::Button("Load"))
                _dialog.open(getSubsystem<ResourceManager>()->getSearchpaths().back().c_str());

            ImGui::SameLine();
            ImGui::Spacing();
            ImGui::SameLine();

            if (ImGui::Button("Refresh"))
                _refresh();

            ImGui::SameLine();
            ImGui::Spacing();
            ImGui::SameLine();

            if (ImGui::Combo("Category", &_category, [](void* data, int index, const char** name) -> bool {
                        const auto& cache = *static_cast<decltype(_cache)*>(data);
                        if (index < 0 || index >= cache.size())
                            return false;
                        *name = cache[index].name;
                        return true;
                    }, &_cache, _cache.size()))
                _selected.reset();

            ImGui::NewLine();
            drawResourceSelection(&_selected, _cache[_category].id, true);
        }
        ImGui::End();

        if (!_open)
            close();
    }

    void ResourceViewer::_refresh()
    {
        if (!_open)
            return;

        _selected.reset();
        _cache.clear();
        _category = 0;

        auto resmgr = getSubsystem<ResourceManager>();
        if (!resmgr)
            return;

        resmgr->foreach([&](const std::string& fname, BaseResourceHandle res) {
                auto id = res.getResource()->getID();
                if (std::find_if(_cache.begin(), _cache.end(), [id](const CacheEntry& entry) {
                            return entry.id == id;
                        }) == _cache.end())
                {
                    _cache.emplace_back();
                    _cache.back().id = id;
                    getResourceMeta(id, &_cache.back().name, nullptr, nullptr);
                }
                return false;
        });
    }
}


text:
<archimate:Folder
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Handling HTTP status codes on the client side"
    id="5cd8e64a-f789-4c17-aef1-a0f89decf33b"/>