text:
layout: page
title: Resistance
author: Bronte Hebdon
---

## Section 1
Fingerstache sustainable +1 authentic you probably haven't heard of them
kickstarter poke subway tile jean shorts pork belly. Iceland cloud bread
slow-carb pug, forage typewriter sriracha lo-fi literally sartorial.
Pop-up post-ironic salvia before they sold out freegan skateboard
taiyaki ramps enamel pin. Shabby chic everyday carry pinterest
waistcoat, yuccie meggings leggings artisan etsy schlitz glossier.
Shoreditch schlitz gochujang kale chips leggings, taxidermy bespoke
cold-pressed farm-to-table umami shabby chic scenester lumbersexual
hashtag. Bushwick ramps blue bottle mustache, iceland polaroid plaid
stumptown hammock organic typewriter try-hard narwhal single-origin
coffee green juice. Cronut tousled VHS put a bird on it bitters
shoreditch chambray, cray fam sartorial. Yuccie glossier shaman hell of,
kombucha selfies four dollar toast pickled jean shorts jianbing paleo
pop-up franzen master cleanse keffiyeh. Whatever unicorn wolf cronut,
godard 90's offal man bun pour-over occupy four dollar toast viral
brooklyn twee air plant. La croix hoodie meggings gentrify. Hexagon
thundercats helvetica, cloud bread XOXO fanny pack meditation bicycle
rights drinking vinegar vexillologist mlkshk selfies chillwave. Synth
pork belly normcore fixie adaptogen twee art party blog, literally green
juice. Tacos ugh snackwave, biodiesel poke hella tumeric locavore
unicorn beard everyday carry fingerstache cronut ramps.

### subsection added by Alex

Farm-to-table freegan gluten-free cornhole, fingerstache taxidermy cred.
Tumeric raw denim keffiyeh +1 taiyaki. Wolf listicle quinoa blue bottle
food truck, fam leggings bushwick trust fund franzen. Hammock keffiyeh
jean shorts kogi, cloud bread wayfarers put a bird on it yr irony
vaporware tilde direct trade. Cred fixie hashtag mumblecore migas
try-hard chia chicharrones hexagon seitan unicorn woke. Swag brunch
freegan, leggings vice la croix crucifix pour-over. Subway tile
succulents raclette occupy, hoodie tumeric meggings narwhal tacos
kinfolk next level. Health goth chia gochujang single-origin coffee.
Cliche before they sold out cloud bread kombucha vaporware literally.
Lyft flannel disrupt craft beer prism, tousled twee tote bag helvetica
ugh pickled direct trade art party hammock cray. Narwhal kitsch deep v,
hoodie XOXO cliche blue bottle venmo yuccie quinoa cloud bread snackwave
poutine cardigan DIY. Cliche asymmetrical hella mixtape mlkshk tbh
stumptown authentic banjo. Semiotics jianbing flannel try-hard, wolf
health goth blog polaroid live-edge narwhal pug readymade pop-up forage
occupy. Street art banjo adaptogen aesthetic cronut. Heirloom coloring
book vinyl waistcoat pickled, cray austin.

Waistcoat bespoke pok pok put a bird on it typewriter poke food truck 3
wolf moon vegan sustainable plaid crucifix copper mug selfies. Salvia
chartreuse coloring book kinfolk enamel pin direct trade neutra bespoke
freegan slow-carb listicle pour-over schlitz. Meggings artisan adaptogen
8-bit, sriracha ethical skateboard VHS. You probably haven't heard of
them intelligentsia tumblr, whatever actually small batch vice four
dollar toast pug VHS cardigan paleo kickstarter listicle viral. Meh
biodiesel selfies freegan iPhone chambray tote bag kinfolk paleo.
Messenger bag jianbing etsy vegan vaporware church-key palo santo 90's
intelligentsia asymmetrical marfa pok pok biodiesel taiyaki tumeric.
Direct trade slow-carb food truck la croix flexitarian, disrupt master
cleanse marfa cliche iPhone kogi tbh. Neutra put a bird on it sriracha
cardigan lomo pok pok coloring book. Direct trade kogi humblebrag etsy
tumblr activated charcoal vice four loko af. Leggings poke ethical
wayfarers chartreuse small batch.

Distillery kogi tumeric cliche snackwave. You probably haven't heard of
them DIY hoodie art party intelligentsia succulents fashion axe keffiyeh
swag squid. Cred bitters slow-carb vaporware subway tile. Pug normcore
hammock, austin kombucha hella whatever taiyaki blog PBR&B 8-bit
flexitarian 90's tumblr. Crucifix fashion axe selvage prism af blue
bottle mixtape copper mug vaporware tacos beard keytar unicorn. Beard
ugh irony post-ironic. Yr mlkshk cray master cleanse keffiyeh.
Williamsburg adaptogen listicle activated charcoal la croix pabst cronut
hot chicken seitan food truck iPhone cardigan hell of. Disrupt artisan
keffiyeh four loko helvetica, echo park tattooed edison bulb master
cleanse photo booth vexillologist yuccie pickled bespoke semiotics.
Bicycle rights chicharrones vegan kombucha copper mug. Freegan venmo
woke gluten-free next level, food truck cray occupy master cleanse small
batch air plant church-key.

A sentence that needs a note.[^1]

![image caption](IMG_0554.JPG)

image caption

## Section 2.

Umami lumbersexual fixie[^2] blue bottle truffaut PBR&B schlitz meh. Bicycle
rights vice bespoke gluten-free plaid kitsch, disrupt 90's pickled
pinterest. Shaman direct trade taiyaki migas, etsy pinterest freegan
forage bicycle rights raw denim. Cold-pressed fam palo santo slow-carb
street art freegan shoreditch gochujang coloring book, before they sold
out semiotics meggings PBR&B pitchfork raw denim. Try-hard normcore
biodiesel, hoodie polaroid 3 wolf moon meh. Sartorial thundercats synth
glossier, hella sriracha literally. Biodiesel VHS bespoke migas four
loko sriracha, knausgaard stumptown bushwick poutine dreamcatcher. Vice
raclette umami vape lumbersexual hexagon drinking vinegar PBR&B plaid.
Chia snackwave intelligentsia fam organic banh mi. Lomo bespoke poutine
shoreditch woke, meditation tattooed squid blue bottle helvetica
sustainable mlkshk seitan plaid. Schlitz pickled skateboard art party
trust fund tattooed. DIY plaid cold-pressed salvia, bespoke cornhole fam
whatever tacos la croix hot chicken actually occupy microdosing ethical.

Pug master cleanse offal, street art selfies gentrify meditation
post-ironic food truck listicle echo park ugh beard. Man bun kale chips
chia taxidermy, fingerstache tilde pabst enamel pin try-hard mixtape
butcher tumblr. Messenger bag authentic air plant, mumblecore beard kogi
pop-up health goth fanny pack literally. Hell of neutra man bun glossier
hot chicken chillwave. Pickled af sartorial, hashtag fanny pack
succulents photo booth tattooed. Narwhal put a bird on it tousled
tumeric banh mi chartreuse. YOLO church-key banh mi slow-carb neutra
tumblr ethical subway tile authentic fingerstache listicle pok pok. Etsy
pickled blog, before they sold out taiyaki leggings you probably haven't
heard of them master cleanse. Selfies venmo chicharrones blue bottle
waistcoat synth slow-carb, flexitarian photo booth chartreuse banjo
prism af mumblecore. +1 taiyaki trust fund artisan, unicorn viral copper
mug. Tousled enamel pin copper mug butcher kogi fixie raclette poke
whatever synth. Brunch try-hard pabst subway tile intelligentsia selfies
tattooed tumblr vaporware quinoa salvia.

## Section 3.

Prism street art try-hard,[^3] cloud bread kinfolk fixie activated charcoal
truffaut cliche lomo. Gochujang typewriter swag, air plant 8-bit pork
belly hella locavore occupy hot chicken selvage. Godard copper mug
mixtape migas taxidermy hashtag listicle lomo. Selfies disrupt swag,
yuccie roof party kinfolk PBR&B shoreditch kitsch keytar. Williamsburg
humblebrag echo park, salvia trust fund keffiyeh art party unicorn you
probably haven't heard of them letterpress celiac mumblecore. Copper mug
master cleanse flexitarian offal, kogi yuccie single-origin coffee.
Umami thundercats fanny pack vaporware vape. Mlkshk biodiesel portland
heirloom humblebrag pop-up. Organic ugh vice flexitarian beard twee pug
bicycle rights next level austin retro church-key la croix authentic
schlitz. Helvetica wolf echo park listicle kinfolk whatever umami.
Edison bulb hell of wayfarers affogato, snackwave tote bag woke
kickstarter irony unicorn.

Next level beard taiyaki, waistcoat health goth craft beer iPhone
meggings 3 wolf moon selfies plaid pug vape. Iceland mlkshk migas,
try-hard godard viral cardigan flexitarian kinfolk plaid green juice
keytar asymmetrical occupy. Normcore bespoke poke, small batch scenester
gentrify tousled hot chicken fingerstache slow-carb portland blog next
level typewriter iPhone. Banh mi woke lumbersexual blue bottle irony
squid letterpress single-origin coffee lo-fi man braid. Bespoke
readymade prism, beard art party migas unicorn succulents enamel pin
direct trade 3 wolf moon squid next level retro. Brooklyn williamsburg
chambray kogi green juice squid. Neutra paleo kogi palo santo mlkshk
jianbing. Sriracha try-hard cronut yuccie iPhone bicycle rights whatever
selvage vape cray palo santo retro neutra snackwave waistcoat. Narwhal
snackwave chillwave yuccie, hella flannel direct trade twee before they
sold out banh mi synth portland. Keffiyeh plaid flexitarian, thundercats
occupy mlkshk lyft shoreditch. Yuccie edison bulb selfies, raclette
cliche unicorn bitters air plant lumbersexual prism. Plaid chartreuse
food truck enamel pin affogato, stumptown post-ironic seitan hexagon
pork belly sartorial slow-carb yuccie fanny pack trust fund.

Fam crucifix shoreditch seitan chia sustainable. Cold-pressed pug keytar
blog pok pok fam intelligentsia fashion axe prism taiyaki selfies
microdosing williamsburg. Adaptogen humblebrag synth coloring book. Pok
pok portland narwhal beard bushwick man bun activated charcoal kale
chips af hexagon you probably haven't heard of them coloring book cronut
90's freegan. Vexillologist hella iceland portland. Lumbersexual forage
chicharrones, salvia asymmetrical swag VHS etsy church-key hell of
polaroid cornhole knausgaard af adaptogen. Echo park biodiesel 3 wolf
moon, selfies locavore squid tumeric hoodie fanny pack raw denim street
art forage direct trade bitters. Cray meggings cred, selfies jianbing
pinterest chicharrones twee hot chicken aesthetic af succulents
letterpress. Artisan iceland hell of try-hard tofu. Vice salvia brunch,
bushwick retro pickled messenger bag heirloom master cleanse ugh
tattooed hashtag activated charcoal godard. Gochujang master cleanse
cray narwhal.

---

[^1]:my first footnote! And a [link](https://morganlibrary.org/).

[^2]:Footnote 2

[^3]:Footnote 3


text:
package com.github.jrh3k5.membership.renewal.mailer.service.jpa.data;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import com.google.appengine.api.datastore.Key;

@Entity(name = "MembershipDate")
public class JpaMembershipDate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Key id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "MEMBERSHIP_RECORD_ID")
    private JpaMembershipRecord membershipRecord;

    private Date membershipDate;

    public void setMembershipDate(Date membershipDate) {
        this.membershipDate = membershipDate;
    }

    public Date getMembershipDate() {
        return membershipDate;
    }
}

redpajama_set_name: RedPajamaGithub


text:
This data set contains transcribed high-quality audio of Basque sentences
recorded by volunteers. The data set consists of wave files, and a TSV file
(line_index.tsv). The file line_index.tsv contains a anonymized FileID and the
transcription of audio in the file.

The data set has been manually quality checked, but there might still be errors.

Please report any issues in the following issue tracker on GitHub.

  https://github.com/googlei18n/language-resources/issues

See LICENSE file for license information.

Copyright 2018, 2019 Google, Inc.

If you use this data in publications, please cite it as follows:

  @inproceedings{kjartansson-etal-2020-open,
    title = {{Open-Source High Quality Speech Datasets for Basque, Catalan and Galician}},
    author = {Kjartansson, Oddur and Gutkin, Alexander and Butryna, Alena and Demirsahin, Isin and Rivera, Clara},
    booktitle = {Proceedings of the 1st Joint Workshop on Spoken Language Technologies for Under-resourced languages (SLTU) and Collaboration and Computing for Under-Resourced Languages (CCURL)},
    year = {2020},
    pages = {21--27},
    month = may,
    address = {Marseille, France},
    publisher = {European Language Resources association (ELRA)},
    url = {https://www.aclweb.org/anthology/2020.sltu-1.3},
    ISBN = {979-10-95546-35-1},
  }


text:
const path = require('path')

export class Runner {
	app = null
	bootstrapper = null

	constructor(bootstrapper) {
		this.bootstrapper = bootstrapper
	}

	run() {
		const app = this.bootstrapper()
		this.app = app

		return app.start()
	}

	async watch(command, option, restartHandler) {
		// Build the dirs to watch
		const dirs = command
			.option(option)
			.split(/,/)
			.map(dir => {
				if (dir[0] === '/') {
					return dir
				}

				return path.join(process.cwd(), dir)
			})

		// Strip the option from `argv` to avoid infinite loops
		process.argv = process.argv.filter(arg => !arg.startsWith(`--${option}=`))

		// Kick off the watcher
		const Watcher = require('./Runner/Watcher').Watcher
		return new Watcher(this, dirs, restartHandler).watch()
	}
}


text:
package cz.mjanys.iface.converter.generic;

import org.springframework.core.convert.converter.Converter;

import java.util.List;

/**
 * @author Martin Janys
 */
public interface ExtendedConverter<S, T> extends Converter<S, T> {

    T newTarget();

    T convert(S source, T target);

    List<T> convert(Iterable<S> source);

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.tools.ant.taskdefs.optional.depend Class Hierarchy (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.tools.ant.taskdefs.optional.depend

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.tools.ant.util.depend.AbstractAnalyzer (implements org.apache.tools.ant.util.depend.DependencyAnalyzer)

org.apache.tools.ant.taskdefs.optional.depend.AntAnalyzer

org.apache.tools.ant.taskdefs.optional.depend.ClassFile

org.apache.tools.ant.taskdefs.optional.depend.ClassFileUtils

org.apache.tools.ant.taskdefs.optional.depend.DirectoryIterator (implements org.apache.tools.ant.taskdefs.optional.depend.ClassFileIterator)

org.apache.tools.ant.taskdefs.optional.depend.JarFileIterator (implements org.apache.tools.ant.taskdefs.optional.depend.ClassFileIterator)

org.apache.tools.ant.ProjectComponent (implements java.lang.Cloneable)

org.apache.tools.ant.Task

org.apache.tools.ant.taskdefs.MatchingTask (implements org.apache.tools.ant.types.selectors.SelectorContainer)

org.apache.tools.ant.taskdefs.optional.depend.Depend

Interface Hierarchy

org.apache.tools.ant.taskdefs.optional.depend.ClassFileIterator

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
"use strict";
Object.defineProperties(exports, {
  JSCoreDataVersionNumber: {get: function() {
      return JSCoreDataVersionNumber;
    }},
  __esModule: {value: true}
});
var JSCoreDataVersionNumber = {
  JSCoreDataVersionNumber_ANGULAR_1_3: 1,
  JSCoreDataVersionNumber_ANGULAR_2: 1,
  JSCoreDataVersionNumber_NODEJS_10: 1,
  JSCoreDataVersionNumber_NODEJS_11: 1
};
;


text:
// DEPENDENCIES
// ============
var express = require("express")
var http = require("http")
var port = process.env.PORT || 8002
var server = module.exports = express();
var fs = require("fs");
var path = require('path')
var request = require('request')
var passport = require('passport')
var crypto = require('crypto')
var RedditStrategy = require('passport-reddit').Strategy;
var device = require('express-device')

//middleware stuffs
var bodyParser = require('body-parser')
var compress = require('compression')
var cookieParser = require('cookie-parser');
var session = require('express-session')
var MongoStore = require('connect-mongo/es5')(session);

var errorHandler = require('errorhandler')
var methodOverride = require('method-override')
var favicon = require('serve-favicon');
var timestamp = require('../timestamp')

var api = require('./api')
var bots = require('./bots')

// var scope = 'modposts,identity,edit,flair,history,modconfig,modflair,modlog,modposts,modwiki,mysubreddits,privatemessages,read,report,save,submit,subscribe,vote,wikiedit,wikiread'
var scope = 'modposts,identity,edit,flair,history,mysubreddits,privatemessages,read,report,save,submit,subscribe,vote'
var callbackURL = process.env.REDDIT_CALLBACK || "https://js4.red/auth/reddit/callback"
var loginAgainMsg = 'login to reddit please'

//determines if we should serve minified CSS and Javascript to the client
var minifiedStr = process.env.NODE_ENV === 'production' ? '.min' : ''

/*
for your local env run
    export NODE_ENV='dev'
    export REDDIT_KEY = 'your key'
    export REDDIT_SECRET = 'your secret'
    export REDDIT_CALLBACK = 'http://localhost:8002/auth/reddit/callback'
    export SESSION_SECERET = 'make up some random string'

    *put these in ~/.profile so you have them on reboot
*/

var REDDIT_CONSUMER_KEY = process.env.REDDIT_KEY || 'only use these';
var REDDIT_CONSUMER_SECRET = process.env.REDDIT_SECRET || 'to use oauth';

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use(new RedditStrategy({
    clientID: REDDIT_CONSUMER_KEY,
    clientSecret: REDDIT_CONSUMER_SECRET,
    callbackURL: callbackURL
      //callbackURL: "http://redditjs.com/auth/reddit/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    profile.access_token = accessToken //set the recently updated access token
    profile.refresh_token = refreshToken
    profile.tokenExpires = Math.round(+new Date() / 1000) + (60 * 59) //expires one hour from now, with one minute to spare

    process.nextTick(function() {
      return done(null, profile);
    });

  }));

// SERVER CONFIGURATION
// ====================
var oneDay = 86400000;
var sessionExpireTime = 999999999
server.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

server.set('trust proxy', 1)
server.use(compress());
server.use(express.static(__dirname + '../../public', {
  maxAge: oneDay
}));

server.use(favicon(__dirname + '../../public/img/favicon.ico'));

if (process.env.NODE_ENV !== 'production') {

  server.use(errorHandler({
    dumpExceptions: true,
    showStack: true
  }));
}

server.use(cookieParser(process.env.SESSION_SECRET || 'As3242g23g32hs343y346d32fg23f'));

var secureCookies = {}
var mongoOpts = {
  url: 'mongodb://localhost/redditjs-sessions'
}

if (process.env.NODE_ENV === 'production') {

  secureCookies = {
    store: new MongoStore(mongoOpts),
    proxy: true,
    saveUninitialized: false, // don't create session until something stored
    resave: false, //don't save session if unmodified
    //cookie: {
    // maxAge: sessionExpireTime,
    // secure: true
    //},
    secret: process.env.SESSION_SECRET || 'asdasdasdasd32fg23f'
  }

} else {
  //development
  secureCookies = {
    store: new MongoStore(mongoOpts),
    saveUninitialized: false, // don't create session until something stored
    resave: false, //don't save session if unmodified
    //cookie: {
    //  maxAge: sessionExpireTime
    //},
    secret: process.env.SESSION_SECRET || 'asdasdasdasd32fg23f'
  }

}

server.use(session(secureCookies));
server.use(setupLocals)
  //server.use(logger());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
  extended: true
}));
server.use(methodOverride());
server.use(passport.initialize());
server.use(passport.session());
server.use(device.capture());
// server.use(server.router);
server.set('views', path.join(__dirname, 'views'))
server.set('view engine', 'jade')

server.get('/api', ensureAuthenticated, function(req, res) {
  api.get(res, req)
});
server.post('/api', ensureAuthenticated, function(req, res) {
  api.post(res, req)
});

server.get('/apiNonAuth', function(req, res) {
  api.getNonAuth(res, req)
});
server.post('/apiNonAuth', function(req, res) {
  api.postNonAuth(res, req)
});
server.get('/me', ensureAuthenticated, function(req, res) {
  res.json(200, req.user)

});

//requests the <title> tag of any given URL, used for the submit page
server.get('/api/getTitle', function(req, res) {
  api.getTitle(res, req)
});

//Oauth routes
//   GET /auth/reddit
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Reddit authentication will involve
//   redirecting the user to reddit.com.  After authorization, Reddit
//   will redirect the user back to this application at /auth/reddit/callback
//
//   Note that the 'state' option is a Reddit-specific requirement.
server.get('/login', function(req, res, next) {
  req.session.state = crypto.randomBytes(32).toString('hex');

  passport.authenticate('reddit', {
    state: req.session.state,
    //authorizationURL: 'https://ssl.reddit.com/api/v1/authorize.compact',
    scope: scope,
    duration: 'permanent' //permanent or temporary
      //duration: 'temporary' //permanent or temporary
  })(req, res, next);
});

server.get('/logout', function(req, res, next) {
  req.session.destroy();
  req.logout()
  res.send(200, "ok")
});

//reddit Oauth docs: https://github.com/reddit/reddit/wiki/OAuth2
server.get('/auth/reddit/callback', function(req, res, next) {
  // Check for origin via state token

  if (req.query.state == req.session.state) {

    req.session.code = req.query.code
      //request users info at: https://oauth.reddit.com/api/v1/me.json
    passport.authenticate('reddit', {
      successRedirect: '/redirectBack',
      failureRedirect: '/login'
    })(req, res, next);
  } else {

    next(new Error('There was a problem connecting to the reddit server.  Please try again'));
  }
});

server.get("/redirectBack", function(req, res) {
  delete req.session.state;
  res.render('index', {
    user: req.user || false //bootstrap user to client if they are logged in
  })

});

//redirect to non-www
server.all('/*', function(req, res, next) {
  if (req.headers.host.match(/^www/) !== null) {
    res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
  } else {
    next();
  }
})

//handles all other requests to the backbone router
server.get("*", function(req, res) {

  if (req.device.type === 'bot') {
    bots.fetchForBot(res, req)
  } else {
    res.render('index', {
      user: req.user || false, //bootstrap user to client if they are logged in
      customCss: (req.path == '/embed' && req.query.customCss) || false
    })
  }

});

http.createServer(server).listen(port);

console.log('\nWelcome to redditjs.com!, running on port: ' + port + ' in with NODE_ENV: ' + process.env.NODE_ENV);

function ensureAuthenticated(req, res, next) {

  if (req.isAuthenticated()) {

    refreshToken(req, res, function(isExpired) {
      if (isExpired === true) {
        return next();
      } else {
        res.send(419, loginAgainMsg)
      }
    })

  } else {
    res.send(419, loginAgainMsg)

  }

}

function setupLocals(req, res, next) {
  res.locals.timestamp = timestamp.timestamp //saves the last time we ran grunt
  res.locals.minifiedStr = minifiedStr
  next()
}

function refreshToken(req, res, next) {
  var now = Math.round(+new Date() / 1000)

  if (now < req.user.tokenExpires) {
    //console.log('token is NOT expired')
    return next(true)
  } else {
    //console.log('token is expired, lets refresh!', req.user.name)

    var authorization = "Basic " + Buffer("" + REDDIT_CONSUMER_KEY + ":" + REDDIT_CONSUMER_SECRET).toString('base64');

    var params = {
      "client_id": REDDIT_CONSUMER_KEY,
      "client_secret": REDDIT_CONSUMER_SECRET,
      "grant_type": 'refresh_token',
      "refresh_token": req.user.refresh_token,
      'scope': scope,
      'duration': 'permanent',
      "redirect_uri": callbackURL

    }

    var options = {
      'Content-Type': 'application/x-www-form-urlencoded',
      url: 'https://ssl.reddit.com/api/v1/access_token?',
      headers: {
        'User-Agent': 'RedditJS/1.0 by ' + req.user.name,
        'Authorization': authorization
      },
      form: params,
    };

    request.post(options, function(error, response, body) {
      if (error) {

        res.send(419, loginAgainMsg)
        return
      } else if (!error && response.statusCode == 200 || response.statusCode == 304) {
        //set a new access token after getting a new one
        var values = JSON.parse(body)

        values.tokenExpires = (now + values.expires_in) - 60 //give it 60 seconds grace time

        if (values !== 'undefined' && typeof values.access_token !== 'undefined' && values.access_token.length > 3) { //return value cant be trusted
          req.user.tokenExpires = values.tokenExpires
          req.user.access_token = values.access_token

          process.nextTick(function() { //wait for the access token to be in the DB
            return next(true)
          });
        } else {
          res.send(419, loginAgainMsg)
        }

      } else {
        res.send(419, loginAgainMsg)
      }

    });

  }

}


text:
package com.stnetix.ariaddna.desktopgui.controllers;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;

import org.controlsfx.control.ToggleSwitch;
import org.springframework.stereotype.Component;

/**
 * Controller for each cloud settings page
 *
 * @author slonikmak
 */
@Component
public class CloudSettingsController implements IGuiController, Initializable {
    @FXML
    private ToggleSwitch enableBtn;

    @FXML
    private Label enableLable;

    @FXML
    private Label userNameLable;

    @FXML
    private AnchorPane pieChartPane;

    /**
     * Native init method
     * @param location
     * @param resources
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initChart();
    }

    /**
     * Generate pipe chart
     */
    private void initChart() {
        PieChart.Data available = new PieChart.Data("Available", 13);
        PieChart.Data used = new PieChart.Data("Used", 25);
        PieChart.Data empty = new PieChart.Data("Empty", 10);

        ObservableList<PieChart.Data> pieChartData =
                FXCollections.observableArrayList(available, used, empty);
        final PieChart chart = new PieChart(pieChartData);
        chart.setTitle("");
        chart.setPrefSize(350, 350);
        chart.setLegendVisible(false);
        chart.setStyle("-fx-background-color: none");
        pieChartPane.getChildren().add(chart);

        available.getNode().setStyle("-fx-background-color: #55c4fe");
        used.getNode().setStyle("-fx-background-color: #008287");
        empty.getNode().setStyle("-fx-background-color: #219297");

    }
}


text:
<!-- BEGINNING OF PRE-COMMIT-BLUEPRINT DOCS HOOK:TITLE -->
# Cloud Logging Log Bucket Export blueprint

<!-- END OF PRE-COMMIT-BLUEPRINT DOCS HOOK:TITLE -->
<!-- BEGINNING OF PRE-COMMIT-BLUEPRINT DOCS HOOK:BODY -->
A log export on an organization that sinks to Cloud Logging Log Bucket

## Setters

|      Name       |       Value       | Type | Count |
|-----------------|-------------------|------|-------|
| bucket-locked   | false             | bool |     1 |
| filter          |                   | str  |     0 |
| location        | global            | str  |     2 |
| log-bucket-name | my-log-k8s-bucket | str  |     3 |
| namespace       | my-namespace      | str  |     6 |
| org-id          |      123456789012 | str  |     4 |
| project-id      | my-project-id     | str  |     6 |
| retention-days  |                30 | int  |     1 |

## Sub-packages

This package has no sub-packages.

## Resources

|    File     |                 APIVersion                 |       Kind       |            Name            |  Namespace   |
|-------------|--------------------------------------------|------------------|----------------------------|--------------|
| export.yaml | serviceusage.cnrm.cloud.google.com/v1beta1 | Service          | my-project-id-logbucket    | my-namespace |
| export.yaml | logging.cnrm.cloud.google.com/v1beta1      | LoggingLogSink   | 123456789012-logbucketsink | my-namespace |
| export.yaml | logging.cnrm.cloud.google.com/v1beta1      | LoggingLogBucket | my-log-k8s-bucket          | my-namespace |
| iam.yaml    | iam.cnrm.cloud.google.com/v1beta1          | IAMPolicyMember  | log-bkt-project-iam-policy | logging      |

## Resource References

- [IAMPolicyMember](https://cloud.google.com/config-connector/docs/reference/resource-docs/iam/iampolicymember)
- [LoggingLogBucket](https://cloud.google.com/config-connector/docs/reference/resource-docs/logging/logginglogbucket)
- [LoggingLogSink](https://cloud.google.com/config-connector/docs/reference/resource-docs/logging/logginglogsink)
- [Service](https://cloud.google.com/config-connector/docs/reference/resource-docs/serviceusage/service)

## Usage

1.  Clone the package:
    ```shell
    kpt pkg get https://github.com/GoogleCloudPlatform/blueprints.git/catalog/log-export/org/logbucket-export@${VERSION}
    ```
    Replace `${VERSION}` with the desired repo branch or tag
    (for example, `main`).

1.  Move into the local package:
    ```shell
    cd "./logbucket-export/"
    ```

1.  Edit the function config file(s):
    - setters.yaml

1.  Execute the function pipeline
    ```shell
    kpt fn render
    ```

1.  Initialize the resource inventory
    ```shell
    kpt live init --namespace ${NAMESPACE}"
    ```
    Replace `${NAMESPACE}` with the namespace in which to manage
    the inventory ResourceGroup (for example, `config-control`).

1.  Apply the package resources to your cluster
    ```shell
    kpt live apply
    ```

1.  Wait for the resources to be ready
    ```shell
    kpt live status --output table --poll-until current
    ```

<!-- END OF PRE-COMMIT-BLUEPRINT DOCS HOOK:BODY -->


text:
define([
	'knockout',
	'text!./negative-control-outcome-cohort-settings-editor.html',
	'components/Component',
	'utils/CommonUtils',
	'../../const',
	'databindings',
], function (
	ko,
	view,
	Component,
	commonUtils,
	constants,
) {
	class NegativeControlOutcomeCohortSettingsEditor extends Component {
		constructor(params) {
      super(params);
			this.isEditPermitted = params.isEditPermitted;

			this.negativeControlCohortSettings = params.negativeControlCohortSettings;
            this.options = constants.options;
		}
	}

	return commonUtils.build('nc-outcome-cohort-settings-editor', NegativeControlOutcomeCohortSettingsEditor, view);
});


text:
    @foreach($users as $user)
        url() }}" class="avatar thumb-xs"
           data-controller="tooltip"
           data-action="mouseover->tooltip#mouseOver"
           data-toggle="tooltip"
           data-placement="top"
           title="{{ $user->title() }}">
            image() }}"
                 class="avatar-img rounded-circle b bg-light"
                 alt="{{ $user->title() }}">

    @endforeach


text:
<?php

use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\YiiAsset;
use yii\widgets\DetailView;
use modules\user\AnimateAsset;

/* @var $this yii\web\View */
/* @var $model modules\user\models\AuthItem */
/* @var $context modules\user\controllers\AuthItemController */

$context = $this->context;
$labels = $context->labels();
$this->title = $model->name . ' | ' . Yii::t('user', 'View ' . $labels['Item']);
$this->params['breadcrumbs'][] = ['label' => Yii::t('user', $labels['Items']), 'url' => ['index']];
$this->params['breadcrumbs'][] = $model->name;
$this->params['page_title'] = $labels['Items'];
$this->params['page_type'] = 'view';

AnimateAsset::register($this);
YiiAsset::register($this);
$opts = Json::htmlEncode([
    'items' => $model->getItems(),
]);
$this->registerJs("var _opts = {$opts};");
$this->registerJs($this->render('_script.js'));
$animateIcon = ' ';
?>

        <?=Html::a(Yii::t('user', 'Update'), ['update', 'id' => $model->name], ['class' => 'btn btn-primary']);?>
        <?=Html::a(Yii::t('user', 'Delete'), ['delete', 'id' => $model->name], [
            'class' => 'btn btn-danger',
            'data-confirm' => Yii::t('user', 'Are you sure to delete this item?'),
            'data-method' => 'post',
        ]);?>
        <?=Html::a(Yii::t('user', 'Create'), ['create'], ['class' => 'btn btn-success']);?>

            <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"></button>

                <?=
                DetailView::widget([
                    'model' => $model,
                    'attributes' => [
                        'name',
                        'description:ntext',
                        'ruleName',
                        'data:ntext',
                    ],
                    'template' => '
{label}	{value}
',
                ]);
                ?>

                <input class="form-control search" data-target="available" placeholder="<?=Yii::t('user', 'Search for available');?>">
                <select multiple size="20" class="form-control list" data-target="available"></select>

                <?=Html::a('>>' . $animateIcon, ['assign', 'id' => $model->name], [
                    'class' => 'btn btn-success btn-assign',
                    'data-target' => 'available',
                    'title' => Yii::t('user', 'Assign'),
                ]);?>

                <?=Html::a('<<' . $animateIcon, ['remove', 'id' => $model->name], [
                    'class' => 'btn btn-danger btn-assign',
                    'data-target' => 'assigned',
                    'title' => Yii::t('user', 'Remove'),
                ]);?>

                <input class="form-control search" data-target="assigned" placeholder="<?=Yii::t('user', 'Search for assigned');?>">
                <select multiple size="20" class="form-control list" data-target="assigned"></select>


text:
using System;

namespace Poker
{
    public class Card : ICard
    {
        public CardFace Face { get; private set; }
        public CardSuit Suit { get; private set; }

        public Card(CardFace face, CardSuit suit)
        {
            this.Face = face;
            this.Suit = suit;
        }

        public override string ToString()
        {
            string msg = this.Face.ToString() + this.Suit.ToString();
            return msg;
        }
    }
}


text:
package org.apache.maven.plugins.resources.it;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_EXTENSIONS_ITERATORS_CIRCULAR_ITERATOR_HPP
#define BOOST_GEOMETRY_EXTENSIONS_ITERATORS_CIRCULAR_ITERATOR_HPP

#include <boost/iterator.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/iterator/iterator_categories.hpp>

#include <boost/geometry/iterators/base.hpp>

namespace boost { namespace geometry
{

/*!
    \brief Iterator which goes circular through a range, starting at a point, ending at that point
    \tparam Iterator iterator on which this class is based on
    \ingroup iterators
*/
template <typename Iterator>
struct circular_iterator :
    public detail::iterators::iterator_base
    <
        circular_iterator<Iterator>,
        Iterator
    >
{
    friend class boost::iterator_core_access;

    explicit inline circular_iterator(Iterator begin, Iterator end, Iterator start)
        : m_begin(begin)
        , m_end(end)
        , m_start(start)
    {
        this->base_reference() = start;
    }

    // Constructor to indicate the end of a range, to enable e.g. std::copy
    explicit inline circular_iterator(Iterator end)
        : m_begin(end)
        , m_end(end)
        , m_start(end)
    {
        this->base_reference() = end;
    }

    /// Navigate to a certain position, should be in [start .. end], it at end
    /// it will circle again.
    inline void moveto(Iterator it)
    {
        this->base_reference() = it;
        check_end();
    }

private:

    inline void increment()
    {
        if (this->base() != m_end)
        {
            (this->base_reference())++;
            check_end();
        }
    }
    inline void decrement()
    {
        if (this->base() != m_end)
        {
            // If at begin, go back to end (assumed this is possible...)
            if (this->base() == m_begin)
            {
                this->base_reference() = this->m_end;
            }

            // Decrement
            (this->base_reference())--;

            // If really back at start, go to end == end of iteration
            if (this->base() == m_start)
            {
                this->base_reference() = this->m_end;
            }
        }
    }

    inline void check_end()
    {
        if (this->base() == this->m_end)
        {
            this->base_reference() = this->m_begin;
        }

        if (this->base() == m_start)
        {
            this->base_reference() = this->m_end;
        }
    }

    Iterator m_begin;
    Iterator m_end;
    Iterator m_start;
};

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_EXTENSIONS_ITERATORS_CIRCULAR_ITERATOR_HPP


text:
import React, { Component, createRef } from 'react';
import classnames from 'classnames';
import { observer } from 'mobx-react';
import StakingNavigation from '../navigation/StakingNavigation';
import styles from './StakingWithNavigation.scss';

type Props = {
  children?: React.ReactNode;
  activeItem: string;
  showInfoTab: boolean;
  onNavItemClick: (...args: Array<any>) => any;
  isActiveNavItem: (...args: Array<any>) => any;
};
type ContextValue = {
  scrollElementRef: React.RefObject<HTMLDivElement> | null | undefined;
};
export const StakingPageScrollContext = React.createContext<ContextValue>({
  scrollElementRef: null,
});

@observer
class StakingWithNavigation extends Component<Props> {
  stakingPageScrollContext = { scrollElementRef: createRef<HTMLDivElement>() };

  render() {
    const {
      children,
      onNavItemClick,
      activeItem,
      isActiveNavItem,
      showInfoTab,
    } = this.props;
    const componentStyles = classnames([styles.component, styles[activeItem]]);
    return (
      <StakingPageScrollContext.Provider value={this.stakingPageScrollContext}>

            <StakingNavigation
              isActiveNavItem={isActiveNavItem}
              onNavItemClick={onNavItemClick}
              activeItem={activeItem}
              showInfoTab={showInfoTab}
            />

            {children}

      </StakingPageScrollContext.Provider>
    );
  }
}

export default StakingWithNavigation;


text:
var logging = true; //enables logging in the broswers JS console.

function getStatsPageURI_() {
    //gets the URI of the current page, turns it into the stats page URL returns it
    //we are using the url an element in the page header because the actual pageurl doesn't change after a redirect page
    var url = document.querySelectorAll('[rel="canonical"]')[0].getAttribute('href');
    var article = url.slice(url.lastIndexOf("/") + 1, url.length);
    //Start language retrieval. Code is pretty inneficient.
    //Works by turning string back into url so we can use href methods to manupulate it
    var hrefe = document.createElement("a");
    hrefe.href = url;
    var host = hrefe.hostname;
    var lang = host.substr(0, host.indexOf('.'));
    if(logging){
    console.log(lang);
    console.log(lang.constructor.name);
    }

    var statsuri = "https://tools.wmflabs.org/xtools/articleinfo/index.php?article=" + article + "&lang="+ lang +"&wiki=wikipedia";
    if (logging) {
        console.log("statsuri: "+statsuri);
    }
    return statsuri;
}

function extractStats_(div) {
    //Currently unused. May be used to extract stats from the div we pass around
    var tables = div.getElementsByType('table');
    putbox(document, tables, "warning");
}

function putbox(document, score, color) {
    //puts a box on the page and styles it.
    var box = document.getElementById('mw-content-text');
    var table = document.createElement("table");
    var newrow = document.createElement('tr');
    var th = document.createElement('th');
    newrow.className = color;
    table.className = color + " infobox vcard ";
    table.style.width = "22em";
    table.id = color;
    th.colspan = "2";
    th.className = color + " n";
    th.style.textAlign = "center";
    th.style.fontSize = "125%";
    th.appendChild(score.firstChild);
    newrow.appendChild(th);
    table.appendChild(newrow);
    box.insertBefore(table, box.firstChild);
}

// this is our mainloop, we need to refactor for better structure
if (!document.getElementById("ca-nstab-main") || (document.getElementsByClassName("action-view").length==0) || (document.getElementsByClassName("ns-subject").length==0)){
    //We're checking to see if we are on a wikipedia article page.
    if(logging){
    console.log("nothing to do");
    }
}
else{
    if(logging){
console.log(document.getElementsByClassName("action-view"));
}
//We're opening a connection to background.js
var port = chrome.runtime.connect({
    name: "uriexchange"
});
//send the URI generated by getStatsPageURI_()
port.postMessage({
    uri: getStatsPageURI_()
});
if (logging) {
console.log("port name: " + port.name);
}
port.onMessage.addListener(function (msg) { //wait for background.js to hand us back a score (or something)
    xml = msg.table;
    var html =new DOMParser().parseFromString(xml, "text/html");
    if (logging) {
        console.log("msg: " + msg);
        console.log("msg.table: " + msg.table);
        //console.log("xml: " +xml);
        //console.log("html:"+html);
    }
    putbox(document, html, "success");
});

function insertCSS() {
    //inserts our cutdown css styles to color the scoreBox.
    var css = document.createElement("link");
    var bsurl = chrome.extension.getURL("bootstrap.css");
    css.href = bsurl;
    css.rel = "stylesheet";
    document.head.appendChild(css);
}
insertCSS();

}


text:
set -o errexit

# quit on unbound symbols:
set -o nounset

DIR=`dirname "$0"`

cd $DIR
export FLASK_APP=app.py

## Load fixtures

# create users. Use the following emails and passwords to login.
flask users create info@inveniosoftware.org -a --password 123456
flask users create reader@inveniosoftware.org -a --password 123456
flask users create editor@inveniosoftware.org -a --password 123456
flask users create admin@inveniosoftware.org -a --password 123456

# create admin role and add the role to a user
flask roles create admin
flask roles add info@inveniosoftware.org admin
flask roles add admin@inveniosoftware.org admin

# assign some allowed actions to this users
flask access allow open user editor@inveniosoftware.org
flask access deny open user info@inveniosoftware.org
flask access allow read user reader@inveniosoftware.org
flask access allow open role admin
flask access allow read role admin
flask access allow admin-access role admin
flask access allow superuser-access role admin


text:
<?php

class Mage_Index_Block_Adminhtml_Process_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * Process model
     *
     * @var Mage_Index_Model_Process
     */
    protected $_processModel;

    /**
     * Mass-action block
     *
     * @var string
     */
    protected $_massactionBlockName = 'index/adminhtml_process_grid_massaction';

    /**
     * Class constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->_processModel = Mage::getSingleton('index/process');
        $this->setId('indexer_processes_grid');
        $this->_filterVisibility = false;
        $this->_pagerVisibility  = false;
    }

    /**
     * Prepare grid collection
     *
     * @return Mage_Index_Block_Adminhtml_Process_Grid
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('index/process_collection');
        $this->setCollection($collection);
        parent::_prepareCollection();

        return $this;
    }

    /**
     * Add name and description to collection elements
     *
     * @return Mage_Index_Block_Adminhtml_Process_Grid
     */
    protected function _afterLoadCollection()
    {
        /** @var $item Mage_Index_Model_Process */
        foreach ($this->_collection as $key => $item) {
            if (!$item->getIndexer()->isVisible()) {
                $this->_collection->removeItemByKey($key);
                continue;
            }
            $item->setName($item->getIndexer()->getName());
            $item->setDescription($item->getIndexer()->getDescription());
            $item->setUpdateRequired($item->getUnprocessedEventsCollection()->count() > 0 ? 1 : 0);
            if ($item->isLocked()) {
                $item->setStatus(Mage_Index_Model_Process::STATUS_RUNNING);
            }
        }
        return $this;
    }

    /**
     * Prepare grid columns
     *
     * @return Mage_Index_Block_Adminhtml_Process_Grid
     */
    protected function _prepareColumns()
    {
        $baseUrl = $this->getUrl();
        $this->addColumn('indexer_code', array(
            'header'    => Mage::helper('index')->__('Index'),
            'width'     => '180',
            'align'     => 'left',
            'index'     => 'name',
            'sortable'  => false,
        ));

        $this->addColumn('description', array(
            'header'    => Mage::helper('index')->__('Description'),
            'align'     => 'left',
            'index'     => 'description',
            'sortable'  => false,
        ));

        $this->addColumn('mode', array(
            'header'    => Mage::helper('index')->__('Mode'),
            'width'     => '150',
            'align'     => 'left',
            'index'     => 'mode',
            'type'      => 'options',
            'options'   => $this->_processModel->getModesOptions()
        ));

        $this->addColumn('status', array(
            'header'    => Mage::helper('index')->__('Status'),
            'width'     => '120',
            'align'     => 'left',
            'index'     => 'status',
            'type'      => 'options',
            'options'   => $this->_processModel->getStatusesOptions(),
            'frame_callback' => array($this, 'decorateStatus')
        ));

        $this->addColumn('update_required', array(
            'header'    => Mage::helper('index')->__('Update Required'),
            'sortable'  => false,
            'width'     => '120',
            'align'     => 'left',
            'index'     => 'update_required',
            'type'      => 'options',
            'options'   => $this->_processModel->getUpdateRequiredOptions(),
            'frame_callback' => array($this, 'decorateUpdateRequired')
        ));

        $this->addColumn('ended_at', array(
            'header'    => Mage::helper('index')->__('Updated At'),
            'type'      => 'datetime',
            'width'     => '180',
            'align'     => 'left',
            'index'     => 'ended_at',
            'frame_callback' => array($this, 'decorateDate')
        ));

        $this->addColumn('action',
            array(
                'header'    =>  Mage::helper('index')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('index')->__('Reindex Data'),
                        'url'       => array('base'=> '*/*/reindexProcess'),
                        'field'     => 'process'
                    ),
                ),
                'filter'    => false,
                'sortable'  => false,
                'is_system' => true,
        ));

        parent::_prepareColumns();

        return $this;
    }

    /**
     * Decorate status column values
     *
     * @param string $value
     * @param Mage_Index_Model_Process $row
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     * @param bool $isExport
     *
     * @return string
     */
    public function decorateStatus($value, $row, $column, $isExport)
    {
        $class = '';
        switch ($row->getStatus()) {
            case Mage_Index_Model_Process::STATUS_PENDING :
                $class = 'grid-severity-notice';
                break;
            case Mage_Index_Model_Process::STATUS_RUNNING :
                $class = 'grid-severity-major';
                break;
            case Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX :
                $class = 'grid-severity-critical';
                break;
        }
        return ''.$value.'';
    }

    /**
     * Decorate "Update Required" column values
     *
     * @param string $value
     * @param Mage_Index_Model_Process $row
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     * @param bool $isExport
     *
     * @return string
     */
    public function decorateUpdateRequired($value, $row, $column, $isExport)
    {
        $class = '';
        switch ($row->getUpdateRequired()) {
            case 0:
                $class = 'grid-severity-notice';
                break;
            case 1:
                $class = 'grid-severity-critical';
                break;
        }
        return ''.$value.'';
    }

    /**
     * Decorate last run date coumn
     *
     * @param string $value
     * @param Mage_Index_Model_Process $row
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     * @param bool $isExport
     *
     * @return string
     */
    public function decorateDate($value, $row, $column, $isExport)
    {
        if(!$value) {
            return $this->__('Never');
        }
        return $value;
    }

    /**
     * Get row edit url
     *
     * @param Mage_Index_Model_Process $row
     *
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('process' => $row->getId()));
    }

    /**
     * Add mass-actions to grid
     *
     * @return Mage_Index_Block_Adminhtml_Process_Grid
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('process_id');
        $this->getMassactionBlock()->setFormFieldName('process');

        $modeOptions = Mage::getModel('index/process')->getModesOptions();

        $this->getMassactionBlock()->addItem('change_mode', array(
            'label'         => Mage::helper('index')->__('Change Index Mode'),
            'url'           => $this->getUrl('*/*/massChangeMode'),
            'additional'    => array(
                'mode'      => array(
                    'name'      => 'index_mode',
                    'type'      => 'select',
                    'class'     => 'required-entry',
                    'label'     => Mage::helper('index')->__('Index mode'),
                    'values'    => $modeOptions
                )
            )
        ));

        $this->getMassactionBlock()->addItem('reindex', array(
            'label'    => Mage::helper('index')->__('Reindex Data'),
            'url'      => $this->getUrl('*/*/massReindex'),
            'selected' => true,
        ));

        return $this;
    }
}


text:
This game was developed to experiment with Phaser, desktop and mobile HTML5 game framework.

Based on the Phaser tutorial.


text:
<!DOCTYPE html>

    <title>NominalElementDictionary Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          PenguinStructures Docs

         (94% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

      PenguinStructures Reference

      NominalElementDictionary Structure Reference

            Hierarchical Collections

                HierarchicalCollection

                MutableHierarchicalCollection

                Deque

                – Cursor

                DoubleEndedBuffer

                DoubleEndedAllocationPolicy

                HierarchicalArray

                – Cursor

                LeafArray

            Other Classes

                AnyArrayStorage

            Other Enumerations

                Either

            Other Extensions

                Array

                Array

                ArrayPriorityQueueIndexer

                BinaryInteger

                Collection

                Collection

                Dictionary

                EitherCollection

                EitherSequence

                – Iterator

                Empty

                Int

                Int32

                Int64

                KeyPath

                MutableCollection

                MutableCollection

                RandomAccessCollection

                RandomAccessCollection

                Sequence

                Sequence

                String

                UInt32

                UInt64

                UnsignedInteger

            Other Protocols

                DefaultInitializable

                FactoryInitializable

                FixedSizeArray

                IdIndexable

                IndexProtocol

                KeyPathProtocol

                Lens

                PriorityQueueIndexer

                Queue

                SourceInitializableCollection

                TupleProtocol

            Other Structures

                AnyArrayBuffer

                AnyValue

                Array0

                ArrayBuffer

                ArrayN

                ArrayStorage

                CollectionPriorityQueueIndexer

                Concatenation

                – Index

                Empty

                GenericMaxPriorityQueue

                GenericPriorityQueue

                InsertionOrderedDictionary

                KeyValuePair

                – ProjectKey

                – ProjectValue

                NominalElementDictionary

                – Iterator

                NonIndexingPriorityQueueIndexer

                PCGRandomNumberGenerator

                PriorityQueueElement

                Projections

                – Iterator

                Tuple

                Type

                TypeID

            Other Type Aliases

                AnyElementArrayBuffer

                Array1

                Array2

                Array3

                Array4

                Array5

                Array6

                Array7

                ArrayPriorityQueueIndexer

                EitherCollection

                EitherSequence

                KeyValueTuple

                MaxPriorityQueue

                PriorityQueue

                ReprioritizableMaxPriorityQueue

                ReprioritizablePriorityQueue

                SimpleMaxPriorityQueue

                SimplePriorityQueue

                Tuple0

                Tuple1

                Tuple2

                Tuple3

                Tuple4

                Tuple5

                Tuple6

                Tuple7

NominalElementDictionary

public struct NominalElementDictionary<Key, Value> where Key : Hashable

extension NominalElementDictionary : Collection

extension NominalElementDictionary : Sequence

extension NominalElementDictionary : CustomReflectable

extension NominalElementDictionary
  : CustomStringConvertible, CustomDebugStringConvertible

extension NominalElementDictionary : Hashable where Value : Hashable

extension NominalElementDictionary : Equatable where Value : Equatable

extension NominalElementDictionary
  : Decodable where Key : Decodable, Value : Decodable

extension NominalElementDictionary : Encodable
  where Key : Encodable, Value : Encodable

A Dictionary with a nominal Element type, that can conform to things.

                Show on GitHub

                    Base

The underlying Swift dictionary.

Declaration

Swift

public typealias Base = [Key : Value]

                        Show on GitHub

                    Keys

A view of a dictionary’s keys.

Declaration

Swift

public typealias Keys = Base.Keys

                        Show on GitHub

                    Values

A view of a dictionary’s values.

Declaration

Swift

public typealias Values = Base.Values

                        Show on GitHub

                    Index

The position of a key-value pair in a dictionary.

Declaration

Swift

public typealias Index = Base.Index

                        Show on GitHub

                    base

The underlying Swift Dictionary

Declaration

Swift

public var base: Base

                        Show on GitHub

                    init(_:<wbr>)

Creates an instance equivalent to base.

Declaration

Swift

public init(_ base: Base)

                        Show on GitHub

                    Element

The element type of a dictionary, just like a tuple containing an
individual key-value pair, but nominal.

Declaration

Swift

public typealias Element = KeyValuePair<Key, Value>

                        Show on GitHub

                    init()

Creates an empty dictionary.

Declaration

Swift

public init()

                        Show on GitHub

                    init(minimumCapacity:<wbr>)

Creates an empty dictionary with preallocated space for at least the
specified number of elements.

Declaration

Swift

public init(minimumCapacity: Int)

                        Show on GitHub

                    init(uniqueKeysWithValues:<wbr>)

Creates a new dictionary from the key-value pairs in the given sequence.

Declaration

Swift

public init<S>(
  uniqueKeysWithValues keysAndValues: S)
  where S : Sequence, S.Element == Element

                        Show on GitHub

                    init(_:<wbr>uniquingKeysWith:<wbr>)

Creates a new dictionary from the key-value pairs in the given sequence,
using a combining closure to determine the value for any duplicate keys.

Declaration

Swift

public init<S>(
  _ keysAndValues: S,
  uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S : Sequence, S.Element == Element

                        Show on GitHub

                    init(grouping:<wbr>by:<wbr>)

Creates a new dictionary whose keys are the groupings returned by the
given closure and whose values are arrays of the elements that returned
each key.

Declaration

Swift

public init<S>(
  grouping values: S, by keyForValue: (S.Element) throws -> Key)
  rethrows where Value == [S.Element], S : Sequence

                        Show on GitHub

                    filter(_:<wbr>)

Returns a new dictionary containing the key-value pairs of the dictionary
that satisfy the given predicate.

Declaration

Swift

@available(swift 4.0)
public func filter(
  _ isIncluded: (Element) throws -> Bool
) rethrows -> NominalElementDictionary

                        Show on GitHub

                    subscript(_:<wbr>)

Accesses the value associated with the given key, producing nil when the value of a key not
in the dictionary is read, and erasing the key if nil is written.

Declaration

Swift

public subscript(key: Key) -> Value? { get set }

                        Show on GitHub

                    subscript(_:<wbr>default:<wbr>)

Accesses the value for key, or defaultValue no such key exists in the dictionary, on write
first inserting key with value defaultValue if it does not exist in the dictionary.

Declaration

Swift

public subscript(
  key: Key, default defaultValue: @autoclosure () -> Value
) -> Value

                        Show on GitHub

                    mapValues(_:<wbr>)

Returns a new dictionary containing the keys of this dictionary with the
values transformed by the given closure.

Declaration

Swift

public func mapValues<T>(
  _ transform: (Value) throws -> T
) rethrows -> NominalElementDictionary<Key, T>

                        Show on GitHub

                    compactMapValues(_:<wbr>)

Returns a new dictionary containing only the key-value pairs that have
non-nil values as the result of transformation by the given closure.

Declaration

Swift

public func compactMapValues<T>(
  _ transform: (Value) throws -> T?
) rethrows -> [Key : T]

                        Show on GitHub

                    updateValue(_:<wbr>forKey:<wbr>)

Updates the value stored in the dictionary for the given key and returns the old value, or
adds a new key-value pair if the key does not exist and returns nil .

Declaration

Swift

public mutating func updateValue(
  _ value: Value, forKey key: Key
) -> Value?

                        Show on GitHub

                    merge(_:<wbr>uniquingKeysWith:<wbr>)

Merges the key-value pairs in the given sequence into the dictionary,
using a combining closure to determine the value for any duplicate keys.

Declaration

Swift

public mutating func merge<S>(
  _ other: S,
  uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S : Sequence, S.Element == Element

                        Show on GitHub

                    merge(_:<wbr>uniquingKeysWith:<wbr>)

Merges the given dictionary into this dictionary, using a combining
closure to determine the value for any duplicate keys.

Declaration

Swift

public mutating func merge(
  _ other: Self,
  uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows

                        Show on GitHub

                    merging(_:<wbr>uniquingKeysWith:<wbr>)

Creates a dictionary by merging key-value pairs in a sequence into the
dictionary, using a combining closure to determine the value for
duplicate keys.

Declaration

Swift

public func merging<S>(
  _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> Self where S : Sequence, S.Element == Element

                        Show on GitHub

                    merging(_:<wbr>uniquingKeysWith:<wbr>)

Creates a dictionary by merging the given dictionary into this
dictionary, using a combining closure to determine the value for
duplicate keys.

Declaration

Swift

public func merging(
  _ other: Self, uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> Self

                        Show on GitHub

                    remove(at:<wbr>)

Removes and returns the key-value pair at the specified index.

Declaration

Swift

public mutating func remove(at index: Index) -> Element

                        Show on GitHub

                    removeValue(forKey:<wbr>)

Removes the given key and its associated value from the dictionary.

Declaration

Swift

public mutating func removeValue(forKey key: Key) -> Value?

                        Show on GitHub

                    removeAll(keepingCapacity:<wbr>)

Removes all key-value pairs from the dictionary.

Declaration

Swift

public mutating func removeAll(
  keepingCapacity keepCapacity: Bool = false
)

                        Show on GitHub

                    keys

A collection containing just the keys of the dictionary.

Declaration

Swift

@available(swift 4.0)
public var keys: Keys { get }

                        Show on GitHub

                    values

A collection containing just the values of the dictionary.

Declaration

Swift

@available(swift 4.0)
public var values: Values { get set }

                        Show on GitHub

                    Iterator

An iterator over the members of a NominalElementDictionary<Key, Value>.

                        See more

Declaration

Swift

public struct Iterator : IteratorProtocol

                        Show on GitHub

                    popFirst()

Removes and returns the first key-value pair of the dictionary if the
dictionary isn’t empty.

Declaration

Swift

public mutating func popFirst() -> Element?

                        Show on GitHub

                    capacity

The total number of key-value pairs that the dictionary can contain without
allocating new storage.

Declaration

Swift

public var capacity: Int { get }

                        Show on GitHub

                    reserveCapacity(_:<wbr>)

Reserves enough space to store the specified number of key-value pairs.

Declaration

Swift

public mutating func reserveCapacity(_ minimumCapacity: Int)

                        Show on GitHub

                    startIndex

The position of the first element in a nonempty dictionary.

Declaration

Swift

public var startIndex: Index { get }

                        Show on GitHub

                    endIndex

The dictionary’s “past the end” position—that is, the position one
greater than the last valid subscript argument.

Declaration

Swift

public var endIndex: Index { get }

                        Show on GitHub

                    index(after:<wbr>)

Returns the position immediately after the given index.

Declaration

Swift

public func index(after i: Index) -> Index

                        Show on GitHub

                    formIndex(after:<wbr>)

Replaces the given index with its successor.

Declaration

Swift

public func formIndex(after i: inout Index)

                        Show on GitHub

                    index(forKey:<wbr>)

Returns the index for the given key.

Declaration

Swift

public func index(forKey key: Key) -> Index?

                        Show on GitHub

                    subscript(_:<wbr>)

Accesses the key-value pair at the specified position.

Declaration

Swift

public subscript(position: Index) -> Element { get }

                        Show on GitHub

                    count

The number of key-value pairs in the dictionary.

Declaration

Swift

public var count: Int { get }

                        Show on GitHub

                    isEmpty

A Boolean value that indicates whether the dictionary is empty.

Declaration

Swift

public var isEmpty: Bool { get }

                        Show on GitHub

                    makeIterator()

Returns an iterator over the dictionary’s key-value pairs.

Declaration

Swift

public func makeIterator() -> Iterator

                        Show on GitHub

                    customMirror

A mirror that reflects the dictionary.

Declaration

Swift

public var customMirror: Mirror { get }

                        Show on GitHub

                    description

A string that represents the contents of the dictionary.

Declaration

Swift

public var description: String { get }

                        Show on GitHub

                    debugDescription

A string that represents the contents of the dictionary, suitable for
debugging.

Declaration

Swift

public var debugDescription: String { get }

                        Show on GitHub

                <a name="//apple_ref/swift/Section/Available where `Key` : `Decodable`, `Value` : `Decodable`" class="dashAnchor">

Available where Key : Decodable, Value : Decodable

                    init(from:<wbr>)

Creates a new dictionary by decoding from the given decoder.

Declaration

Swift

public init(from decoder: Decoder) throws

                        Show on GitHub

                <a name="//apple_ref/swift/Section/Available where `Key` : `Encodable`, `Value` : `Encodable`" class="dashAnchor">

Available where Key : Encodable, Value : Encodable

                    encode(to:<wbr>)

Encodes the contents of this dictionary into the given encoder.

Declaration

Swift

public func encode(to encoder: Encoder) throws

                        Show on GitHub

© 2020 Brennan Saeta saeta@google.com. All rights reserved. (Last updated: 2020-12-07)

Generated by jazzy ♪♫ v0.13.6, a Realm project.


text:
/*
 * Created on Feb 11, 2005
 */
package bp.pecan.dimensions;

import bp.common.fp.Functions;

/**
 * @author benedictpaten
 */
public class SequenceTest
                         extends AbstractDimensionTest {
    final static int length = 100;

    /**
     * Constructor for SequenceTest.
     *
     * @param arg0
     */
    public SequenceTest(final String arg0) {
        super(arg0);
    }

    public void testTinySequence() {
        final int length = 1;
        final Dimension d = DimensionTools.getSequenceOfFunction(Functions.
                rCurry(this.getFunction(), new Double(0)), length);
        this.testComplete(d, this.getFunction(), length, 1);
    }

    public void testZeroLengthSequence() {
        final int length = 0;
        final Dimension d = DimensionTools.getSequenceOfFunction(Functions.
                rCurry(this.getFunction(), new Double(0)), length);
        this.testComplete(d, this.getFunction(), length, 1);
    }

    /* (non-Javadoc)
     * @see bp.pecan.dimensions.AbstractDimensionTest#getDimension()
     */
    @Override
	Dimension getDimension() {
        return DimensionTools.getSequenceOfFunction(Functions.
                rCurry(this.getFunction(), new Double(0)), this.length());
    }

    /* (non-Javadoc)
     * @see bp.pecan.dimensions.AbstractDimensionTest#length()
     */
    @Override
	int length() {
        return 100;
    }

    /* (non-Javadoc)
     * @see bp.pecan.dimensions.AbstractDimensionTest#subDimensionsNumber()
     */
    @Override
	int subDimensionsNumber() {
        return 1;
    }

}


text:
{CSSTemplate {
    $classpath : "aria.widgets.container.SplitterStyle",
    $extends : "aria.widgets.WidgetStyle"
}}
    {var skinnableClassName="Splitter"/}

    {macro writeSkinClass(info)}
        {var skinClassName=info.skinClassName/}
        {var skinClass=info.skinClass/}

/* Splitter classes */

.xSplitter_${skinClassName}_sHandleH {
  position:absolute;
  height:${skinClass.separatorHeight}px;
  cursor: n-resize;
  display:block;
  {call background(skinClass.handleBackgroundColor,skinClass.handleSpriteURLh,"no-repeat center top")/}
}

.xSplitter_${skinClassName}_sContainer{
  position:relative;
  display:inline-block;
}

.xSplitter_${skinClassName}_sConstrained{
  width:100%;
  height:100%;
  display:inline-block;
  position:absolute;
}

.xSplitter_${skinClassName}_sSplitBarProxyH{
  position:absolute;
  height:${skinClass.separatorHeight}px;
  cursor: n-resize;
  display:block;
  z-index:9999;
  width:100%;
  {call background(skinClass.proxyBackgroundColor,skinClass.proxySpriteURLh,"no-repeat center top")/}
}

.xSplitter_${skinClassName}_sBdr{
   border:1px solid ${skinClass.borderColor} ;
}

.xSplitter_${skinClassName}_sMacro {
  position:absolute;
  overflow: auto;
  display:block;
}

    {/macro}

{/CSSTemplate}


text:
package tabletmanager

import (
	"golang.org/x/net/context"
	"vitess.io/vitess/go/sqltypes"
	"vitess.io/vitess/go/vt/log"

	querypb "vitess.io/vitess/go/vt/proto/query"
)

// ExecuteFetchAsDba will execute the given query, possibly disabling binlogs and reload schema.
func (agent *ActionAgent) ExecuteFetchAsDba(ctx context.Context, query []byte, dbName string, maxrows int, disableBinlogs bool, reloadSchema bool) (*querypb.QueryResult, error) {
	// get a connection
	conn, err := agent.MysqlDaemon.GetDbaConnection()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	// disable binlogs if necessary
	if disableBinlogs {
		_, err := conn.ExecuteFetch("SET sql_log_bin = OFF", 0, false)
		if err != nil {
			return nil, err
		}
	}

	if dbName != "" {
		// This execute might fail if db does not exist.
		// Error is ignored because given query might create this database.
		conn.ExecuteFetch("USE "+dbName, 1, false)
	}

	// run the query
	result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/)

	// re-enable binlogs if necessary
	if disableBinlogs && !conn.IsClosed() {
		_, err := conn.ExecuteFetch("SET sql_log_bin = ON", 0, false)
		if err != nil {
			// if we can't reset the sql_log_bin flag,
			// let's just close the connection.
			conn.Close()
		}
	}

	if err == nil && reloadSchema {
		reloadErr := agent.QueryServiceControl.ReloadSchema(ctx)
		if reloadErr != nil {
			log.Errorf("failed to reload the schema %v", reloadErr)
		}
	}
	return sqltypes.ResultToProto3(result), err
}

// ExecuteFetchAsAllPrivs will execute the given query, possibly reloading schema.
func (agent *ActionAgent) ExecuteFetchAsAllPrivs(ctx context.Context, query []byte, dbName string, maxrows int, reloadSchema bool) (*querypb.QueryResult, error) {
	// get a connection
	conn, err := agent.MysqlDaemon.GetAllPrivsConnection()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	if dbName != "" {
		// This execute might fail if db does not exist.
		// Error is ignored because given query might create this database.
		conn.ExecuteFetch("USE "+dbName, 1, false)
	}

	// run the query
	result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/)

	if err == nil && reloadSchema {
		reloadErr := agent.QueryServiceControl.ReloadSchema(ctx)
		if reloadErr != nil {
			log.Errorf("failed to reload the schema %v", reloadErr)
		}
	}
	return sqltypes.ResultToProto3(result), err
}

// ExecuteFetchAsApp will execute the given query.
func (agent *ActionAgent) ExecuteFetchAsApp(ctx context.Context, query []byte, maxrows int) (*querypb.QueryResult, error) {
	// get a connection
	conn, err := agent.MysqlDaemon.GetAppConnection(ctx)
	if err != nil {
		return nil, err
	}
	defer conn.Recycle()
	result, err := conn.ExecuteFetch(string(query), maxrows, true /*wantFields*/)
	return sqltypes.ResultToProto3(result), err
}


text:
/*
 * animation.js
 * Apply custom animations to steps
 */
(function( $, document, window, undefined ) {

	'use strict';

	function parseSubstepInfo(str) {
		var arr = str.split(" ");
		var className = arr[0];
		var config = { willClass: "will-"+className, doClass: "do-"+className, hasClass: "has-"+className };
		var state = "";
		for(var i = 1; i < arr.length; i++) {
			var s = arr[i];
			switch(state) {
			case "":
				if(s === "after") {
					state = "after";
				} else {
					$.warn("unknown keyword in '"+str+"'. '"+s+"' unknown.");
				}
				break;
			case "after":
				if(s.match(/^[1-9][0-9]*m?s?/)) {
					var value = parseFloat(s);
					if(s.indexOf("ms") !== -1) {
						value *= 1;
					} else if(s.indexOf("s") !== -1) {
						value *= 1000;
					} else if(s.indexOf("m") !== -1) {
						value *= 60000;
					}
					config.delay = value;
				} else {
					config.after = Array.prototype.slice.call(arr, i).join(" ");
					i = arr.length;
				}
			}
		}
		return config;
	}
	function find(array, selector, start, end) {
		end = end || (array.length - 1);
		start = start || 0;
		for(var i = start; i < end + 1; i++) {
			if($(array[i].element).is(selector)) {
				return i;
			}
		}
	}
	function addOn(list, substep, delay) {
		$.each(substep._on, function(idx, child) {
			list.push({substep: child.substep, delay: child.delay + delay});
			addOn(list, child.substep, child.delay + delay);
		});
	}
	$.jmpress("defaults").customAnimationDataAttribute = "jmpress";
	$.jmpress("afterInit", function( nil, eventData ) {
		eventData.current.animationTimeouts = [];
		eventData.current.animationCleanupWaiting = [];
	});
	$.jmpress("applyStep", function( step, eventData ) {
		// read custom animation from elements
		var substepsData = {};
		var listOfSubsteps = [];
		$(step).find("[data-"+eventData.settings.customAnimationDataAttribute+"]")
				.each(function(idx, element) {
			if($(element).closest(eventData.settings.stepSelector).is(step)) {
				listOfSubsteps.push({element: element});
			}
		});
		if(listOfSubsteps.length === 0) {
			return;
		}
		$.each(listOfSubsteps, function(idx, substep) {
			substep.info = parseSubstepInfo(
				$(substep.element).data(eventData.settings.customAnimationDataAttribute));
			$(substep.element).addClass(substep.info.willClass);
			substep._on = [];
			substep._after = null;
		});
		var current = {_after: undefined, _on: [], info: {}}; // virtual zero step
		$.each(listOfSubsteps, function(idx, substep) {
			var other = substep.info.after;
			if(other) {
				if(other === "step") {
					other = current;
				} else if(other === "prev") {
					other = listOfSubsteps[idx-1];
				} else {
					var index = find(listOfSubsteps, other, 0, idx - 1);
					if(index === undefined) {
						index = find(listOfSubsteps, other);
					}
					other = (index === undefined || index === idx) ? listOfSubsteps[idx-1] : listOfSubsteps[index];
				}
			} else {
				other = listOfSubsteps[idx-1];
			}
			if(other) {
				if(!substep.info.delay) {
					if(!other._after) {
						other._after = substep;
						return;
					}
					other = other._after;
				}
				other._on.push({substep: substep, delay: substep.info.delay || 0});
			}
		});
		if(current._after === undefined && current._on.length === 0) {
			var startStep = find(listOfSubsteps, eventData.stepData.startSubstep) || 0;
			current._after = listOfSubsteps[startStep];
		}
		var substepsInOrder = [];
		function findNextFunc(idx, item) {
			if(item.substep._after) {
				current = item.substep._after;
				return false;
			}
		}
		do {
			var substepList = [{substep: current, delay: 0}];
			addOn(substepList, current, 0);
			substepsInOrder.push(substepList);
			current = null;
			$.each(substepList, findNextFunc);
		} while(current);
		substepsData.list = substepsInOrder;
		$(step).data("substepsData", substepsData);
	});
	$.jmpress("unapplyStep", function( step, eventData ) {
		var substepsData = $(step).data("substepsData");
		if(substepsData) {
			$.each(substepsData.list, function(idx, activeSubsteps) {
				$.each(activeSubsteps, function(idx, substep) {
					if(substep.substep.info.willClass) {
						$(substep.substep.element).removeClass(substep.substep.info.willClass);
					}
					if(substep.substep.info.hasClass) {
						$(substep.substep.element).removeClass(substep.substep.info.hasClass);
					}
					if(substep.substep.info.doClass) {
						$(substep.substep.element).removeClass(substep.substep.info.doClass);
					}
				});
			});
		}
	});
	$.jmpress("setActive", function(step, eventData) {
		var substepsData = $(step).data("substepsData");
		if(!substepsData) {
			return;
		}
		if(eventData.substep === undefined) {
			eventData.substep =
				(eventData.reason === "prev" ?
					substepsData.list.length-1 :
					0
				);
		}
		var substep = eventData.substep;
		$.each(eventData.current.animationTimeouts, function(idx, timeout) {
			clearTimeout(timeout);
		});
		eventData.current.animationTimeouts = [];
		$.each(substepsData.list, function(idx, activeSubsteps) {
			var applyHas = idx < substep;
			var applyDo = idx <= substep;
			$.each(activeSubsteps, function(idx, substep) {
				if(substep.substep.info.hasClass) {
					$(substep.substep.element)[(applyHas?"add":"remove")+"Class"](substep.substep.info.hasClass);
				}
				function applyIt() {
					$(substep.substep.element).addClass(substep.substep.info.doClass);
				}
				if(applyDo && !applyHas && substep.delay && eventData.reason !== "prev") {
					if(substep.substep.info.doClass) {
						$(substep.substep.element).removeClass(substep.substep.info.doClass);
						eventData.current.animationTimeouts.push(setTimeout(applyIt, substep.delay));
					}
				} else {
					if(substep.substep.info.doClass) {
						$(substep.substep.element)[(applyDo?"add":"remove")+"Class"](substep.substep.info.doClass);
					}
				}
			});
		});
	});
	$.jmpress("setInactive", function(step, eventData) {
		if(eventData.nextStep === step) {
			return;
		}
		function cleanupAnimation( substepsData ) {
			$.each(substepsData.list, function(idx, activeSubsteps) {
				$.each(activeSubsteps, function(idx, substep) {
					if(substep.substep.info.hasClass) {
						$(substep.substep.element).removeClass(substep.substep.info.hasClass);
					}
					if(substep.substep.info.doClass) {
						$(substep.substep.element).removeClass(substep.substep.info.doClass);
					}
				});
			});
		}
		$.each(eventData.current.animationCleanupWaiting, function(idx, item) {
			cleanupAnimation(item);
		});
		eventData.current.animationCleanupWaiting = [];
		var substepsData = $(step).data("substepsData");
		if(substepsData) {
			eventData.current.animationCleanupWaiting.push( substepsData );
		}
	});
	$.jmpress("selectNext", function( step, eventData ) {
		if(eventData.substep === undefined) {
			return;
		}
		var substepsData = $(step).data("substepsData");
		if(!substepsData) {
			return;
		}
		if(eventData.substep < substepsData.list.length-1) {
			return {step: step, substep: eventData.substep+1};
		}
	});
	$.jmpress("selectPrev", function( step, eventData ) {
		if(eventData.substep === undefined) {
			return;
		}
		var substepsData = $(step).data("substepsData");
		if(!substepsData) {
			return;
		}
		if(eventData.substep > 0) {
			return {step: step, substep: eventData.substep-1};
		}
	});

}(jQuery, document, window));


text:
function prtUtilRemoveOldLicense(fileName,doIt)
% prtUtilRemoveOldLicense(fileName)
%   Used internaly to update license information in the PRT
%
%  Uses prtUtilLicense to get the right license string.
%  Ignores files containing prtExternal or prtDoc.
%  Ignores files that already have "% Copyright (c) 2013 New Folder Consulting" in
%  them.
%  May duplicate copyrights in other files, so be careful.
%  When we update the license file, we need to write prtUtilRemoveLicense
%
%  Edit this M-file to see how to call it to make it actually do something.
%   This functionality is too dangerous to DOC.  Just edit the M-file and
%   poke around.

% Copyright (c) 2014 CoVar Applied Technologies
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files (the
% "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.

% To make it do something, make doIt true...

% g = subDir(prtRoot,'*.m');
% for i = 1:length(g); prtUtilApplyLicense(g{i}); end

if nargin < 2
    doIt = false;
end

if ~isempty(strfind(lower(fileName),'prtexternal'))
    [p,f] = fileparts(fileName);
    fprintf('prtExternal file ignored: %s (in %s)\n',p,f);
    return;
end
if ~isempty(strfind(lower(fileName),'prtdoc'))
    [p,f] = fileparts(fileName);
    fprintf('prtDoc file ignored: %s (in %s)\n',f,p);
    return;
end

fid = fopen(fileName);
s = fscanf(fid,'%c');
fclose(fid);

oldLicense = {prtUtilLicense(1)};
for i = 1:length(oldLicense)
    s = strrep(s,oldLicense{i},''); % remove any old license
end

if doIt
    fOut = fopen(fileName,'w');
    fprintf(fOut,'%s',s);
    fclose(fOut);
else
    disp('Not doing anything; see the help');
end


text:
from __future__ import absolute_import, unicode_literals

import os

import django

DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("DATABASE_ENGINE", "django.db.backends.sqlite3"),
        "NAME": os.environ.get("DATABASE_NAME", ":memory:"),
        'USER': os.environ.get("DATABASE_USER", ""),
        'PASSWORD': os.environ.get("DATABASE_PASSWORD", ""),
    }
}

INSTALLED_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sites",
    "rest_framework",
    "txmoney.rates.apps.TXMoneyRatesConfig",
    "txmoney.rest.apps.TXMoneyRestAppConfig",
    "tests.testapp"
]

if django.VERSION >= (1, 10):
    MIDDLEWARE = ()
else:
    MIDDLEWARE_CLASSES = ()

ROOT_URLCONF = "tests.testapp.urls"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
    },
]

SECRET_KEY = "not needed"

SITE_ID = 1

TXMONEY = {
    "DEFAULT_CURRENCY": "EUR",
    "OPENEXCHANGE_APP_ID": os.environ.get("OPENEXCHANGE_APP_ID")
}

USE_TZ = True


text:
<?php
/* SVN FILE: $Id: SassMixinNode.php 76 2010-05-03 11:32:32Z chris.l.yates $ */
/**
 * SassMixinNode class file.
 * @author			Chris Yates <chris.l.yates@gmail.com>
 * @copyright 	Copyright (c) 2010 PBM Web Development
 * @license			http://phamlp.googlecode.com/files/license.txt
 * @package			PHamlP
 * @subpackage	Sass.tree
 */

/**
 * SassMixinNode class.
 * Represents a Mixin.
 * @package			PHamlP
 * @subpackage	Sass.tree
 */
class SassMixinNode extends SassNode {
	const IDENTIFIER = '+';
	const MATCH = '/^\+([-\w]+)(?:\((.*?)\))?$/';
	const NAME = 1;
	const ARGUMENTS = 2;

	/**
	 * @var string name of the mixin
	 */
	private $name;
	/**
	 * @var array arguments for the mixin
	 */
	private $args = array();

	/**
	 * SassMixinDefinitionNode constructor.
	 * @param string name of the mixin
	 * @param string arguments for the mixin
	 * @return SassMixinNode
	 */
	public function __construct($name, $args = '') {
	  $this->name = $name;
	  if (!empty($args)) {
		  $_args = explode(',', $args);
		  foreach ($_args as $arg) {
	  		$this->args[] = trim($arg);
		  } // foreach
	  }
	}

	/**
	 * Parse this node.
	 * Set any attributes passed and any optional arguments not passed to their
	 * defaults, then render the children of the mixin definition.
	 * @param SassContext the context in which this node is parsed
	 * @return array the parsed node
	 */
	public function parse($context) {
		$mixin = $context->getMixin($this->name);

		$context = new SassContext($context);
		foreach ($mixin->args as $n => $name) {
			if (isset($this->args[$n])) {
				$context->setVariable($name, $this->evaluate($this->args[$n], $context));
			}
			elseif ($mixin->hasDefault($name)) {
				$context->setVariable($name, $this->evaluate($mixin->getDefault($name), $context));
			}
			else {
				throw new SassMixinNodeException("Required variable - $name - not given when using Mixin::{$this->name}\nMixin used at Line {$this->line['number']}: " . (is_array($this->line['file']) ? join(DIRECTORY_SEPARATOR, $this->line['file']) : '')."\nMixin defined at Line {$mixin->line['number']}: " . (is_array($mixin->line['file']) ? join(DIRECTORY_SEPARATOR, $mixin->line['file']) : ''));
			}
		} // foreach

		$children = array();
		foreach ($mixin->children as $child) {
			$child->parent = $this;
			$children = array_merge($children, $child->parse($context));
		} // foreach

		$context->merge();
		return $children;
	}

	/**
	 * Returns a value indicating if the line represents this type of node.
	 * @param array the line to test
	 * @return boolean true if the line represents this type of node, false if not
	 */
	static public function isa($line) {
		return $line['source'][0] === self::IDENTIFIER;
	}

	/**
	 * Returns the matches for this type of node.
	 * @param array the line to match
	 * @return array matches
	 */
	static public function match($line) {
		preg_match(self::MATCH, $line['source'], $matches);
		return $matches;
	}
}


text:
> Similar to [`String#trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) but removes only newlines

## Install

```
$ npm install --save trim-off-newlines
```

## Usage

```js
var trimOffNewlines = require('trim-off-newlines');

trimOffNewlines('\n\nunicorns\n\n');
//=> 'unicorns'
```

## Related

- [`trim-left`](https://github.com/sindresorhus/trim-left) - Similar to `String#trim()` but removes only whitespace on the left
- [`trim-right`](https://github.com/sindresorhus/trim-right) - Similar to `String#trim()` but removes only whitespace on the right

## License

MIT © [Steve Mao](https://github.com/stevemao)


text:
#include <fstream>
#include <stdlib.h>
#include <base/misc_utils.h>
#include <base/logging.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include "base/sandesh/version_types.h"
#include "base/logging.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

using namespace std;
namespace fs = boost::filesystem;
const std::string MiscUtils::CoreFileDir = "/var/crashes/";
const int MiscUtils::MaxCoreFiles = 5;
const map<MiscUtils::BuildModule, string> MiscUtils::BuildModuleNames =
    MiscUtils::MapInit();

SandeshTraceBufferPtr VersionTraceBuf(SandeshTraceBufferCreate(
                                       VERSION_TRACE_BUF, 500));

string MiscUtils::BaseName(string filename) {
    size_t pos = filename.find_last_of('/');
    if (pos != string::npos) {
        return filename.substr((pos+1));
    }
    return filename;
}

void MiscUtils::LogVersionInfo(const string build_info, Category::type categ) {
    VERSION_TRACE(VersionInfoTrace, build_info);
    if (!LoggingDisabled()) {
        VERSION_LOG(VersionInfoLog, categ, build_info);
    }
}

void MiscUtils::GetCoreFileList(string prog, vector<string> &list) {
    if (!fs::exists(CoreFileDir) || !fs::is_directory(CoreFileDir)) {
        return;
    }
    FileMMap files_map;

    string filename = "core." + BaseName(prog) + ".";

    fs::path dir_path(CoreFileDir.c_str());
    fs::directory_iterator end_itr;
    for (fs::directory_iterator itr(dir_path); itr != end_itr; itr++) {
        if (fs::is_regular_file(itr->status())) {
            const string file = itr->path().filename().generic_string();
            size_t pos = file.find(filename);
            if (pos != 0) {
                continue;
            }
            files_map.insert(FileMMap::value_type(fs::last_write_time
                                                    (itr->path()), file));
        }
    }
    FileMMap::reverse_iterator rit;
    int count = 0;
    for (rit = files_map.rbegin(); rit != files_map.rend() &&
        count < MaxCoreFiles; ++rit) {
        count++;
        list.push_back(rit->second);
    }
}

bool MiscUtils::GetVersionInfoInternal(const string &cmd, string &result) {
    FILE *fp;
    char line[512];
    fp = popen(cmd.c_str(), "r");
    if (fp == NULL) {
        result.assign("unknown");
        return false;
    }
    char *ptr = fgets(line, sizeof(line), fp);
    if (ptr == NULL) {
        result.assign("unknown");
        pclose(fp);
        return false;
    }
    ptr = strchr(line, '\n');
    if (ptr != NULL) {
        *ptr = '\0';
    }
    result.assign(line);
    pclose(fp);
    return true;
}

bool MiscUtils::GetContrailVersionInfo(BuildModule id, string &rpm_version,
                                       string &build_num) {
    bool ret1, ret2;
    stringstream build_id_cmd;
    build_id_cmd << "contrail-version | grep '" << BuildModuleNames.at(id);
    build_id_cmd << "' | awk '{ print $2 }'";
    ret1 = GetVersionInfoInternal(build_id_cmd.str(), rpm_version);

    stringstream build_num_cmd;
    build_num_cmd << "contrail-version | grep '" << BuildModuleNames.at(id);
    build_num_cmd << "' | awk '{ print $3 }'";
    ret2 = GetVersionInfoInternal(build_num_cmd.str(), build_num);

    if (!ret1 || !ret2) {
        return false;
    }
    return true;
}

bool MiscUtils::GetBuildInfo(BuildModule id, const string &build_info,
                             string &result) {
    string rpm_version;
    string build_num;

    bool ret = GetContrailVersionInfo(id, rpm_version, build_num);
    rapidjson::Document d;
    if (d.Parse<0>(const_cast<char *>(build_info.c_str())).HasParseError()) {
        result = build_info;
        return false;
    }
    rapidjson::Value& fields = d["build-info"];
    if (!fields.IsArray()) {
        result = build_info;
        return false;
    }
    fields[0u].AddMember("build-id", const_cast<char *>(rpm_version.c_str()),
                         d.GetAllocator());
    fields[0u].AddMember("build-number", const_cast<char *>(build_num.c_str()),
                         d.GetAllocator());

    rapidjson::StringBuffer strbuf;
    rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf);
    d.Accept(writer);
    result = strbuf.GetString();
    return ret;
}


text:
package api

import (
	"cf"
	"cf/models"
	"cf/net"
)

type FakeSpaceRepository struct {
	CurrentSpace models.Space

	Spaces []models.Space

	FindByNameName     string
	FindByNameSpace    models.Space
	FindByNameErr      bool
	FindByNameNotFound bool

	FindByNameInOrgName    string
	FindByNameInOrgOrgGuid string
	FindByNameInOrgSpace   models.Space

	SummarySpace models.Space

	CreateSpaceName    string
	CreateSpaceOrgGuid string
	CreateSpaceExists  bool
	CreateSpaceSpace   models.Space

	RenameSpaceGuid string
	RenameNewName   string

	DeletedSpaceGuid string
}

func (repo FakeSpaceRepository) GetCurrentSpace() (space models.Space) {
	return repo.CurrentSpace
}

func (repo FakeSpaceRepository) ListSpaces(callback func(models.Space) bool) net.ApiResponse {
	for _, space := range repo.Spaces {
		if !callback(space) {
			break
		}
	}
	return net.NewApiResponseWithStatusCode(200)
}

func (repo *FakeSpaceRepository) FindByName(name string) (space models.Space, apiResponse net.ApiResponse) {
	repo.FindByNameName = name

	var foundSpace bool = false
	for _, someSpace := range repo.Spaces {
		if name == someSpace.Name {
			foundSpace = true
			space = someSpace
			break
		}
	}

	if repo.FindByNameErr || !foundSpace {
		apiResponse = net.NewApiResponseWithMessage("Error finding space by name.")
	}

	if repo.FindByNameNotFound {
		apiResponse = net.NewNotFoundApiResponse("%s %s not found", "Space", name)
	}

	return
}

func (repo *FakeSpaceRepository) FindByNameInOrg(name, orgGuid string) (space models.Space, apiResponse net.ApiResponse) {
	repo.FindByNameInOrgName = name
	repo.FindByNameInOrgOrgGuid = orgGuid
	space = repo.FindByNameInOrgSpace
	return
}

func (repo *FakeSpaceRepository) GetSummary() (space models.Space, apiResponse net.ApiResponse) {
	space = repo.SummarySpace
	return
}

func (repo *FakeSpaceRepository) Create(name string, orgGuid string) (space models.Space, apiResponse net.ApiResponse) {
	if repo.CreateSpaceExists {
		apiResponse = net.NewApiResponse("Space already exists", cf.SPACE_EXISTS, 400)
		return
	}
	repo.CreateSpaceName = name
	repo.CreateSpaceOrgGuid = orgGuid
	space = repo.CreateSpaceSpace
	return
}

func (repo *FakeSpaceRepository) Rename(spaceGuid, newName string) (apiResponse net.ApiResponse) {
	repo.RenameSpaceGuid = spaceGuid
	repo.RenameNewName = newName
	return
}

func (repo *FakeSpaceRepository) Delete(spaceGuid string) (apiResponse net.ApiResponse) {
	repo.DeletedSpaceGuid = spaceGuid
	return
}


text:
Rack::Attack.throttle("limit 'POST /users/password' attempts per IP", limit: 20, period: 1.hour) do |request|
  if request.path == "/users/password" && request.post?
    request.env["action_dispatch.remote_ip"].to_s
  end
end

Rack::Attack.throttled_responder = lambda do |_request|
  [429, { "Content-Type" => "text/plain" }, ["Too many requests."]]
end