text:
const opts = require('./opts');
if (require.main == module) opts.parse_args();
opts.load_defaults();

const _ = require('../lib/underscore'),
    amusement = require('./amusement'),
    auth = require('./auth'),
    caps = require('./caps'),
    check = require('./msgcheck').check,
    common = require('../common'),
    { OneeSama, safe, escape_html } = common,
    config = require('../config'),
    curfew = require('../curfew/server'),
    crypto = require('crypto'),
    db = require('../db'),
    fs = require('fs'),
    imager = require('../imager'),
    { Muggle, json_paranoid } = require('../etc'),
    { Okyaku, dispatcher, scan_client_caps } = require('./okyaku'),
    render = require('./render'),
    fetch = require('node-fetch'),
    STATE = require('./state'),
    tripcode = require('./../tripcode/tripcode'),
    urlParse = require('url').parse,
    web = require('./web'),
    winston = require('winston'),
    WebSocketServer = require('ws').Server;

require('../admin');
if (!imager.is_standalone())
	require('../imager/daemon'); // preload and confirm it works
try {
	const reportConfig = require('../report/config');
	if (reportConfig.RECAPTCHA_SITE_KEY)
		require('../report/server');
} catch (e) {}

const RES = STATE.resources;

dispatcher[common.PING] = async function (msg, client) {
	if (msg.length)
		throw Muggle("Extra ping data.", JSON.stringify(msg));
	client.send([0, common.PING]);
};

dispatcher[common.SYNCHRONIZE] = async function (msg, client) {
	const chunks = web.parse_cookie(msg.pop());
	const cookie = auth.extract_login_cookie(chunks);
	if (cookie) {
		try {
			const ident = await auth.check_cookie_async(cookie);
			_.extend(client.ident, ident);
		}
		catch (err) {
			// cookie was invalid. that's OK. fall through.
			if (config.DEBUG)
				winston.verbose(`expired cookie: ${cookie}`);
		}
	}
	await synchronize(msg, client);
};

async function synchronize(msg, client) {
	if (!check(['id', 'string', 'id=>nat', 'boolean'], msg))
		throw Muggle("Invalid synchronize message");
	let [id, board, syncs, live] = msg;
	if (id in STATE.clients) {
		winston.error(`Duplicate client id ${id}`);
		throw Muggle(`Duplicate client id`);
	}
	client.id = id;
	STATE.clients[id] = client;
	const { ident } = client;

	if (!caps.can_access_board(ident, board))
		throw Muggle('Access denied.');

	let oneThreadOnly = undefined;
	client.watching = new Map();
	if (live) {
		// watch (all?) threads + listen for new threads
		// TODO: watch only the threads on the front page

		/* XXX: This will break if a thread disappears during sync
		 *      (won't be reported)
		 * Or if any of the threads they see on the first page
		 * don't show up in the 'live' pub for whatever reason.
		 * Really we should get them synced first and *then* switch
		 * to the live pub.
		 */
		client.watching.set('live', true);
	}
	else { // watch individual threads
		let count = 0;
		for (let k in syncs) {
			k = parseInt(k, 10);
			// threads might have been deleted in the interim. skip them
			if (db.OPs[k] != k || !db.OP_has_tag(board, k)) {
				delete syncs[k];
				continue;
			}
			// don't let them spam subscriptions
			if (++count > (config.THREADS_PER_PAGE * 2)) {
				return false;
			}
			if (oneThreadOnly === undefined)
				oneThreadOnly = k;
			else if (oneThreadOnly)
				oneThreadOnly = false;
			// okay, we'll request to watch this thread
			client.watching.set(k, syncs[k]);
		}
	}

	// it feels too stateful to save the board here
	// TODO delet
	client.board = board;

	if (client.db)
		client.db.disconnect();
	client.db = new db.Yakusoku(board, ident);
	/* Race between subscribe and backlog fetch; client must de-dup */
	try {
		await client.db.kiku(client.watching, client.on_update.bind(client), client.on_thread_sink.bind(client));
	}
	catch (err) {
		throw Muggle("Couldn't sync to board.", err);
	}

	// now that we're subscribed, use the backlogs to catch up
	let logs;
	try {
		logs = await client.db.fetch_backlogs(client.watching);
	}
	catch (err) {
		try {
			client.db.kikanai();
		}
		finally {
			throw Muggle("Couldn't sync to board.", err);
		}
	}

	if (ident.readOnly) {
		logs.push(`0,${common.MODEL_SET},["hot"],{"readOnly":true}`);
	}

	logs.push(`0,${common.SYNCHRONIZE}`);
	client.socket.send(`[[${logs.join('],[')}]]`);
	client.synced = true;

	if (oneThreadOnly) {
		amusement.notify_client_fun_banner(client, oneThreadOnly);
	}
}

function setup_imager_relay() {
	return new Promise((resolve, reject) => {
		const onegai = new imager.Onegai;
		onegai.relay_client_messages();
		onegai.once('relaying', () => {
			onegai.on('message', image_status);
			resolve();
		});
	});
}

function image_status(client_id, status) {
	if (!check('id', client_id))
		return;
	const client = STATE.clients[client_id];
	if (client) {
		try {
			client.send([0, common.IMAGE_STATUS, status]);
		}
		catch (e) {
			// Swallow EINTR
			// anta baka?
		}
	}
}

function page_nav(thread_count, cur_page, ascending) {
	let page_count = Math.ceil(thread_count / config.THREADS_PER_PAGE);
	page_count = Math.max(page_count, 1);
	const info = {pages: page_count, threads: thread_count, cur_page, ascending};

	const step = ascending ? -1 : 1;
	const next = Math.max(cur_page, 0) + step;
	if (next >= 0 && next < page_count)
		info.next_page = 'page' + next;
	const prev = cur_page - step;
	if (prev >= 0 && prev < page_count)
		info.prev_page = 'page' + prev;
	return info;
}

function write_gzip_head(req, resp, headers) {
	const encoding = config.GZIP && req.headers['accept-encoding'];
	if (req.ident.slow || !encoding || !encoding.includes('gzip')) {
		resp.writeHead(200, headers);
		return resp;
	}
	resp.writeHead(200, _.extend({}, headers, {
		'Content-Encoding': 'gzip',
		Vary: 'Accept-Encoding',
	}));

	const gz = require('zlib').createGzip();
	gz.pipe(resp);
	return gz;
}

function redirect_thread(cb, num, op, tag) {
	if (!tag)
		cb(null, 'redirect', `${op}#${num}`);
	else
		/* Use a JS redirect to preserve the hash */
		cb(null, 'redirect_js', `../${tag}/${op}#${num}`);
}

// unless imager.config.DAEMON, we deal with image uploads in-process.
if (!imager.is_standalone()) {
	web.route_post(/^\/upload\/$/, require('../imager/daemon').new_upload);
}

/// site root
web.resource(/^\/$/, function (req, cb) {
	cb(null, 'redirect', config.DEFAULT_BOARD + '/');
});

if (config.DEBUG) {
	/* Shortcuts for convenience */
	winston.warn("Running in (insecure) debug mode.");
	winston.warn("Do not use on the public internet.");
	web.route_get(/^\/login$/, function (req, resp) {
		auth.set_cookie(req, resp, {auth: 'Admin'});
	});
	web.route_get(/^\/mod$/, function (req, resp) {
		auth.set_cookie(req, resp, {auth: 'Moderator'});
	});
}
else {
	/* Production login endpoint */
	web.route_get(/^\/login$/, auth.login);

	if (config.SERVE_STATIC_FILES)
		winston.warn("Recommended: nginx-like webserver instead of SERVE_STATIC_FILES.");
	if (config.SERVE_IMAGES)
		winston.warn("Recommended: nginx-like webserver instead of SERVE_IMAGES.");
}
web.route_get(/^\/logout$/, auth.logout);
web.route_post(/^\/logout$/, auth.logout);

function write_mod_js(resp, ident) {
	if (!RES.modJs) {
		resp.writeHead(500);
		resp.end('Mod js not built?!');
		return;
	}

	const noCacheJs = _.clone(web.noCacheHeaders);
	noCacheJs['Content-Type'] = 'text/javascript; charset=UTF-8';
	resp.writeHead(200, noCacheJs);
	resp.end(`(function (IDENT) {
${RES.modJs};
})(${JSON.stringify(ident)});`);
}

/// provide admin client js
web.resource_auth(/^\/admin\.js$/, (req, cb) => {
	if (!caps.can_administrate(req.ident))
		cb(404);
	else
		cb(null, 'ok');
},
function (req, resp) {
	const { auth, csrf, user } = req.ident;
	write_mod_js(resp, { auth, csrf, user });
});

web.resource_auth(/^\/mod\.js$/, (req, cb) => {
	if (!caps.can_moderate(req.ident))
		cb(404);
	else
		cb(null, 'ok');
},
(req, resp) => {
	const { auth, csrf, user } = req.ident;
	write_mod_js(resp, { auth, csrf, user });
});

/// view board index
web.resource(/^\/(\w+)$/, function (req, params, cb) {
	const board = params[1];
	/* If arbitrary boards were allowed, need to escape this: */
	const dest = board + '/';
	if (req.ident.suspension)
		return cb(null, 'redirect', dest); /* TEMP */
	if (!caps.can_ever_access_board(req.ident, board))
		return cb(404);
	cb(null, 'redirect', dest);
});

web.resource(/^\/(\w+)\/live$/, function (req, params, cb) {
	if (req.ident.suspension)
		return cb(null, 'redirect', '.'); /* TEMP */
	if (!caps.can_ever_access_board(req.ident, params[1]))
		return cb(404);
	cb(null, 'redirect', '.');
});

web.resource(/^\/(\w+)\/$/, (req, params, cb) => {
	const board = params[1];
	const { ident } = req;
	if (ident.suspension)
		return cb(null, 'ok'); /* TEMP */
	if (!caps.can_ever_access_board(ident, board))
		return cb(404);

	cb(null, 'ok', { board });
},
function (req, resp) {
	/* TEMP */
	if (req.ident.suspension)
		return render_suspension(req, resp);

	const { board } = this;
	const { ident } = req;
	if (!caps.temporal_access_check(ident, board)) {
		curfew.divert_response(board, resp);
		return;
	}

	const yaku = new db.Yakusoku(board, ident);
	yaku.get_tag(-1);
	let paginationHtml;
	yaku.once('begin', (thread_count) => {
		const nav = page_nav(thread_count, -1, board == 'archive');
		const initScript = make_init_script(ident);
		render.write_board_head(resp, initScript, board, nav);
		paginationHtml = render.make_pagination_html(nav);
		resp.write(paginationHtml);
		resp.write('
\n');
	});
	resp = write_gzip_head(req, resp, web.noCacheHeaders);
	const opts = {fullLinks: true, board};
	render.write_thread_html(yaku, req, resp, opts);
	yaku.once('end', () => {
		resp.write(paginationHtml);
		render.write_page_end(resp, ident, false);
		resp.end();
		yaku.disconnect();
	});
	yaku.once('error', (err) => {
		winston.error(`rendering /${board}/ index: ${err}`);
		resp.end();
		yaku.disconnect();
	});
});

/// view page of board
web.resource(/^\/(\w+)\/page(\d+)$/, function (req, params, cb) {
	const board = params[1];
	if (!caps.temporal_access_check(req.ident, board))
		return cb(null, 302, '..');
	if (req.ident.suspension)
		return cb(null, 'ok'); /* TEMP */
	if (!caps.can_access_board(req.ident, board))
		return cb(404);
	const page = parseInt(params[2], 10);
	if (page > 0 && params[2][0] == '0') /* leading zeroes? */
		return cb(null, 'redirect', 'page' + page); // if so, normalize url

	const yaku = new db.Yakusoku(board, req.ident);
	yaku.get_tag(page);
	yaku.once('nomatch', () => {
		cb(null, 302, '.');
		yaku.disconnect();
	});
	yaku.once('begin', (threadCount) => {
		cb(null, 'ok', { board, page, yaku, threadCount });
	});
},
function (req, resp) {
	/* TEMP */
	if (req.ident.suspension)
		return render_suspension(req, resp);

	const { board, page, yaku, threadCount } = this;
	const nav = page_nav(this.threadCount, page, board == 'archive');
	resp = write_gzip_head(req, resp, web.noCacheHeaders);
	const initScript = make_init_script(req.ident);
	render.write_board_head(resp, initScript, board, nav);
	const paginationHtml = render.make_pagination_html(nav);
	resp.write(paginationHtml);
	resp.write('
\n');

	const opts = {fullLinks: true, board};
	render.write_thread_html(yaku, req, resp, opts);
	yaku.once('end', () => {
		resp.write(paginationHtml);
		render.write_page_end(resp, req.ident, false);
		resp.end();
		this.finished();
	});
	yaku.once('error', (err) => {
		winston.error(`rendering /${board}/ page #${page}: ${err}`);
		resp.end();
		this.finished();
	});
},
function () {
	this.yaku.disconnect();
});

web.resource(/^\/(\w+)\/page(\d+)\/$/, (req, params, cb) => {
	if (!caps.temporal_access_check(req.ident, params[1]))
		cb(null, 302, '..');
	else
		cb(null, 'redirect', '../page' + params[2]);
});

/// view thread
web.resource(/^\/(\w+)\/(\d+)$/, function (req, params, cb) {
	const board = params[1];
	if (!caps.temporal_access_check(req.ident, board))
		return cb(null, 302, '.');
	if (req.ident.suspension)
		return cb(null, 'ok'); /* TEMP */
	if (!caps.can_access_board(req.ident, board))
		return cb(404);
	const num = parseInt(params[2], 10);
	if (!num)
		return cb(404);
	else if (params[2][0] == '0')
		return cb(null, 'redirect', '' + num);

	const json = web.prefers_json(req.headers.accept);
	let op;
	if (board == 'graveyard') {
		op = num;
	}
	else {
		op = db.OPs[num];
		if (!op)
			return cb(404);
		if (!json && !db.OP_has_tag(board, op)) {
			const tag = db.first_tag_of(op);
			if (tag) {
				if (!caps.can_access_board(req.ident, tag))
					return cb(404);
				return redirect_thread(cb, num, op, tag);
			}
			else {
				winston.warn(`Orphaned post >>${num} with tagless OP >>${op}`);
				return cb(404);
			}
		}
		if (!json && op != num)
			return redirect_thread(cb, num, op);
	}
	if (!caps.can_access_thread(req.ident, op))
		return cb(404);
	if (json)
		return cb(null, 'ok', {json: true, num});

	const yaku = new db.Yakusoku(board, req.ident);
	const reader = new db.Reader(yaku);
	const opts = {redirect: true};

	const lastN = detect_last_n(req.query);
	if (lastN)
		opts.abbrev = lastN + config.ABBREVIATED_REPLIES;

	if (caps.can_administrate(req.ident) && 'reported' in req.query)
		opts.showDead = true;

	reader.get_thread(board, num, opts);
	reader.once('nomatch', () => {
		cb(404);
		yaku.disconnect();
	});
	reader.once('redirect', (op, tag) => {
		redirect_thread(cb, num, op, tag);
		yaku.disconnect();
	});
	reader.once('begin', (preThread) => {
		const headers = web.noCacheHeaders;
		const { subject } = preThread;
		const { abbrev } = opts;
		cb(null, 'ok', { board, op, headers, subject, abbrev, yaku, reader });
	});
},
function (req, resp) {
	/* TODO: json suspensions */
	if (req.ident.suspension)
		return render_suspension(req, resp);
	if (this.json)
		return write_json_post(req, resp, this.num);

	const { board, op, headers, subject, abbrev, yaku, reader } = this;

	resp = write_gzip_head(req, resp, headers);
	const initScript = make_init_script(req.ident);
	render.write_thread_head(resp, initScript, board, op, { subject, abbrev });

	const opts = {fullPosts: true, board, loadAllPostsLink: true};
	render.write_thread_html(reader, req, resp, opts);
	reader.once('end', () => {
		render.write_page_end(resp, req.ident, true);
		resp.end();
		this.finished();
	});
	const on_err = (err) => {
		winston.error(`rendering thread >>${num}: ${err}`);
		resp.end();
		this.finished();
	};
	this.reader.once('error', on_err);
	this.yaku.once('error', on_err);
},
function () {
	this.yaku.disconnect();
});

function write_json_post(req, resp, num) {
	const json = {TODO: true};

	const cache = json.editing ? 'no-cache' : 'private, max-age=86400';
	resp = write_gzip_head(req, resp, {
		'Content-Type': 'application/json',
		'Cache-Control': cache,
	});
	resp.end(JSON.stringify(json));
}

function detect_last_n(query) {
	for (let k in query) {
		const m = /^last(\d+)$/.exec(k);
		if (m) {
			const n = parseInt(m[1], 10);
			if (common.reasonable_last_n(n))
				return n;
		}
	}
	return 0;
}

web.resource(/^\/(\w+)\/(\d+)\/$/, function (req, params, cb) {
	if (!caps.temporal_access_check(req.ident, params[1]))
		cb(null, 302, '..');
	else
		cb(null, 'redirect', '../' + params[2]);
});

web.resource(/^\/outbound\/iqdb\/([\w+\/]{22}\.\w{3,4})$/, (req, params, cb) => {
	let thumb = `${imager.config.MEDIA_URL}vint/${params[1]}`;

	// attempt to make protocol more absolute
	const u = urlParse(thumb, false, true);
	if (!u.protocol) {
		u.protocol = 'http:';
		thumb = u.format();
	}
	cb(null, 303.1, `https://iqdb.org?url=${encodeURIComponent(thumb)}`);
});

web.resource(/^\/outbound\/a\/(\d{0,10})$/, function (req, params, cb) {
	const thread = parseInt(params[1], 10);
	let url = 'https://boards.4chan.org/a/';
	if (thread)
		url += 'thread/' + thread;
	cb(null, 303.1, url);
});

function make_init_script(ident) {
	const secretKey = STATE.hot.connTokenSecretKey;
	if (!ident || !secretKey)
		return '';
	const country = ident.country || 'x';
	const payload = JSON.stringify({
		ip: ident.ip,
		cc: country,
		ts: Date.now(),
	});
	// encrypt payload as 'ctoken'
	const iv = crypto.randomBytes(12);
	const cipher = crypto.createCipheriv('aes-256-gcm', secretKey, iv);
	let crypted = cipher.update(payload, 'utf8', 'hex');
	crypted += cipher.final('hex');
	const authTag = cipher.getAuthTag()
	if (authTag.length != 16)
		throw 'auth tag of unexpected length';
	const combined = iv.toString('hex') + authTag.toString('hex') + crypted;
	return `\t<script>const ctoken = ${json_paranoid(combined)};</script>\n`;
}

function decrypt_ctoken(ctoken) {
	const secretKey = STATE.hot.connTokenSecretKey;
	if (!secretKey)
		return null;
	if (ctoken.length < 56) {
		winston.warn('ctoken too short');
		return null;
	}
	const iv = Buffer.from(ctoken.slice(0, 24), 'hex');
	if (iv.length != 12) {
		winston.warn('iv not hex');
		return null;
	}
	const authTag = Buffer.from(ctoken.slice(24, 56), 'hex');
	if (authTag.length != 16) {
		winston.warn('authTag not hex');
		return null;
	}
	try {
		const decipher = crypto.createDecipheriv('aes-256-gcm', secretKey, iv);
		decipher.setAuthTag(authTag);
		let plain = decipher.update(ctoken.slice(56), 'hex', 'utf8');
		plain += decipher.final('utf8');
		return JSON.parse(plain);
	}
	catch (e) {
		winston.warn(`decrypt ctoken: ${e}`);
	}
	return null;
}

const TWEET_CACHE = new Map();
const TWEET_CACHE_MAX = 100;
const TWEET_CACHE_EXPIRY = 120*1000;
const TWEET_IN_FLIGHT = new Map();

web.resource(/^\/outbound\/tweet\/(\w{1,15}\/status\/\d{4,20})$/, async (req, params, cb) => {
	const url = new URL('https://publish.twitter.com/oembed');
	{
		const { s, theme } = req.query;
		let tweet_url = 'https://twitter.com/' + params[1];
		if (/^\d+$/.test(s))
			tweet_url += `?s=${s}`;
		url.searchParams.append('url', tweet_url);
		url.searchParams.append('omit_script', 'true');
		url.searchParams.append('theme', theme == 'dark' ? 'dark' : 'light');
	}
	const key = 'tw:'+url;

	// do we have a locally cached copy?
	if (TWEET_CACHE.has(key)) {
		const json = TWEET_CACHE.get(key);
		return cb(null, 'ok', {json});
	}

	// maybe a fetch is already pending?
	if (TWEET_IN_FLIGHT.has(key)) {
		const promise = TWEET_IN_FLIGHT.get(key);
		try {
			const json = await promise;
			if (json) {
				return cb(null, 'ok', {json});
			}
		}
		catch (e) {
			return cb(Muggle("Tweet was lost; try again.", e));
		}
		// shouldn't get here
		return cb('tweet got lost on the way');
	}

	// kick off the twitter API request
	const promise = (async () => {
		const resp = await fetch(url);
		if (!resp.ok) {
			if (resp.status == 404)
				throw 404;
			else
				throw Muggle('twitter returned ' + resp.statusText);
		}
		const json = await resp.json();
		if (!json.html)
			throw Muggle('unexpected tweet form');
		return json;
	})();

	// mark this tweet as in-flight while we fetch it
	TWEET_IN_FLIGHT.set(key, promise);

	// and wait for the tweet to come back
	let json;
	try {
		json = await promise;
	}
	catch (e) {
		cb(e);
		return;
	}
	finally {
		TWEET_IN_FLIGHT.delete(key);
	}

	if (json) {
		// cache the tweet if there's space
		if (TWEET_CACHE.size < TWEET_CACHE_MAX) {
			TWEET_CACHE.set(key, json);
			setTimeout(() => TWEET_CACHE.delete(key), TWEET_CACHE_EXPIRY);
		}

		// pass the tweet json to the second handler
		cb(null, 'ok', {json});
	}

}, function (req, resp) {
	const { json } = this;
	resp = write_gzip_head(req, resp, {
		'Content-Type': 'application/json',
		'Cache-Control': config.DEBUG ? 'no-cache' : 'public, max-age=600',
	});
	resp.end(JSON.stringify(json));
});

web.route_get_auth(/^\/dead\/(src|thumb|mid)\/(\w+\.\w{3})$/,
			function (req, resp, params) {
	if (!caps.can_administrate(req.ident))
		return web.render_404(resp);
	imager.send_dead_image(params[1], params[2], resp);
});

function valid_links(frag, state, ident) {
	const links = {};
	// use a short-lived OneeSama to populate `ident` with all the >>links in `frag`
	const onee = new OneeSama(num => {
		const op = db.OPs[num];
		if (op && caps.can_access_thread(ident, op))
			links[num] = db.OPs[num];
	});
	onee.callback = (frag) => {};
	onee.state = state;
	onee.fragment(frag);
	return _.isEmpty(links) ? null : links;
}

const insertSpec = [{
	frag: 'opt string',
	image: 'opt string',
	nonce: 'id',
	op: 'opt id',
	name: 'opt string',
	email: 'opt string',
	auth: 'opt string',
	subject: 'opt string',
	flavor: 'opt string',
}];

dispatcher[common.INSERT_POST] = async function (msg, client) {
	if (!check(insertSpec, msg))
		return false;
	msg = msg[0];
	if (client.post)
		return update_post(msg.frag, client);
	if (!caps.can_access_board(client.ident, client.board))
		return false;
	const { frag, image } = msg;
	if (frag && /^\s*$/g.test(frag))
		return false;
	if (!frag && !image)
		return false;
	if (config.DEBUG)
		debug_command(client, frag);

	await allocate_post(msg, client);
}

async function allocate_post(msg, client) {
	if (client.post)
		throw Muggle("Already have a post.");
	const post = {time: Date.now(), nonce: msg.nonce};
	const { board, ident } = client;
	const { ip } = ident;
	let image_alloc;
	if (msg.image) {
		if (!/^\d+$/.test(msg.image))
			throw Muggle('Expired image token.');
		image_alloc = msg.image;
	}
	let body = '';
	if (msg.frag) {
		if (/^\s*$/g.test(msg.frag))
			throw Muggle('Bad post body.');
		if (msg.frag.length > common.MAX_POST_CHARS)
			throw Muggle('Post is too long.');
		body = msg.frag.replace(config.EXCLUDE_REGEXP, '');
	}

	const { op } = msg;
	if (op) {
		if (db.OPs[op] != op)
			throw Muggle('Thread does not exist.');
		if (!db.OP_has_tag(board, op))
			throw Muggle('Wrong board for thread.');
		post.op = op;
	}
	else {
		// new threads must have an image
		if (!image_alloc)
			throw Muggle('Image missing.');
		let subject = (msg.subject || '').trim();
		subject = subject.replace(config.EXCLUDE_REGEXP, '');
		subject = subject.replace(/[「」]/g, '');
		subject = subject.slice(0, config.SUBJECT_MAX_LENGTH);
		if (subject)
			post.subject = subject;
	}

	/* TODO: Check against client.watching? */
	if (msg.name) {
		const [name, trip, secureTrip] = common.parse_name(msg.name);
		post.name = name;
		const spec = STATE.hot.SPECIAL_TRIPCODES;
		if (spec && trip && trip in spec) {
			post.trip = spec[trip];
		}
		else if (trip || secureTrip) {
			const hashed = tripcode.hash(trip, secureTrip);
			if (hashed)
				post.trip = hashed;
		}
	}
	if (msg.email) {
		post.email = msg.email.trim().substr(0, 320);
		if (common.is_noko(post.email))
			delete post.email;
	}
	if (msg.flavor && /^\w+$/.test(msg.flavor)) {
		if (msg.flavor == 'floop')
			post.flavor = 'floop';
	}
	post.state = common.initial_state();

	if ('auth' in msg) {
		if (!msg.auth || !ident || msg.auth !== ident.auth)
			throw Muggle('Bad auth.');
		post.auth = msg.auth;
	}

	if (op)
		await client.db.check_thread_locked(op);
	else
		await client.db.check_new_thread_throttle(ip);

	// note: `reserve_post` checks the words-per-timeslot rate limiter
	const num = await client.db.reserve_post(op, ip);
	post.num = num;

	if (!client.synced)
		throw Muggle('Dropped; post aborted.');
	// sort-of guard against a race condition here
	if (client.post)
		throw Muggle('Already have a post.');

	const links = valid_links(body, post.state, ident);
	if (links)
		post.links = links;

	const extra = {ip, board};
	if (body.length && is_game_board(board))
		amusement.roll_dice(body, post, extra);

	client.post = post;
	try {
		if (image_alloc) {
			const image = await imager.obtain_image_alloc(image_alloc);
			if (image)
				extra.image_alloc = image;
		}
		if (!client.synced)
			throw Muggle('Dropped; post aborted.');

		await client.db.insert_post(post, body, extra);
		post.body = body;
	}
	catch (err) {
		if (client.post === post)
			client.post = null;
		throw err;
	}
}

async function update_post(frag, client) {
	if (typeof frag != 'string')
		return false;
	if (config.DEBUG)
		debug_command(client, frag);
	frag = frag.replace(config.EXCLUDE_REGEXP, '');
	const { post } = client;
	if (!post)
		return false;
	const limit = common.MAX_POST_CHARS;
	if (frag.length > limit || post.length >= limit)
		return false;
	const combined = post.length + frag.length;
	if (combined > limit)
		frag = frag.substr(0, combined - limit);
	const extra = {ip: client.ident.ip};
	if (is_game_board(client.board))
		amusement.roll_dice(frag, post, extra);
	post.body += frag;
	/* imporant: broadcast prior state */
	const old_state = post.state.slice();

	const links = valid_links(frag, post.state, client.ident);
	if (links) {
		if (!post.links)
			post.links = {};
		// TODO wtf use Maps instead
		const new_links = {};
		for (let k in links) {
			const link = links[k];
			if (post.links[k] != link) {
				post.links[k] = link;
				new_links[k] = link;
			}
		}
		extra.links = links;
		extra.new_links = new_links;
	}

	await client.db.append_post(post, frag, old_state, extra);
}
dispatcher[common.UPDATE_POST] = update_post;

function debug_command(client, frag) {
	if (!frag)
		return;
	if (/\bfail\b/.test(frag))
		client.kotowaru(Muggle("Failure requested."));
	else if (/\bclose\b/.test(frag))
		client.socket.close();
}

dispatcher[common.FINISH_POST] = async function (msg, client) {
	if (!check([], msg))
		return false;
	if (!client.post)
		return true; /* whatever */
	await client.finish_post();
}

dispatcher[common.DELETE_POSTS] = caps.mod_handler(async (nums, client) => {
	/* Omit to-be-deleted posts that are inside to-be-deleted threads */
	const ops = {};
	const { OPs } = db;
	for (let num of nums) {
		if (num == OPs[num])
			ops[num] = 1;
	}
	nums = nums.filter(num => (OPs[num] == num || !(OPs[num] in ops)));
	await client.db.remove_posts(nums);
});

dispatcher[common.LOCK_THREAD] = caps.mod_handler(async (nums, client) => {
	nums = nums.filter(op => db.OPs[op] == op);
	for (let num of nums) {
		await client.db.toggle_thread_lock(num);
	}
});

dispatcher[common.DELETE_IMAGES] = caps.mod_handler(async (nums, client) => {
	await client.db.remove_images(nums);
});

dispatcher[common.INSERT_IMAGE] = async function (msg, client) {
	if (!check(['string'], msg))
		return false;
	const [alloc_token] = msg;
	const { post } = client;
	if (!post || post.image)
		return false;
	const alloc = await imager.obtain_image_alloc(alloc_token);
	if (post.image)
		return;
	await client.db.add_image(post, alloc, client.ident.ip);
};

dispatcher[common.SPOILER_IMAGES] = caps.mod_handler(async (nums, client) => {
	await client.db.force_image_spoilers(nums);
});

dispatcher[common.EXECUTE_JS] = function (msg, client) {
	if (!caps.can_administrate(client.ident))
		return false;
	if (!check(['id'], msg))
		return false;
	const op = msg[0];
	client.db.set_fun_thread(op, function (err) {
		if (err)
			client.kotowaru(err);
	});
	return true;
};

function is_game_board(board) {
	return config.GAME_BOARDS.includes(board);
}

function render_suspension(req, resp) {
setTimeout(function () {
	const ban = req.ident.suspension, tmpl = RES.suspensionTmpl;
	resp.writeHead(200, web.noCacheHeaders);
	resp.write(tmpl[0]);
	resp.write(escape_html(ban.why || ''));
	resp.write(tmpl[1]);
	resp.write(escape_html(ban.until || ''));
	resp.write(tmpl[2]);
	resp.write(escape_html(STATE.hot.EMAIL || '<missing>'));
	resp.end(tmpl[3]);
}, 2000);
}

if (config.DEBUG) {
	winston.remove(winston.transports.Console);
	winston.add(winston.transports.Console, {level: 'verbose'});
}
else {
	winston.add(winston.transports.File, {level: 'warn', filename: 'error.log'});
}

function start_server() {
	const is_unix_socket = (typeof config.LISTEN_PORT == 'string');
	if (is_unix_socket) {
		try { fs.unlinkSync(config.LISTEN_PORT); } catch (e) {}
	}
	web.server.listen(config.LISTEN_PORT, config.LISTEN_HOST);
	if (is_unix_socket) {
		fs.chmodSync(config.LISTEN_PORT, '777'); // TEMP
	}

	const ws_server = new WebSocketServer({ noServer: true });
	web.server.on('upgrade', (req, socket, head) => {
		const { pathname } = urlParse(req.url);
		if (pathname == config.SOCKET_PATH) {
			ws_server.handleUpgrade(req, socket, head, (ws) => {
				ws_server.emit('connection', ws, req);
			});
		}
		else {
			winston.warn(`http upgrade "${encodeURI(pathname)}" discarded`);
			socket.destroy();
		}
	});

	ws_server.on('connection', (socket, req) => {
		let ip = req.socket.remoteAddress;
		let country;
		if (config.TRUST_X_FORWARDED_FOR) {
			const ff = web.parse_forwarded_for(req.headers['x-forwarded-for']);
			if (ff)
				ip = ff;
		}
		if (config.CLOUDFLARE) {
			ip = req.headers['cf-connecting-ip'] || ip;
			country = req.headers['cf-ipcountry'];
		}
		if (!ip) {
			winston.warn(`no ip from ${socket}`);
			socket.close();
			return;
		}

		// parse ctoken
		const url = urlParse(req.url, true);
		if (url.query && url.query.ctoken) {
			const token = decrypt_ctoken(url.query.ctoken);
			if (token) {
				if (token.ts + 24*60*60*1000 < Date.now()) {
					// token expired, ask for a new one?
					winston.warn('ctoken: expired');
				}
				if (ip != token.ip)
					winston.info(`ctoken: ${ip} != ${token.ip}`);
				if (token.cc && token.cc != country) {
					if (country)
						winston.info(`ctoken: ${country} => ${token.cc}`);
					country = token.cc;
				}
			}
			else {
				winston.log(`ctoken: invalid from ${ip}`);
			}
		}
		else if (STATE.hot.connTokenSecretKey) {
			winston.warn(`ctoken: MISSING from ${ip}`);
		}

		const client = new Okyaku(socket, ip, country);
		socket.on('message', client.on_message.bind(client));
		socket.on('close', client.on_close.bind(client));
	});

	process.on('SIGHUP', hot_reloader);
	db.on_pub('reloadHot', hot_reloader);

	if (config.DAEMON) {
		const daemon = require('daemon');
		daemon.start(process.stdout.fd, process.stderr.fd);
		daemon.lock(config.PID_FILE);
		winston.remove(winston.transports.Console);
		return;
	}

	process.nextTick(non_daemon_pid_setup);

	winston.info(`Listening on ${config.LISTEN_HOST || ''}${is_unix_socket ? '' : ':'}${config.LISTEN_PORT}.`);
}

async function hot_reloader() {
	try {
		await STATE.reload_hot_resources();
	}
	catch (err) {
		winston.error("Error trying to reload:");
		winston.error(err);
		return;
	}
	scan_client_caps();
	winston.info('Reloaded initial state.');
}

function non_daemon_pid_setup() {
	const pidFile = config.PID_FILE;
	fs.writeFile(pidFile, process.pid+'\n', (err) => {
		if (err)
			return winston.warn(`Couldn't write pid: ${err}`);
		process.once('SIGINT', delete_pid);
		process.once('SIGTERM', delete_pid);
		winston.info(`PID ${process.pid} written to ${pidFile}`);
	});

	function delete_pid() {
		try {
			fs.unlinkSync(pidFile);
		}
		catch (e) { }
		process.exit(1);
	}
}

async function main() {
	if (!process.getuid())
		throw new Error("Refusing to run as root.");
	tripcode.setSalt(config.SECURE_SALT);

	await imager.make_media_dirs();
	await setup_imager_relay();
	await STATE.reload_hot_resources();
	await db.track_OPs();

	if (!config.READ_ONLY) {
		const yaku = new db.Yakusoku(null, db.UPKEEP_IDENT);
		await yaku.finish_all();
		yaku.disconnect();

		if (!imager.is_standalone()) {
			const onegai = new imager.Onegai;
			await onegai.delete_temporaries();
			onegai.disconnect();
		}
	}
	process.nextTick(start_server);
}

if (require.main === module)
	main().catch(err => { winston.error(err); process.exit(1); });


text:
#include "AudioDeviceList.h"
#include "AudioDevice.h"

AudioDeviceList::AudioDeviceList(bool inputs) :
	mInputs(inputs)
{
	BuildList();
}

AudioDeviceList::~AudioDeviceList()
{
}

void	AudioDeviceList::BuildList()
{
	mDevices.clear();

	UInt32 propsize;

	verify_noerr(AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propsize, NULL));
	int nDevices = propsize / sizeof(AudioDeviceID);
	AudioDeviceID *devids = new AudioDeviceID[nDevices];
	verify_noerr(AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propsize, devids));

	for (int i = 0; i < nDevices; ++i) {
		AudioDevice dev(devids[i], mInputs);
		//if (dev.CountChannels() > 0)
		{
			Device d;

			d.mID = devids[i];
			dev.GetName(d.mName, sizeof(d.mName));
			mDevices.push_back(d);
		}
	}
	delete[] devids;
}

redpajama_set_name: RedPajamaGithub


text:
# coding: utf-8

#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import unittest

import azure.mgmt.storage
from testutils.common_recordingtestcase import record
from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase

class MgmtStorageTest(AzureMgmtTestCase):

    def setUp(self):
        super(MgmtStorageTest, self).setUp()
        self.storage_client = self.create_mgmt_client(
            azure.mgmt.storage.StorageManagementClient
        )
        if not self.is_playback():
            self.create_resource_group()

    @record
    def test_storage_usage(self):
        usages = list(self.storage_client.usage.list())
        self.assertGreater(len(usages), 0)

    @record
    def test_storage_accounts(self):
        account_name = self.get_resource_name('pyarmstorage')

        result_check = self.storage_client.storage_accounts.check_name_availability(
            account_name
        )
        self.assertTrue(result_check.name_available)
        self.assertFalse(result_check.reason)
        self.assertFalse(result_check.message)

        params_create = azure.mgmt.storage.models.StorageAccountCreateParameters(
            sku=azure.mgmt.storage.models.Sku(azure.mgmt.storage.models.SkuName.standard_lrs),
            kind=azure.mgmt.storage.models.Kind.storage,
            location=self.region
        )
        result_create = self.storage_client.storage_accounts.create(
            self.group_name,
            account_name,
            params_create,
        )
        storage_account = result_create.result()
        self.assertEqual(storage_account.name, account_name)

        storage_account = self.storage_client.storage_accounts.get_properties(
            self.group_name,
            account_name,
        )
        self.assertEqual(storage_account.name, account_name)

        result_list_keys = self.storage_client.storage_accounts.list_keys(
            self.group_name,
            account_name,
        )
        keys = {v.key_name: (v.value, v.permissions) for v in result_list_keys.keys}
        self.assertEqual(len(keys), 2)
        self.assertGreater(len(keys['key1'][0]), 0)
        self.assertGreater(len(keys['key1'][0]), 0)

        result_regen_keys = self.storage_client.storage_accounts.regenerate_key(
            self.group_name,
            account_name,
            "key1"
        )
        new_keys = {v.key_name: (v.value, v.permissions) for v in result_regen_keys.keys}
        self.assertEqual(len(new_keys), 2)
        self.assertNotEqual(
            new_keys['key1'][0],
            keys['key1'][0],
        )
        self.assertEqual(
            new_keys['key2'][0],
            keys['key2'][0],
        )

        result_list = self.storage_client.storage_accounts.list_by_resource_group(
            self.group_name,
        )
        result_list = list(result_list)
        self.assertGreater(len(result_list), 0)

        result_list = self.storage_client.storage_accounts.list()
        result_list = list(result_list)
        self.assertGreater(len(result_list), 0)

        storage_account = self.storage_client.storage_accounts.update(
            self.group_name,
            account_name,
            azure.mgmt.storage.models.StorageAccountUpdateParameters(
                sku=azure.mgmt.storage.models.Sku(azure.mgmt.storage.models.SkuName.standard_grs)
            )
        )

        self.storage_client.storage_accounts.delete(
            self.group_name,
            account_name,
        )

#------------------------------------------------------------------------------
if __name__ == '__main__':
    unittest.main()


text:
class Api::V1::MeetingsController < JSONAPI::ResourceController
end


text:
using System;
using TIKSN.PowerShell;

namespace TIKSN.Cmdlets.Commands
{
    public abstract class Command : CommandBase
    {
        protected override IServiceProvider GetServiceProvider() => CompositionRootSetup.ServiceProvider;
    }
}


text:
package org.sindice.siren.search.node;

import java.io.IOException;

import org.apache.lucene.util.IntsRef;
import org.sindice.siren.index.DocsAndNodesIterator;
import org.sindice.siren.index.DocsNodesAndPositionsEnum;
import org.sindice.siren.util.NodeUtils;

/**
 * A NodeDisjunctionScorerQueue maintains a partial ordering of its
 * {@link NodeScorer}s such that the least scorer can always be found in
 * constant time. This allows to retrieve in order all matching documents and
 * nodes from multiple scorers, as if they were one stream.
 *

 * NOTE: After initialisation, the NodeDisjunctionScorerQueue is
 * positioned on the first candidate document.
 *

 * Based on a binary heap data structure. The root (top) of the heap contains
 * the least scorer.
 *

 * {@link #put(NodeScorer)} requires log(size) time.
 *

 * The ordering is based on {@link SirenScorer.doc()} and
 * {@link SirenScorer.node()}.
 *

 * Code taken from {@link ScorerDocQueue} and adapted for the Siren use case.
 */
class NodeDisjunctionScorerQueue {

  private final HeapedScorerNode[] heap;

  private int size;

  private int nrMatchersInNode = -1;

  private float scoreInNode = 0;

  private class HeapedScorerNode {

    NodeScorer scorer;

    int doc;
    IntsRef node;

    HeapedScorerNode(final NodeScorer s) {
      this.scorer = s;
      this.adjust();
    }

    void adjust() {
      doc = scorer.doc();
      node = scorer.node();
    }

    @Override
    public String toString() {
      return "[" + doc + "," + "[" + node + "]]";
    }

  }

  private HeapedScorerNode topHSN; // same as heap[1], only for speed

  /** Create a NodeDisjunctionScorerQueue with a given capacity. */
  public NodeDisjunctionScorerQueue(final int capacity) {
    size = 0;
    final int heapSize = capacity + 1;
    heap = new HeapedScorerNode[heapSize];
    topHSN = heap[1]; // initially null
  }

  /**
   * Adds a SirenPrimitiveScorer to a NodeDisjunctionScorerQueue in log(size)
   * time. If one tries to add more Scorers than maxSize a RuntimeException
   * (ArrayIndexOutOfBound) is thrown.
   *

   * The scorer is advanced to the next document to initiate heap ordering.
   */
  public final void put(final NodeScorer scorer) throws IOException {
    if (scorer.nextCandidateDocument()) { // if scorer exhausted, no need to add it
      size++;
      heap[size] = new HeapedScorerNode(scorer);
      this.upHeap();
    }
  }

  /**
   * For test purpose only
   *

   * Returns the least Scorer of the NodeDisjunctionScorerQueue in constant time.
   * Should not be used when the queue is empty.
   */
  protected NodeScorer top() {
    return topHSN.scorer;
  }

  /**
   * Return the current document
   */
  public int doc() {
    return size == 0 ? DocsAndNodesIterator.NO_MORE_DOC : topHSN.doc;
  }

  /**
   * Return the current node
   */
  public IntsRef node() {
    return size == 0 ? DocsAndNodesIterator.NO_MORE_NOD : topHSN.node;
  }

  /**
   * Count the number of subscorers that provide the match in the current node,
   * and sum their score.
   *

   * Counting the number of matchers within a node during node iteration is not
   * possible as it will require to cache the latest top node. This would have
   * required a copy of the array node since array node are reused in the
   * {@link DocsNodesAndPositionsEnum}.
   *

   * Iterating over the elements of the queue enables us to save such a array
   * copy.
   *
   * @see #nrMatchersInNode()
   * @see #scoreInNode()
   */
  protected void countAndSumMatchers() throws IOException {
    if (nrMatchersInNode < 0) { // count and sum not done
      nrMatchersInNode = 1; // init counter at 1 to include the top
      scoreInNode = topHSN.scorer.scoreInNode();
      // perform recursive traversal of the heap
      this.computeSumRecursive(1);
    }
  }

  /**
   * Perform a traversal of the heap binary tree using recursion. Given a node,
   * visit its children and check if their subscorer is equivalent to the least
   * subscorer. If the subscorer is equivalent, it increments the number of
   * matchers, sum its score with the current score, and recursively visit its
   * two children.
   */
  private final void computeSumRecursive(final int root) throws IOException {
    final int i1 = (root << 1); // index of first child node
    final int i2 = (root << 1) + 1; // index of second child node

    if (i1 <= size) {
      final HeapedScorerNode child1 = heap[i1];
      if (topHSN.doc == child1.doc && topHSN.node.intsEquals(child1.node)) {
        nrMatchersInNode++;
        scoreInNode += child1.scorer.scoreInNode();
        this.computeSumRecursive(i1);
      }
    }

    if (i2 <= size) {
      final HeapedScorerNode child2 = heap[i2];
      if (topHSN.doc == child2.doc && topHSN.node.intsEquals(child2.node)) {
        nrMatchersInNode++;
        scoreInNode += child2.scorer.scoreInNode();
        this.computeSumRecursive(i2);
      }
    }
  }

  /**
   * Return the number of subscorers that provide the match in the current node.
   *

   * NOTE: {@link #countAndSumMatchers()} must be called first before.
   */
  public int nrMatchersInNode() {
    return nrMatchersInNode;
  }

  /**
   * Return the sum of the score of the subscorers that provide the match in
   * the current node.
   *

   * NOTE: {@link #countAndSumMatchers()} must be called first before.
   */
  public float scoreInNode() {
    return scoreInNode;
  }

  /**
   * Move all the scorers (including the top scorer) that have document
   * equals to the top document. If one of the subscorer is exhausted,
   * removes the scorer.
   *
   * @return If the least scorer is exhausted, return false.
   */
  public final boolean nextCandidateDocumentAndAdjustElsePop() throws IOException {
    if (topHSN != null) {
      final int currentDocument = topHSN.doc;

      while (size > 0 && topHSN.doc == currentDocument) {
        this.checkAdjustElsePop(topHSN.scorer.nextCandidateDocument());
      }

      // reset nrMatchersInNode
      nrMatchersInNode = -1;

      // no more doc when queue empty
      return (size > 0);
    }
    else {
      return false;
    }
  }

  /**
   * Move all the scorers that have document equals to the top document to the
   * next node and adjust the heap.
   *
   * @return If the least scorer has no more nodes, returns false.
   */
  public final boolean nextNodeAndAdjust() throws IOException {
    /*
     * TODO: stecam: I had a NPE in this method with topHSN. However,
     * I cannot reproduce it. Try to find the case it does occur.
     */
    // count number of scorers having the same document and node
    // counting the number of scorers and then performing the iterations of
    // all the scorers allows to avoid a node array copy (i.e., current node cache)
    if (size > 0 && nrMatchersInNode < 0) {
      this.countAndSumMatchers();
    }

    // Move the scorers to the next node
    for (int i = 0; i < nrMatchersInNode; i++) {
      topHSN.scorer.nextNode();
      this.adjustTop();
    }

    // reset nrMatchersInNode
    nrMatchersInNode = -1;
    // if top node has sentinel value, it means that there is no more nodes
    return this.node() != DocsAndNodesIterator.NO_MORE_NOD;
  }

  /**
   * Move all the scorers to the candidate document beyond (see NOTE below) the
   * current whose number is greater than or equal to target.
   *

   * NOTE: when  target ≤ current implementations must
   * not advance beyond their current {@link #doc()}.
   *
   * @return If the least scorer has no more nodes, returns false.
   */
  public final boolean skipToCandidateAndAdjustElsePop(final int target)
  throws IOException {
    if (topHSN != null) {
      while (size > 0 && topHSN.doc < target) {
        this.checkAdjustElsePop(topHSN.scorer.skipToCandidate(target));
      }

      // no more doc when queue empty
      return (size > 0);
    }
    else {
      return false;
    }
  }

  /**
   * If condition is true, then pop the top and adjust the heap.
   */
  private boolean checkAdjustElsePop(final boolean cond) {
    if (cond) {
      topHSN.adjust();
    }
    else { // pop
      heap[1] = heap[size]; // move last to first
      heap[size] = null;
      size--;
    }
    this.downHeap();
    return cond;
  }

  /**
   * Should be called when the scorer at top changes of values.
   */
  public final void adjustTop() {
    topHSN.adjust();
    this.downHeap();
  }

  /**
   * Compares the given scorer with the specified heaped scorer for order.
   * Returns a negative integer, zero, or a positive integer as this scorer is
   * less than, equal to, or greater than the specified heaped scorer.
   */
  private int compareTo(final NodeScorer scorer, final NodeScorer other) {
    // compare docs
    final int doc = scorer.doc();
    final int otherDoc = other.doc();

    if (doc != otherDoc) {
      return doc - otherDoc;
    }

    // compare nodes
    return NodeUtils.compare(scorer.node(), other.node());
  }

  /**
   * Returns the number of scorers currently stored in the
   * NodeDisjunctionScorerQueue.
   **/
  public final int size() {
    return size;
  }

  /** Removes all entries from the NodeDisjunctionScorerQueue. */
  public final void clear() {
    for (int i = 0; i <= size; i++) {
      heap[i] = null;
    }
    size = 0;
  }

  private final void upHeap() {
    int i = size;
    final HeapedScorerNode node = heap[i]; // save bottom node
    int j = i >>> 1;
    while ((j > 0) && (this.compareTo(node.scorer, heap[j].scorer) < 0)) {
      heap[i] = heap[j]; // shift parents down
      i = j;
      j = j >>> 1;
    }
    heap[i] = node; // install saved node
    topHSN = heap[1];
  }

  private final void downHeap() {
    int i = 1;
    final HeapedScorerNode node = heap[i]; // save top node
    int j = i << 1; // find smaller child
    int k = j + 1;
    if ((k <= size) && (this.compareTo(heap[k].scorer, heap[j].scorer) < 0)) {
      j = k;
    }
    while ((j <= size) && (this.compareTo(heap[j].scorer, node.scorer) < 0)) {
      heap[i] = heap[j]; // shift up child
      i = j;
      j = i << 1;
      k = j + 1;
      if (k <= size && (this.compareTo(heap[k].scorer, heap[j].scorer) < 0)) {
        j = k;
      }
    }
    heap[i] = node; // install saved node
    topHSN = heap[1];
  }

}


text:
package br.mp.mpt.prt8.severino.entity;

import static javax.persistence.FetchType.LAZY;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;

import com.fasterxml.jackson.annotation.JsonView;

import br.mp.mpt.prt8.severino.validators.CadastrarVeiculo;
import br.mp.mpt.prt8.severino.validators.SelecionarVeiculo;

/**
 * The persistent class for the veiculo database table.
 *
 */
@Entity
@Table(name = "veiculo")
public class Veiculo extends AbstractEntity<String> {

	private static final long serialVersionUID = 4430369112378957922L;
	private static final String FORMATO_DESCRICAO = "%s - %s %s (%s)";
	private static final String FORMATO_MOTORISTA = "%s - " + FORMATO_DESCRICAO;

	@Id
	@Column(name = "placa", unique = true, nullable = false, length = 7)
	@NotNull(groups = { CadastrarVeiculo.class, SelecionarVeiculo.class })
	@Pattern(regexp = "[A-Z]{3}\\d{4}", message = "O formato da placa deve ser xxx0000", groups = CadastrarVeiculo.class)
	@JsonView(DataTablesOutput.View.class)
	private String id;

	@Column(nullable = false, length = 10)
	@NotNull(groups = CadastrarVeiculo.class)
	@Size(max = 10, groups = CadastrarVeiculo.class)
	@JsonView(DataTablesOutput.View.class)
	private String cor;

	@Column(nullable = false, length = 30)
	@NotNull(groups = CadastrarVeiculo.class)
	@Size(max = 30, groups = CadastrarVeiculo.class)
	@JsonView(DataTablesOutput.View.class)
	private String marca;

	@Column(nullable = false, length = 30)
	@Size(max = 30, groups = CadastrarVeiculo.class)
	@NotNull(groups = CadastrarVeiculo.class)
	@JsonView(DataTablesOutput.View.class)
	private String modelo;

	@Column(name = "viatura_mp", nullable = false)
	@JsonView(DataTablesOutput.View.class)
	private boolean viaturaMp;

	@Column(nullable = false)
	@JsonView(DataTablesOutput.View.class)
	private boolean ativo = true;

	// bi-directional many-to-one association to Motorista
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "id_motorista")
	@JsonView(DataTablesOutput.View.class)
	private Motorista motorista;

	@ManyToOne(fetch = LAZY)
	@JoinColumn(name = "id_local", nullable = false, updatable = false)
	private Local local;

	@Override
	public String getId() {
		return this.id;
	}

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

	public String getCor() {
		return this.cor;
	}

	public void setCor(String cor) {
		this.cor = cor;
	}

	public String getMarca() {
		return this.marca;
	}

	public void setMarca(String marca) {
		this.marca = marca;
	}

	public String getModelo() {
		return this.modelo;
	}

	public void setModelo(String modelo) {
		this.modelo = modelo;
	}

	public boolean getViaturaMp() {
		return this.viaturaMp;
	}

	public void setViaturaMp(boolean viaturaMp) {
		this.viaturaMp = viaturaMp;
	}

	public Motorista getMotorista() {
		return this.motorista;
	}

	public void setMotorista(Motorista motorista) {
		this.motorista = motorista;
	}

	/**
	 * Descrição completa do veículo.
	 *
	 * @return
	 */
	public String getDescricaoCompleta() {
		return String.format(FORMATO_DESCRICAO, getId(), getMarca(), getModelo(), getCor());
	}

	/**
	 * Descrição completa do veículo com motorista.
	 *
	 * @return
	 */
	public String getDescricaoMotorista() {
		String nomeMotorista = "";
		if (getMotorista() != null) {
			nomeMotorista = getMotorista().getNome();
		}
		return String.format(FORMATO_MOTORISTA, nomeMotorista, getId(), getMarca(), getModelo(), getCor());
	}

	public boolean isAtivo() {
		return ativo;
	}

	public void setAtivo(boolean ativo) {
		this.ativo = ativo;
	}

	public Local getLocal() {
		return local;
	}

	public void setLocal(Local local) {
		this.local = local;
	}

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

function input_get($index = NULL, $default=null, $xss_clean = NULL){
    $value= get_instance()->input->get($index, $xss_clean);
    if( $value == null ){
        $value = $default;
    }
    return $value;
}
function input_post($index = NULL, $xss_clean = NULL){
    $value = get_instance()->input->post($index, $xss_clean);
    return is_string($value) ? trim($value) : $value;
}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.java;

import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;

/** Provides the fully qualified name of the primary class to invoke for java targets. */
@Immutable
@AutoCodec
public final class JavaPrimaryClassProvider implements TransitiveInfoProvider {
  private final String primaryClass;

  public JavaPrimaryClassProvider(String primaryClass) {
    this.primaryClass = primaryClass;
  }

  /**
   * Returns either the Java class whose main() method is to be invoked (when use_testrunner=0) or
   * the Java subclass of junit.framework.Test that is to be tested by the test runner class (when
   * use_testrunner=1).
   *
   * @return a fully qualified Java class name, or null if none could be determined.
   */
  public String getPrimaryClass() {
    return primaryClass;
  }
}


text:
<?php

/* NFPlatformBundle:Security:login.html.twig */
class __TwigTemplate_b3340379966b6dbc49279af655307642c0fd69670307f717e17a2679c0e9dd84 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 2
        $this->parent = $this->loadTemplate("::layout.html.twig", "NFPlatformBundle:Security:login.html.twig", 2);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 6
    public function block_body($context, array $blocks = array())
    {
        // line 7
        echo "
  ";
        // line 9
        echo "  ";
        if ((isset($context["error"]) ? $context["error"] : null)) {
            // line 10
            echo "
";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["error"]) ? $context["error"] : null), "message", array()), "html", null, true);
            echo "

  ";
        }
        // line 12
        echo "
  ";
        // line 14
        echo "  <form action=\"";
        echo $this->env->getExtension('routing')->getPath("login_check");
        echo "\" method=\"post\" class=\"form-horizontal\">

       Login :

      <input type=\"text\" id=\"username\" name=\"_username\" value=\"";
        // line 19
        echo twig_escape_filter($this->env, (isset($context["last_username"]) ? $context["last_username"] : null), "html", null, true);
        echo "\" class=\"form-control\" placeholder=\"Identifiant\" />

        Mot de passe :

        <input type=\"password\" class=\"form-control\" placeholder=\"Mot de passe\" id=\"password\" name=\"_password\" />

          <input type=\"submit\" class=\"btn btn-default\" value=\"Connexion\" />

  </form>

";
    }

    public function getTemplateName()
    {
        return "NFPlatformBundle:Security:login.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  55 => 19,  46 => 14,  43 => 12,  37 => 10,  34 => 9,  31 => 7,  28 => 6,  11 => 2,);
    }
}


text:
layout:     post
title:      " Get the Subtitle"
subtitle:   " \" get the subtitle with Python from .srt file! \""
date:       2016-07-06
author:     "Ethan"
header-img: "img/inPost/GettheSubtitle.jpg"
tags:
    - Python
    - English
---

## Get the Subtitle

Avatar: The last Airbender, 起初是为了练习英语听力及口语而了解的一部动漫,评价很是不错,看了下来之后确实很是喜欢。从网上 Download 下来 .srt 文件,打印之的话,其中的时间行却是无用。 自己写了个小脚本将字幕提取了出来。
这部剧有三季,Download 下来三季的 zip 包,解压缩后放置在桌面上各季的文件夹中。分别新建文件夹用来保存脚本生成的 .txt 文件。

	import re
	import os

	fPath = "/Users/xing/Desktop/Avatar_The_Last_Airbender - season 1.en"
	sPath = "/Users/xing/Desktop/Avatar_The_Last_Airbender_subtitle/"

	os.chdir(fPath)
	flist = os.listdir(fPath)

	for eachFile in flist[1:]:
		with open(eachFile) as F:
			subTxt = F.read()
			subTxtList = re.findall(r'[^\n][a-zA-Z]+.*\n', subTxt)
			print subTxtList
			fullSPath = os.path.join(sPath, eachFile+'.txt')
			fileSave = open(fullSPath, 'w')
			for eachline in subTxtList[:-2]:
				fileSave.write(eachline+'\n')
			fileSave.close()

## Avatar: The last Airbender

这部剧在 IMDB 的评分:[Avatar: The Last Airbender(IMDB)](http://www.imdb.com/title/tt0417299/)

#### Basic

《最后的风之子》是由派拉蒙影业公司出品,由M·奈特·沙马兰执导,诺亚·林格、戴夫·帕特尔、妮可拉·佩尔茨、杰克逊·拉斯波恩领衔主演的奇幻片。
该片根据动画系列片《降世神通:最后的气宗》改编,讲述了世界被四大神力"气、火、水、土"支配着,其中被称为"神通"的便是世上唯一同时拥有这四种神力的人,他可以阻止邪恶的火烈国征服世界的故事。
影片于2010年7月1日在美国上映,2010年8月23日在中国内地上映。

#### BackStory

全世界被战火吞噬,没有人能够阻止无法避免的毁灭。一个世纪以来,烈火国一直在全世界开战,企图征服其它的三个部族,大气牧族、水族部落以及大地国。烈火国对于被他们强大的军力击败的村落只给了一个选择,完全投降或是彻底毁灭。当世界各地的村民徒然地试着自卫,同时也极力保护少数拥有他们部族的神力,并且能够随心所欲驾驭属于他们部族的元素的神通。但是拥有模庞大的军队以及毁灭性强大的武器的烈火国,早就消灭了地球上每一个风之子。如今他们把目标转向水族部落,准备攻下北极水族的城堡。某天,一名年轻的截水神通凯塔拉(妮可拉·佩尔茨饰)和她的哥哥苏卡(杰克逊·拉斯波恩饰)一起练习她的截水技巧,意外发现一个名字叫安的小男孩(诺亚·林格饰),但是当安展现出御气的能力,凯塔拉和苏卡发现,他们找到的不只是最后的风之子。身为被预言的降世神通-唯一能够同时拥有四大神力的人,这个小小的风之子是唯一拥有击退烈火国猛烈攻击的能力,并且最后将为饱受战火荼毒的世界带来和谐的神通王。但是他能学会其它的三大神力,成为他注定要当的英雄,并且及时拯救世界吗。

#### Wikipedia: The last Airbender

This article is about the TV series. For the 2010 film, see The Last Airbender.
Avatar: The Last Airbender
Avatar The Last Airbender logo.svg
Also known as	Avatar: The Legend of Aang
Genre
Action/Adventure
Fantasy
Comedy-drama
Created by
Michael Dante DiMartino
Bryan Konietzko
Written by
Michael Dante DiMartino
Bryan Konietzko
Aaron Ehasz
Tim Hedrick
John O'Bryan
Elizabeth Welch Ehasz
Joshua Hamilton
May Chan
Matthew Hubbard
James Eagan
Directed by
Lauren MacMullan
Dave Filoni
Giancarlo Volpe
Ethan Spaulding
Joaquim Dos Santos
Voices of
Zach Tyler Eisen
Mae Whitman
Jack DeSena
Jessie Flower
Dante Basco
Dee Bradley Baker
Jennie Kwan
Mako (Seasons 1–2)
Greg Baldwin (Season 3)
Mark Hamill
Grey DeLisle
Jason Isaacs
Clancy Brown
Composer(s)	Jeremy Zuckerman, Benjamin Wynn
Country of origin	United States
Original language(s)	English
No. of seasons	3
No. of episodes	61 (list of episodes)
Production
Executive producer(s)
Michael Dante DiMartino
Bryan Konietzko
Aaron Ehasz
Running time	22 minutes
Production company(s)
Nickelodeon Animation Studios
DR Movie
JM Animation
MOI Animation
Titmouse (opening)[1]
Release
Original network	Nickelodeon
Picture format	NTSC 4:3 (480i)
Original release	February 21, 2005 – July 19, 2008
Chronology
Followed by
Avatar: The Last Airbender (comics)
The Legend of Korra (TV series)
External links
Official website
	This article contains Chinese text. Without proper rendering support, you may see question marks, boxes, or other symbols instead of Chinese characters.
Avatar: The Last Airbender (Avatar: The Legend of Aang in some regions) is an American animated television series that aired for three seasons (referred to as "books" in each episode's title card) on Nickelodeon from 2005 to 2008. Avatar: The Last Airbender is set in an Asiatic-like world[2] in which some people are able to manipulate the classical elements by use of psychokinetic variants of Chinese martial arts, known as "bending". The show combines the styles of anime and American cartoons, and relies on the imagery of various East Asian, Inuit, Southeast Asian, South Asian, and New World societies. Therefore, whether or not the series can be considered as an anime work is often discussed.[3]

The series follows the adventures of protagonist twelve-year-old Aang and his friends, who must bring peace and unity to the world by ending the Fire Lord's war against the other three nations.[4] The pilot episode first aired on February 21, 2005,[5] and the series concluded with a widely praised two-hour episode on July 19, 2008.[6] The show is obtainable from various sources, including DVD, the iTunes Store, the Zune Marketplace, the Xbox Live Marketplace, the PlayStation Store, Netflix, Amazon Video, and the Nicktoons Network.[7]

Throughout its run, Avatar: The Last Airbender was universally acclaimed by audiences and critics alike.[8] Praises went to the art direction, humor, cultural references, characters, and themes. It was also commercially successful, garnering 5.6 million viewers on its best-rated showing and receiving high ratings in the Nicktoons lineup, even outside of its 6- to 11-year-old demographic.[4][9] The series has been nominated for and won awards from the Annie Awards, the Genesis Awards, a Primetime Emmy Award and a Peabody Award, among others. The first season's success prompted Nickelodeon to order second[10] and third[11] seasons.

In other media, the series has spawned a critically panned, but financially successful, live-action film, titled The Last Airbender, directed by M. Night Shyamalan; scaled action figures;[12] a trading card game;[13][14] three video games; stuffed animals distributed by Paramount Parks and two Lego sets. An art book was also released in mid-2010.[15][16] A sequel series, The Legend of Korra, aired from 2012 to 2014.[17]


text:
jQuery(document).ready(function($) {
    //Click anywhere on the page to get rid of lightbox window
    $('#lightbox').live('click', function() { //must use live, as the lightbox element is inserted into the DOM
        $('#lightbox').hide();
    });

});

function trigq(event) {

    var image_href = $(event).attr("url");

    if ($('#lightbox').length > 0) { // #lightbox exists

        //place href as img src value
        $('#content').html('');

        //show lightbox window - you could use .show('fast') for a transition
        $('#lightbox').show();
    }

    else { //#lightbox does not exist - create and insert (runs 1st time only)

        //create HTML markup for lightbox window
        var lightbox =
            '
' +
            '
Click to close
' +
            '
' + //insert clicked link's href into img src
            '' +
            '
' +
            '
';

        //insert lightbox HTML into page
        $('body').append(lightbox);
    }
}

if ($('#lightbox').length > 0) { // #lightbox exists

    //insert img tag with clicked link's href as src value
    $('#content').html('');

    //show lightbox window - you can use a transition here if you want, i.e. .show('fast')
    $('#lightbox').show();
}
else { //#lightbox does not exist

    //create HTML markup for lightbox window
    var lightbox =
        '
' +
        '
Click to close
' +
        '
' + //insert clicked link's href into img src
        '' +
        '
' +
        '
';

    //insert lightbox HTML into page
    $('body').append(lightbox);
}

$('#lightbox').live('click', function() {
    $('#lightbox').hide();
});


text:
<?php

/**
 * Generated 2020-08-19T18:22:34+00:00 16.0.20405.12008
 */
namespace Office365\SharePoint\WebParts;

use Office365\Runtime\ClientValue;
use Office365\Runtime\Actions\InvokePostMethodQuery;
use Office365\Runtime\ResourcePath;
use Office365\SharePoint\BaseEntity;

/**
 * Provides
 * operations to access and modify the existing Web Parts on a Web Part
 * Page, and add new ones to the Web Part Page.
 */
class LimitedWebPartManager extends BaseEntity
{
    /**
     * Imports a Web Part from a string in the .dwp format
     * @param string $webPartXml
     * @return WebPartDefinition
     */
    public function importWebPart($webPartXml)
    {
        $payload = new ClientValue();
        $payload->setProperty("webPartXml", $webPartXml);
        $webPartDefinition = new WebPartDefinition($this->getContext());
        $qry = new InvokePostMethodQuery($this, "ImportWebPart", null, null, $payload);
        $this->getContext()->addQueryAndResultObject($qry, $webPartDefinition);
        return $webPartDefinition;
    }
    /**
     * @return WebPartDefinitionCollection
     */
    public function getWebParts()
    {
        return $this->getProperty("WebParts",
            new WebPartDefinitionCollection($this->getContext(),
                new ResourcePath("WebParts", $this->getResourcePath())));
    }
    /**
     * Specifies
     * whether the Web Part Page
     * contains one or more personalized Web Parts.
     * Its value
     * MUST be "true" if both the personalization scope
     * of the Web Part Page is "User" and the Web Part Page contains one or
     * more personalized Web Parts; otherwise, it MUST be "false".
     * @return bool
     */
    public function getHasPersonalizedParts()
    {
        return $this->getProperty("HasPersonalizedParts");
    }
    /**
     * Specifies
     * whether the Web Part Page
     * contains one or more personalized Web Parts.
     * Its value
     * MUST be "true" if both the personalization scope
     * of the Web Part Page is "User" and the Web Part Page contains one or
     * more personalized Web Parts; otherwise, it MUST be "false".
     * @var bool
     */
    public function setHasPersonalizedParts($value)
    {
        $this->setProperty("HasPersonalizedParts", $value, true);
    }
    /**
     * Specifies
     * the current personalization scope
     * of the Web Part Page.Its value
     * MUST be "User" if personalized data is loaded for the Web Parts
     * on the Web Part Page, or "Shared" if common data for all users is
     * loaded.
     * @return integer
     */
    public function getScope()
    {
        return $this->getProperty("Scope");
    }
    /**
     * Specifies
     * the current personalization scope
     * of the Web Part Page.Its value
     * MUST be "User" if personalized data is loaded for the Web Parts
     * on the Web Part Page, or "Shared" if common data for all users is
     * loaded.
     * @var integer
     */
    public function setScope($value)
    {
        $this->setProperty("Scope", $value, true);
    }
    /**
     * @return bool
     */
    public function getHasWebPartConnections()
    {
        return $this->getProperty("HasWebPartConnections");
    }
    /**
     * @var bool
     */
    public function setHasWebPartConnections($value)
    {
        $this->setProperty("HasWebPartConnections", $value, true);
    }
}


text:
001
017
018    package org.apache.commons.math3.optim.univariate;
019
020    import java.io.Serializable;
021
022    /**
023     * This class holds a point and the value of an objective function at this
024     * point.
025     * This is a simple immutable container.
026     *
027     * @version $Id: UnivariatePointValuePair.java 1364392 2012-07-22 18:27:12Z tn $
028     * @since 3.0
029     */
030    public class UnivariatePointValuePair implements Serializable {
031        /** Serializable version identifier. */
032        private static final long serialVersionUID = 1003888396256744753L;
033        /** Point. */
034        private final double point;
035        /** Value of the objective function at the point. */
036        private final double value;
037
038        /**
039         * Build a point/objective function value pair.
040         *
041         * @param point Point.
042         * @param value Value of an objective function at the point
043         */
044        public UnivariatePointValuePair(final double point,
045                                        final double value) {
046            this.point = point;
047            this.value = value;
048        }
049
050        /**
051         * Get the point.
052         *
053         * @return the point.
054         */
055        public double getPoint() {
056            return point;
057        }
058
059        /**
060         * Get the value of the objective function.
061         *
062         * @return the stored value of the objective function.
063         */
064        public double getValue() {
065            return value;
066        }
067    }


text:
package it.unibz.inf.ontop.rdf4j.repository;

import com.google.common.collect.ImmutableList;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import org.eclipse.rdf4j.query.Binding;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.sql.SQLException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Checks whether the order of variables in the returned binding set is identical to the order in the SPARQL query
 * (in particular, may differ from the natural ordering of variables)
 * Reproduces issue #291
 */
public class RDF4JVariableOrderingTest extends AbstractRDF4JTest {
    private static final String CREATE_DB_FILE = "/var-order/var-order-create.sql";
    private static final String MAPPING_FILE = "/var-order/var-order.obda";

    @BeforeClass
    public static void before() throws IOException, SQLException {
        initOBDA(CREATE_DB_FILE, MAPPING_FILE);
    }

    @AfterClass
    public static void after() throws SQLException {
        release();
    }

    @Test
    public void testVariableOrdering() {
        String query = "" +
                "PREFIX : <http://example.org/>\n"+
                "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"+
                "SELECT  ?i ?v ?l\n" +
                "WHERE {\n" +
                "  ?i rdfs:label ?l .\n" +
                "  ?i :value ?v \n" +
                "}";

        TupleQueryResult result = evaluate(query);
        assertTrue(result.hasNext());
        BindingSet bindingSet = result.next();
        assertEquals(
                ImmutableList.of("i", "v", "l"),
                ImmutableList.copyOf(bindingSet.iterator()).stream()
                        .map(Binding::getName)
                        .collect(ImmutableCollectors.toList())
        );
        result.close();
    }
}


text:
package org.jitsi.impl.neomedia.transform;

/**
 * A helper class that can be used to track references to an object. This
 * class is not thread-safe.
 *
 * @author George Politis
 * @author Lyubomir Marinov
 */
class RefCount<T>
{
    private final T referent;

    private int refCount;

    public RefCount(T referent)
    {
        this.referent = referent;
        this.refCount = 0;
    }

    public void increase()
    {
        refCount++;
    }

    public void decrease()
    {
        refCount--;
    }

    public int get()
    {
        return this.refCount;
    }

    public T getReferent()
    {
        return this.referent;
    }
}


text:
<?php

namespace Riak\Client\Core\Query\Func;

/**
 * An Anonymous JS function.
 *
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 */
class AnonymousJsFunction implements RiakFunction
{
    /**
     * @var string
     */
    private $source;

    /**
     * @param string $source
     */
    public function __construct($source)
    {
        $this->source = $source;
    }

    /**
     * @return string
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * {@inheritdoc}
     */
    public function jsonSerialize()
    {
        return [
            'language' => 'javascript',
            'source'   => $this->source,
        ];
    }
}


text:
package com.strider.datadefender.extensions;

import com.strider.datadefender.anonymizer.functions.Core;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Matthew Eaton
 */
@Log4j2
public class BiographicFunctions extends Core {

    /**
     * Algorithm is taken from https://en.wikipedia.org/wiki/Social_Insurance_Number
     * @param sin
     * @return boolean true, if SIN is valid, otherwise false
     */
    public static boolean isValidSIN(final String sin) {
        boolean valid = false;

        if (sin.length() < 9) {
            log.debug("SIN length is < 9");

            return valid;
        }

        if (!StringUtils.isNumeric(sin)) {
            log.debug("SIN " + sin + " is not number");

            return valid;
        }

        final int[]         sinArray   = new int[sin.length()];
        final int[]         checkArray = {
            1, 2, 1, 2, 1, 2, 1, 2, 1
        };
        final List<Integer> sinList    = new ArrayList();

        for (int i = 0; i < 9; i++) {
            sinArray[i] = Integer.valueOf(sin.substring(i, i + 1));
            sinArray[i] = sinArray[i] * checkArray[i];
        }

        int sum = 0;

        for (int i = 0; i < 9; i++) {
            final String tmp = String.valueOf(sinArray[i]);

            if (tmp.length() == 1) {
                sinList.add(Integer.valueOf(tmp));
                sum += Integer.valueOf(tmp);
            } else {
                sinList.add(Integer.valueOf(tmp.substring(0, 1)));
                sum += Integer.valueOf(tmp.substring(0, 1));
                sinList.add(Integer.valueOf(tmp.substring(1, 2)));
                sum += Integer.valueOf(tmp.substring(1, 2));
            }
        }

        if ((sum % 10) == 0) {
            valid = true;
        }

        return valid;
    }
}


text:
//
//  XGSTaskSource.h
//  GridStuffer
//
//  Created by Charles Parnot on 5/12/05.
//  Copyright 2005, 2006, 2007, 2008 Charles Parnot. All rights reserved.
//

/* GRIDSTUFFER_LICENSE_START */
/* This file is part of GridStuffer. GridStuffer is free software; you can redistribute it and/or modify it under the terms of the Berkeley Software Distribution (BSD) Modified License.*/
/* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 - Neither the name of the owner Charles Parnot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* GRIDSTUFFER_LICENSE_END */

@class GEZMetaJob;
@class XGSInputInterface;
@class XGSOutputInterface;
@class XGSValidator;

@interface XGSTaskSource : NSManagedObject
{
	NSDictionary *prototypeCommandDictionary;
	NSDictionary *prototypeShortcutDictionary;
}

- (XGSInputInterface *)inputInterface;
- (XGSValidator *)validator;
- (XGSOutputInterface *)outputInterface;

//MetaJob data source methods
- (unsigned int)numberOfTasksForMetaJob:(GEZMetaJob *)aJob;
- (id)metaJob:(GEZMetaJob *)metaJob taskAtIndex:(unsigned int)taskIndex;
- (BOOL)metaJob:(GEZMetaJob *)metaJob validateTaskAtIndex:(int)taskIndex results:(NSDictionary *)results;

@end


text:
{% extends "securedpi/base.html" %}
{% block body %}

Activation complete

Back to LogIn Page

{% endblock %}


text:
.. _graphs:

Task Graphs
===========

Internally, Dask encodes algorithms in a simple format involving Python dicts,
tuples, and functions. This graph format can be used in isolation from the
dask collections. Working directly with dask graphs is rare, though, unless you intend
to develop new modules with Dask.  Even then, :doc:`dask.delayed <delayed>` is
often a better choice. If you are a *core developer*, then you should start here.

.. toctree::
   :maxdepth: 1

   spec.rst
   custom-graphs.rst
   optimize.rst
   graph_manipulation.rst
   custom-collections.rst
   high-level-graphs.rst

Motivation
----------

Normally, humans write programs and then compilers/interpreters interpret them
(for example, ``python``, ``javac``, ``clang``).  Sometimes humans disagree with how
these compilers/interpreters choose to interpret and execute their programs.
In these cases, humans often bring the analysis, optimization, and execution of
code into the code itself.

Commonly a desire for parallel execution causes this shift of responsibility
from compiler to human developer.  In these cases, we often represent the
structure of our program explicitly as data within the program itself.

A common approach to parallel execution in user-space is *task scheduling*.  In
task scheduling we break our program into many medium-sized tasks or units of
computation, often a function call on a non-trivial amount of data.  We
represent these tasks as nodes in a graph with edges between nodes if one task
depends on data produced by another.  We call upon a *task scheduler* to
execute this graph in a way that respects these data dependencies and leverages
parallelism where possible, so multiple independent tasks can be run
simultaneously.

|

.. figure:: images/map-reduce-task-scheduling.svg
   :scale: 40%

   There are a number of methods for task scheduling, including embarrassingly parallel, MapReduce, and full task scheduling.

|

Many solutions exist.  This is a common approach in parallel execution
frameworks.  Often task scheduling logic hides within other larger frameworks
(e.g. Luigi, Storm, Spark, IPython Parallel, etc.) and so is often reinvented.
Dask is a specification that encodes full task scheduling with minimal incidental
complexity using terms common to all Python projects, namely, dicts, tuples,
and callables.  Ideally this minimum solution is easy to adopt and understand
by a broad community.

Example
-------

Consider the following simple program:

.. code-block:: python

   def inc(i):
       return i + 1

   def add(a, b):
       return a + b

   x = 1
   y = inc(x)
   z = add(y, 10)

We encode this as a dictionary in the following way:

.. code-block:: python

   d = {'x': 1,
        'y': (inc, 'x'),
        'z': (add, 'y', 10)}

Which is represented by the following Dask graph:

.. image:: _static/dask-simple.png
   :height: 400px
   :alt: A simple dask dictionary

|

While less pleasant than our original code, this representation can be analyzed
and executed by other Python code, not just the CPython interpreter.  We don't
recommend that users write code in this way, but rather that it is an
appropriate target for automated systems.  Also, in non-toy examples, the
execution times are likely much larger than for ``inc`` and ``add``, warranting
the extra complexity.

Schedulers
----------

The Dask library currently contains a few schedulers to execute these
graphs.  Each scheduler works differently, providing different performance
guarantees and operating in different contexts.  These implementations are not
special and others can write different schedulers better suited to other
applications or architectures easily.  Systems that emit dask graphs (like
Dask Array, Dask Bag, and so on) may leverage the appropriate scheduler for
the application and hardware.

Task Expectations
-----------------

When a task is submitted to Dask for execution, there are a number of assumptions
that are made about that task.

Don't Modify Data In-Place
~~~~~~~~~~~~~~~~~~~~~~~~~~

In general, tasks with side-effects that alter the state of a future in-place
are not recommended. Modifying data that is stored in Dask in-place can have
unintended consequences. For example, consider a workflow involving a Numpy
array:

.. code-block:: python

   from dask.distributed import Client
   import numpy as np

   client = Client()
   x = client.submit(np.arange, 10)  # [0, 1, 2, 3, ...]

   def f(arr):
       arr[arr > 5] = 0  # modifies input directly without making a copy
       arr += 1          # modifies input directly without making a copy
       return arr

   y = client.submit(f, x)

In the example above Dask will update the values of the Numpy array
``x`` in-place.  While efficient, this behavior can have unintended consequences,
particularly if other tasks need to use ``x``, or if Dask needs to rerun this
computation multiple times because of worker failure.

Avoid Holding the GIL
~~~~~~~~~~~~~~~~~~~~~

Some Python functions that wrap external C/C++ code can hold onto the GIL,
which stops other Python code from running in the background.  This is
troublesome because while Dask workers run your function, they also need to
communicate to each other in the background.

If you wrap external code then please try to release the GIL.  This is usually
easy to do if you are using any of the common solutions to code-wrapping like
Cython, Numba, ctypes or others.


text:
typedef void (*mpxs_special_list_do_t)(pTHX_ modperl_modglobal_key_t *,
                                       const char *, I32);

static int mpxs_special_list_do(pTHX_ const char *name,
                                SV *package,
                                mpxs_special_list_do_t func)
{
    STRLEN packlen;
    char *packname;
    modperl_modglobal_key_t *gkey = modperl_modglobal_lookup(aTHX_ name);

    if (!gkey) {
        return FALSE;
    }

    packname = SvPV(package, packlen);

    func(aTHX_ gkey, packname, packlen);

    return TRUE;
}

static
MP_INLINE int mpxs_ModPerl__Global_special_list_call(pTHX_ const char *name,
                                                     SV *package)
{
    return mpxs_special_list_do(aTHX_ name, package,
                                modperl_perl_global_avcv_call);
}

static
MP_INLINE int mpxs_ModPerl__Global_special_list_clear(pTHX_ const char *name,
                                                      SV *package)
{
    return mpxs_special_list_do(aTHX_ name, package,
                                modperl_perl_global_avcv_clear);
}

static
MP_INLINE int mpxs_ModPerl__Global_special_list_register(pTHX_
                                                         const char *name,
                                                         SV *package)
{
    return mpxs_special_list_do(aTHX_ name, package,
                                modperl_perl_global_avcv_register);
}

/*
 * Local Variables:
 * c-basic-offset: 4
 * indent-tabs-mode: nil
 * End:
 */


text:
var beforeEach = function() {
  DispatcherHelper = new MeteorFlux.DispatcherHelper();
};

Tinytest.add(
  'MeteorFlux - Dispatcher Blaze Helper - _dispatch tests',
  function(test) {
    beforeEach();

    // Data going in.
    var that = { someData: 'data' };
    var event = {
      preventDefault: function() {},
      stopImmediatePropagation: function() {},
      currentTarget: { dataset: {
        actionType: 'SOMETHING_HAPPENED',
        actionId: '1234',
        actionUserName: 'John'
    }}};
    var template = { someOtherData: 'otherData' };

    // Data coming out.
    var action = {
      type: 'SOMETHING_HAPPENED',
      context: that,
      template: template,
      event: event,
      id: '1234',
      userName: 'John'
    };

    var result = null;
    Dispatcher.register(function(payload){
      result = payload;
    });

    DispatcherHelper._dispatch.call(that, event, template);

    test.isTrue(_.isEqual(result, action));
  }
);


text:
function calculateRow(objIdStr)
{
	var tbody = $("#"+objIdStr+" tbody tr");
	$.each(tbody,function(i,tr){
		if(i>=2)
		{
			$(tr).find("SPAN:first-child").text(i-1);
		}

	})

}

function addRow(objIdStr)
{

	//最后一个tr
	var lastTR = $("#"+objIdStr+" tr:last-child");
	var selectedObj = $("#"+objIdStr+" tr:nth-child(2)").clone();
	var trArr = document.getElementById(objIdStr).getElementsByTagName("TR");
	var trInnerHTML ;
	for(var i=0;i<trArr.length;i++)
	{
		if(trArr[i].style.display.toLowerCase()=="none")
		{
			trInnerHTML = trArr[i].innerHTML;
			break;
		}
	}
	if(trInnerHTML=="" || trInnerHTML.length==0)
	{
		return;
	}

	lastTR.after("<tr>"+trInnerHTML+"</tr>");
	calculateRow(objIdStr);
}

function add2Row(objIdStr1,objIdStr2){
	addRow(objIdStr1);
	addRow(objIdStr2);

}

function deleteCurrentRow(obj,tableId)
{
	if(obj)
	{
		$(obj).parent().parent().remove();
		calculateRow(tableId);
	}
}
function deleteSubCurrentRow(trNo,tableId)
{
	if(trNo)
	{
		$("#"+tableId).find("tr").eq(trNo).remove();
		calculateRow(tableId);
	}
}

function delete2CurrentRow(obj,tableId1,tableId2)
{
	var trNo=$(obj).parent().parent().parent().find("tr").index($(obj).parent().parent());

	deleteSubCurrentRow(trNo,tableId1);
	deleteSubCurrentRow(trNo,tableId2)
}


text:
using namespace cv;

void applyFilter(Mat image){
	Mat filteredImage,element;
	int kernel_size=3,erosion_size=1;//aperture linear size; it must be odd and greater than 1

	element = getStructuringElement( MORPH_RECT,
        						     Size( 2*erosion_size + 1, 2*erosion_size+1 ),
	                                 Point( erosion_size, erosion_size ) );
	erode(image, filteredImage,element);
	displayImage("Min Filtered Image",filteredImage);
	waitKey(0);
	cvDestroyWindow("Min Filtered Image");

	dilate(image, filteredImage,element);
	displayImage("Max Filtered Image",filteredImage);
	waitKey(0);
	cvDestroyWindow("Max Filtered Image");

	boxFilter(image, filteredImage, -1, Size(kernel_size, kernel_size),
			  Point(-1, -1), true, BORDER_DEFAULT);
	displayImage("Average Filtered Image",filteredImage);
	waitKey(0);
	cvDestroyWindow("Average Filtered Image");

	medianBlur(image,filteredImage,kernel_size );
	displayImage("Median Filtered Image",filteredImage);
	waitKey(0);
	cvDestroyWindow("Median Filtered Image");

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>sample-parent</artifactId>
	<name>Sample (Parent)</name>
	<packaging>pom</packaging>

	<parent>
		<groupId>com.evernote</groupId>
		<artifactId>android-sdk-parent</artifactId>
        <version>1.1.2</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<modules>
		<module>HelloEDAM</module>
	</modules>
</project>


text:
#ifndef __ASM_SH_CACHE_H
#define __ASM_SH_CACHE_H
#ifdef __KERNEL__

#include <asm/cpu/cache.h>

#define SH_CACHE_VALID		1
#define SH_CACHE_UPDATED	2
#define SH_CACHE_COMBINED	4
#define SH_CACHE_ASSOC		8

#define L1_CACHE_BYTES		(1 << L1_CACHE_SHIFT)
#define SMP_CACHE_BYTES		L1_CACHE_BYTES

#define L1_CACHE_ALIGN(x)	(((x)+(L1_CACHE_BYTES-1))&~(L1_CACHE_BYTES-1))

#ifndef __ASSEMBLY__
struct cache_info {
	unsigned int ways;		/* Number of cache ways */
	unsigned int sets;		/* Number of cache sets */
	unsigned int linesz;		/* Cache line size (bytes) */

	unsigned int way_size;		/* sets * line size */

	/*
	 * way_incr is the address offset for accessing the next way
	 * in memory mapped cache array ops.
	 */
	unsigned int way_incr;
	unsigned int entry_shift;
	unsigned int entry_mask;

	/*
	 * Compute a mask which selects the address bits which overlap between
	 * 1. those used to select the cache set during indexing
	 * 2. those in the physical page number.
	 */
	unsigned int alias_mask;

	unsigned int n_aliases;		/* Number of aliases */

	unsigned long flags;
};
#endif /* __ASSEMBLY__ */
#endif /* __KERNEL__ */
#endif /* __ASM_SH_CACHE_H */


text:
import {Component} from "angular2/core";
import {FamiliaListaComponent} from "../familia/familia-lista.component";
import {FamiliaDetalhesComponent} from "../familia/familia-detalhes.component";
import {RouteConfig, ROUTER_DIRECTIVES} from "angular2/router";

@Component({
    selector: "my-app",
    templateUrl: "app/paginas/principal/app.html",
    directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    { path: "/", name: "Familias", component: FamiliaListaComponent, useAsDefault: true },
    { path: "familia/:id", name: "FamiliaDetalhes", component: FamiliaDetalhesComponent }
])

export class AppComponent {

}


text:
struct file
{
	FILE* m_file;
	const char* m_path;
	uint m_references;
};

file* open_file(const char* path, bool append);
void  close_file(file* file);
void  clear_file(file* file);
void  append_file(file* file, const char* str);
void  overwrite_file(file* file, const char* str);
file* create_file(const char* path);

#endif


text:
<resources>
    <string name="app_name">ddu</string>
    <string name="action_settings">Settings</string>
    <string name="section_format">Hello World from section: %1$d</string>

    <string name="main_tab_study">学习</string>
    <string name="main_tab_work">工作</string>
    <string name="main_tab_life">生活</string>
    <string name="main_tab_me">我</string>
    <string name="main_exit_msg">再按一次退出程序</string>

    <string name="web_refresh">刷新</string>

    <string name="common_cancel">取消</string>
    <string name="common_please_wait">请稍候…</string>
    <string name="no_install_app_store">未发现应用商店</string>

    <string name="work_program_jet_pack">JetPack</string>
    <string name="work_program_kotlin">Kotlin</string>
    <string name="work_program_java">Java</string>
    <string name="work_program_swift">Swift</string>

    <string name="life_calculator">计算器</string>
    <string name="life_calculator_house">房贷计算器</string>
    <string name="life_calculator_income">个税计算器</string>

    <string name="life_food">饮食</string>
    <string name="life_sleep">作息时间</string>

    <string name="life_food_detail">【健康小课堂】\n❤红色入心:\n\t西红柿、红萝卜、枸杞、红枣、红肉椒。\n💚绿色入肝:\n\t芹菜、波菜,空心菜,西兰花等绿色蔬菜。\n💛黄色入脾:\n\t小米,玉米粒、红薯、南瓜,土豆。\n⚫黑色入肾:\n\t黑木耳、紫菜、黑芝麻,黑米。\n⚪白色入肺:\n\t银耳、百合、山药、杏仁、白萝卜。
\n每天,五色蔬菜都用,5种颜色各一种。功效:有利于身体平衡哦[耶][耶][耶]</string>

    <string name="life_joke">笑话</string>
    <string name="life_sentiment">感悟</string>
    <string name="help">打开app</string>
    <string name="parse1">{hello} [world]</string>
    <string name="parse2">(hello) [world]</string>
    <string name="parse3">"{hello} (world)"</string>
    <string name="parset">^hello^ (world)</string>

    <string name="lockscreen_access_pattern_start">Pattern started</string>

    <string name="lockscreen_access_pattern_cleared">Pattern cleared</string>

    <string name="lockscreen_access_pattern_cell_added">Cell added</string>

    <string name="lockscreen_access_pattern_detected">Pattern completed</string>
    <string name="title_activity_main2">Main2Activity</string>
    <string name="format_count_down">%1$d 后重发</string>
    <string name="title_activity_scrolling">ScrollingActivity</string>
    <string name="large_text">
        "Material is the metaphor.\n\n"

        "A material metaphor is the unifying theory of a rationalized space and a system of motion."
        "The material is grounded in tactile reality, inspired by the study of paper and ink, yet "
        "technologically advanced and open to imagination and magic.\n"
        "Surfaces and edges of the material provide visual cues that are grounded in reality. The "
        "use of familiar tactile attributes helps users quickly understand affordances. Yet the "
        "flexibility of the material creates new affordances that supercede those in the physical "
        "world, without breaking the rules of physics.\n"
        "The fundamentals of light, surface, and movement are key to conveying how objects move, "
        "interact, and exist in space and in relation to each other. Realistic lighting shows "
        "seams, divides space, and indicates moving parts.\n\n"

        "Bold, graphic, intentional.\n\n"

        "The foundational elements of print based design typography, grids, space, scale, color, "
        "and use of imagery guide visual treatments. These elements do far more than please the "
        "eye. They create hierarchy, meaning, and focus. Deliberate color choices, edge to edge "
        "imagery, large scale typography, and intentional white space create a bold and graphic "
        "interface that immerse the user in the experience.\n"
        "An emphasis on user actions makes core functionality immediately apparent and provides "
        "waypoints for the user.\n\n"

        "Motion provides meaning.\n\n"

        "Motion respects and reinforces the user as the prime mover. Primary user actions are "
        "inflection points that initiate motion, transforming the whole design.\n"
        "All action takes place in a single environment. Objects are presented to the user without "
        "breaking the continuity of experience even as they transform and reorganize.\n"
        "Motion is meaningful and appropriate, serving to focus attention and maintain continuity. "
        "Feedback is subtle yet clear. Transitions are efficient yet coherent.\n\n"

        "3D world.\n\n"

        "The material environment is a 3D space, which means all objects have x, y, and z "
        "dimensions. The z-axis is perpendicularly aligned to the plane of the display, with the "
        "positive z-axis extending towards the viewer. Every sheet of material occupies a single "
        "position along the z-axis and has a standard 1dp thickness.\n"
        "On the web, the z-axis is used for layering and not for perspective. The 3D world is "
        "emulated by manipulating the y-axis.\n\n"

        "Light and shadow.\n\n"

        "Within the material environment, virtual lights illuminate the scene. Key lights create "
        "directional shadows, while ambient light creates soft shadows from all angles.\n"
        "Shadows in the material environment are cast by these two light sources. In Android "
        "development, shadows occur when light sources are blocked by sheets of material at "
        "various positions along the z-axis. On the web, shadows are depicted by manipulating the "
        "y-axis only. The following example shows the card with a height of 6dp.\n\n"

        "Resting elevation.\n\n"

        "All material objects, regardless of size, have a resting elevation, or default elevation "
        "that does not change. If an object changes elevation, it should return to its resting "
        "elevation as soon as possible.\n\n"

        "Component elevations.\n\n"

        "The resting elevation for a component type is consistent across apps (e.g., FAB elevation "
        "does not vary from 6dp in one app to 16dp in another app).\n"
        "Components may have different resting elevations across platforms, depending on the depth "
        "of the environment (e.g., TV has a greater depth than mobile or desktop).\n\n"

        "Responsive elevation and dynamic elevation offsets.\n\n"

        "Some component types have responsive elevation, meaning they change elevation in response "
        "to user input (e.g., normal, focused, and pressed) or system events. These elevation "
        "changes are consistently implemented using dynamic elevation offsets.\n"
        "Dynamic elevation offsets are the goal elevation that a component moves towards, relative "
        "to the component's resting state. They ensure that elevation changes are consistent "
        "across actions and component types. For example, all components that lift on press have "
        "the same elevation change relative to their resting elevation.\n"
        "Once the input event is completed or cancelled, the component will return to its resting "
        "elevation.\n\n"

        "Avoiding elevation interference.\n\n"

        "Components with responsive elevations may encounter other components as they move between "
        "their resting elevations and dynamic elevation offsets. Because material cannot pass "
        "through other material, components avoid interfering with one another any number of ways, "
        "whether on a per component basis or using the entire app layout.\n"
        "On a component level, components can move or be removed before they cause interference. "
        "For example, a floating action button (FAB) can disappear or move off screen before a "
        "user picks up a card, or it can move if a snackbar appears.\n"
        "On the layout level, design your app layout to minimize opportunities for interference. "
        "For example, position the FAB to one side of stream of a cards so the FAB won't interfere "
        "when a user tries to pick up one of cards.\n\n"
    </string>
    <string name="title_activity_scrolling1">ScrollingActivity1</string>
    <string name="title_activity_scrolling3">ScrollingActivity3</string>

    <string name="option_progress">Progress:</string>
    <string name="option_bar_color">Bar color:</string>
    <string name="option_wheel_color">Wheel color:</string>
    <string name="interpolated">Interpolated progress:</string>

    <string name="main_text">Options:</string>
    <string name="about_text">This app is for demonstrate the Material-ish progress wheel library, which provides a Material-style progress wheel compatible back to API 9. You can have indeterminate and determinate versions of the progress wheel, the later with a linear animation or a interpolated one like in the guidelines.\n\nRefer to the Github project page for more info at https://github.com/pnikosis/materialish-progress. </string>
    <string name="about">About</string>
    <string name="title_activity_scrolling2">ScrollingActivity2</string>

    <string name="one_separator">一种分割符</string>
    <string name="two_separator">二种分割符</string>
    <string name="multi_separator">多种分割符</string>
    <string name="custom_separator">自定义分割符</string>

    <string name="text_phrase_one">永生不过是场{幻梦},唯吾{所爱}不朽</string>
    <string name="text_phrase_two">何以{缘起}?何以[缘灭]?当以{剑歌}问之</string>
    <string name="text_phrase_three">凤兮{凤兮}归[故乡],遨(游)四海(求其凰)</string>

    <string name="text_phrase_custom">邂逅你,是(生生世世)的宿命</string>
    <string name="text_phrase_multi_click">众里寻他千{百度},蓦然回首,那人却在[网易]</string>

</resources>