text:
require 'bundler' # requiring the bundler
Bundler.require   # bundle our !#$#

# establishing connection to postgresql db
ActiveRecord::Base.establish_connection(
  :database => 'bee_crypt_bzz',
  :adapter => 'postgresql'
)

# this will go in ApplicationController
enable :sessions # so easy a 5year maybe could do it

# helper method to see if username exists!
# does_user_exist(params[:user_name])
def does_user_exist(username)
  user = Account.find_by(:user_name => username)
  if user
    return true
  else
    return false
  end
end

# does our user have access to something?
def authorization_check
  if session[:current_user] == nil
    redirect '/not_authorized'
  else
    return true
  end
end

# basic template routes
get '/' do
  # for any resource i want to protect...
  # i perform an authorization_check
  authorization_check
  @user_name = session[:current_user].user_name
  # return some resource
  #return {:hello => 'world'}.to_json
  erb :index
end

get '/not_authorized' do
  erb :not_authorized
end

# registration for user
get '/register' do
  erb :register
end
post '/register' do

  # check if the user someone is trying to register exists or NOT
  if does_user_exist(params[:user_name]) == true
    return {:message => 'womp, womp... user exists'}.to_json
    # return erb :view_name
  end

  # if we make this far the user does not exist
  # let's make it!
  user = Account.create(user_email: params[:user_email], user_name: params[:user_name], password: params[:password])

  p user

  #session is a hash!
  session[:current_user] = user
  # session[:sam_is_cool] = 'fuck yeah he is'
  # session[:roger_says_hi] = 'HI ROGER'

  redirect '/' # instead of calling a view to render...
  # i want to redirect to a route
end

## login
get '/login' do
  erb :login
end
post '/login' do
  user = Account.authenticate(params[:user_name], params[:password])
  if user
    session[:current_user] = user
    redirect '/'
  else
    @message = 'Your password or account is incorrect'
    erb :login
  end
end

## logout
get '/logout' do
  authorization_check
  session[:current_user] = nil
  redirect '/'
end


text:
'use strict';

import * as path from 'path';
import * as fs from 'fs';
import * as _mkdirp from 'mkdirp';
import * as Bluebird from 'bluebird';
import * as _rimraf from 'rimraf';
import * as child_process from 'child_process';
import * as http from 'http';
import * as https from 'https';

const globBase = require('glob-base');
const globby = require('globby');

Promise = require('bluebird');

const _lstat = Promise.promisify(fs.lstat);
const lstat = async (filename: string) => {
	try {
		return await _lstat(filename);
	} catch (err) {
		return null;
	}
};
const mkdirp:(dirname: string | Buffer, opts?: any)=>Bluebird<{}> = Promise.promisify(_mkdirp);
const _mkdir:(dirname: string | Buffer, opts?: any)=>Bluebird<{}> = Promise.promisify(fs.mkdir);
const rimraf:(dirname: string, opts?: any)=>Bluebird<{}> = Promise.promisify(_rimraf);
const unlink = Promise.promisify(fs.unlink);
const spawn = child_process.spawn;
const readFile:(filename: string, opts?: any)=>Bluebird<Buffer | string> = Promise.promisify(fs.readFile);
const writeFile:(filename: string, data: string | Buffer, opts?: any)=>Bluebird<{}> = Promise.promisify(fs.writeFile);
const rename = Promise.promisify(fs.rename);

const _copyFile = (source: string, dest: string) => {
	return new Promise((resolve, reject) => {
		let cbCalled = false;
		const done = (err?: Error) => {
			if (!cbCalled) {
				cbCalled = true;
				if (err) {
					reject(err);
				} else {
					resolve();
				}
			}
		};

		var rd = fs.createReadStream(source);
		rd.on("error", done);
		var wr = fs.createWriteStream(dest);
		wr.on("error", done);
		wr.on("close", done);
		rd.pipe(wr);
	});
};

const copyFile = async (source: string, dest: string, overwrite?: boolean) => {
	let dstStat = await lstat(dest);
	if (dstStat) {
		if (dstStat.isDirectory()) {
			// Write into directory
			dest = path.join(dest, path.basename(source));
			dstStat = await lstat(dest);
			if (dstStat) {
				if (dstStat.isDirectory()) {
					throw new Error(`cp: cannot overwrite directory with file: ${dest}`);
				}
			}
		}

		if (dstStat && !overwrite) {
			throw new Error(`cp: file already exists: ${dest}`);
		}
	}

	await _copyFile(source, dest);
};

export interface ICopyOpts {
	filters?: Array<string | RegExp>;
	ignoreError?: boolean;
}

const defaultCopyOpts: ICopyOpts = { filters: null, ignoreError: false };

const parseModifiers = (modifiers: string, dict: any, defaults: any = {}) => {
	let ret: any = { ...defaults };
	modifiers = modifiers.replace(/-/g, '').replace(/ /g, '');
	for (let i = 0; i < modifiers.length; i++) {
		const c = modifiers[i];
		const name = dict[c];
		if (!name) {
			throw new Error(`invalid modifier: ${c}`);
		}
		ret[name] = true;
	}
	return ret;
};

const handleErr = (err: any, ignoreError: boolean) => {
	if (ignoreError) {
		console.error(err.message || err);
	} else {
		throw new Error(err.message || err);
	}
};

// BUG: Globs break if the path has brackets in it i.e. "C:\Program Files (x86)"
export const cp: {
	(source: string, dest: string): Promise<void>;
	(source: string, dest: string, opts: ICopyOpts): Promise<void>;
	(modifiers: string, source: string, dest: string): Promise<void>;
	(modifiers: string, source: string, dest: string, opts: ICopyOpts): Promise<void>;
} = async (a: string, b: string, c?: string | ICopyOpts, d?: ICopyOpts) => {
	let modifierStr = '';
	let source = '';
	let dest = '';
	let opts: ICopyOpts = {};

	if ((!c && !d) || (typeof c !== 'string')) {
		source = a;
		dest = b;
		opts = c || {};
	} else {
		modifierStr = a;
		source = b;
		dest = c;
		opts = d || {};
	}
	opts = { ...defaultCopyOpts, ...opts };

	const modifiers = parseModifiers(modifierStr, {
		'r': 'recursive',
		'f': 'force',
	}, {
		recursive: false,
		force: false,
	});

	let files;
	let glob = globBase(source);
	if (glob.isGlob) {
		if (process.platform === 'win32' && glob.glob[0] === '\\') {
			glob.glob = glob.glob.substr(1);
		}
		let patterns = [ glob.glob ];
		if (opts.filters) {
			patterns = patterns.concat(opts.filters);
		}
		files = await globby(patterns, {
			cwd: glob.base,
		});
	} else {
		const srcStat = await lstat(source);
		if (!srcStat) {
			handleErr(`cp: file not found: ${source}`, opts.ignoreError);
			return;
		}
		if (srcStat.isFile()) {
			try {
				console.log(`cp: ${source} => ${dest}`);
				await copyFile(source, dest, modifiers.force);
			} catch (err) {
				handleErr(err, opts.ignoreError);
			}
			return;
		}

		if (!modifiers.recursive) {
			handleErr(`cp: omitting directory: ${source}`, opts.ignoreError);
			return;
		}

		glob = { base: source, isGlob: true, glob: '**' };
		let patterns = [ glob.glob ];
		if (opts.filters) {
			patterns = patterns.concat(opts.filters);
		}
		files = await globby(patterns, {
			cwd: glob.base,
		});
		let dstStat = await lstat(dest);
		if (dstStat) {
			if (!dstStat.isDirectory()) {
				handleErr(`cp: destination not a directory: ${dest}`, opts.ignoreError);
				return;
			}
			// Folder exists, create sub-folder
			dest = path.join(dest, path.basename(source));
			// Check sub-folder is not a file
			dstStat = await lstat(dest);
			if (dstStat && !dstStat.isDirectory()) {
				handleErr(`cp: destination not a directory: ${dest}`, opts.ignoreError);
				return;
			}
		}
	}

	source = glob.base;

	console.log(`cp: ${source} => ${dest}`);

	try {
		await mkdirp(dest);
	} catch (err) {
		handleErr(`cp: error creating directory: ${dest}`, opts.ignoreError);
		return;
	}

	for (let i = 0; i < files.length; i++) {
		const file = files[i];
		const srcPath = path.join(source, file);
		const dstPath = path.join(dest, file);

		const srcStat = await lstat(srcPath);
		if (srcStat.isDirectory()) {
			try {
				await mkdirp(dstPath);
			} catch (err) {
				handleErr(`cp: error creating directory: ${dstPath}`, opts.ignoreError);
				continue;
			}
		} else {
			try {
				console.log(`cp:    ${file}`);
				await copyFile(srcPath, dstPath, modifiers.force);
			} catch (err) {
				handleErr(err, opts.ignoreError);
				continue;
			}
		}
	}
};

export interface IMkdirOpts {
	ignoreError?: boolean;
	mode?: number;
}

const defaultMkdirOpts = { ignoreError: false, mode: parseInt('0777', 8) };

export const mkdir: {
	(dest: string): Promise<void>;
	(dest: string, opts: IMkdirOpts): Promise<void>;
	(modifiers: string, dest: string): Promise<void>;
	(modifiers: string, dest: string, opts: IMkdirOpts): Promise<void>;
} = async (a: string, b?: string | IMkdirOpts, c?: IMkdirOpts) => {
	let modifierStr = '';
	let dest = '';
	let opts: IMkdirOpts = {};
	if (c && (typeof b === 'string')) {
		modifierStr = a;
		dest = b;
		opts = c;
	} else if (typeof b === 'string') {
		modifierStr = a;
		dest = b;
	} else {
		dest = a;
		opts = b || {};
	}

	opts = { ...defaultMkdirOpts, ...opts };

	const modifiers = parseModifiers(modifierStr, {
		'p': 'parents',
	}, {
		parents: false,
	});

	console.log(`mkdir: ${dest}`);

	if (modifiers.parents) {
		try {
			await mkdirp(dest, { mode: opts.mode });
		} catch (err) {
			handleErr(`Directory could not be created\n\tPath: ${dest}`, opts.ignoreError);
			return;
		}
	} else {
		try {
			await _mkdir(dest, { mode: opts.mode });
		} catch (err) {
			handleErr(`Directory could not be created\n\tPath: ${dest}`, opts.ignoreError);
			return;
		}
	}
};

export interface IRmOpts {
	ignoreError?: boolean;
}

const defaultRmOpts: IRmOpts = { ignoreError: false };

export const rm: {
	(dest: string): Promise<void>;
	(dest: string, opts: IRmOpts): Promise<void>;
	(modifiers: string, dest: string): Promise<void>;
	(modifiers: string, dest: string, opts: IRmOpts): Promise<void>;
} = async (a: string, b?: string | IRmOpts, c?: IRmOpts) => {
	let modifierStr = '';
	let dest = '';
	let opts: IRmOpts = {};
	if (c && (typeof b === 'string')) {
		modifierStr = a;
		dest = b;
		opts = c;
	} else if (typeof b === 'string') {
		modifierStr = a;
		dest = b;
	} else {
		dest = a;
		opts = b || {};
	}

	opts = { ...defaultRmOpts, ...opts };

	const modifiers = parseModifiers(modifierStr, {
		'r': 'recursive',
		'f': 'force', // not used
	}, {
		recursive: false,
	});

	console.log(`rm: ${dest}`);

	try {
		if (modifiers.recursive) {
			await rimraf(dest, { glob: false });
		} else {
			await unlink(dest);
		}
	} catch (err) {
		handleErr(`Error removing file/directory: ${dest} (${err.message})`, opts.ignoreError);
	}
};

export interface IExecOpts {
	ignoreError?: boolean;
	cwd?: string;
	env?: any;
	exitCodes?: number[];
	shell?: boolean;
	silent?: boolean;
}

export interface IExecReturn {
	code: number;
	stdout: string;
	stderr: string;
}

const defaultExecOpts: IExecOpts = { ignoreError: false, exitCodes: [0], shell: true, silent: false };

export const exec = (cmd: string, args: string[] = [], opts: IExecOpts = {}): Bluebird<IExecReturn> => {
	let stdout = '';
	let stderr = '';

	return new Promise((resolve, reject) => {
		opts = { ...defaultExecOpts, ...opts };
		opts.exitCodes = opts.exitCodes || [];

		console.log(`exec: command: ${cmd}, args: ${args.join(' ')}`);

		const p = spawn(cmd, args, {
			cwd: opts.cwd || process.cwd(),
			env: opts.env || process.env,
			shell: opts.shell,
		});

		p.stdout.on('data', (data) => {
			stdout += data.toString();
			if (!opts.silent) {
				process.stdout.write(data);
			}
		});

		p.stderr.on('data', (data) => {
			stderr += data.toString();
			if (!opts.silent) {
				process.stderr.write(data);
			}
		});

		p.on('error', (err) => {
			const msg = `exec: failed to launch command: ${cmd} (${err.message})`;
			if (opts.ignoreError) {
				console.error(msg)
				resolve({
					code: 255,
					stdout,
					stderr,
				});
			} else {
				reject(new Error(msg));
			}
		});

		p.on('close', (code) => {
			if (opts.exitCodes.indexOf(code) === -1) {
				const msg = `exec: unexpected exit code: ${code}`;
				if (opts.ignoreError) {
					console.error(msg)
					resolve({
						code,
						stdout,
						stderr,
					});
				} else {
					let err: any = new Error(msg);
					err.code = code;
					reject(err);
				}
			} else {
				resolve({
					code,
					stdout,
					stderr,
				});
			}
		});
	});
};

export const cd = async (dir: string) => {
	process.chdir(dir);
};

export const sed = async (pattern: RegExp, replacement: string, filename: string) => {
	console.log(`sed: ${filename} [ ${pattern} => ${replacement} ]`);

	const contents = await readFile(filename, { encoding: 'utf8' }) as string;
	const lines = contents.split(/\r*\n/);
	const result = lines.map((line) => line.replace(pattern, replacement)).join('\n');

	await writeFile(filename, result, { encdoding: 'utf8' });
};

export const cat = async (filename: string) => {
	console.log(`cat: ${filename}`);

	const contents = await readFile(filename, { encoding: 'utf8' }) as string;
	return contents;
}

export const downloadFile = async (uri: string, filename: string) => {
	return new Promise((resolve, reject) => {
		const done = (err?: Error) => {
			if (err) {
				reject(err);
			} else {
				resolve();
			}
		};

		const file = fs.createWriteStream(filename);
		file.on('error', (err: Error) => {
			// Delete the target file
			fs.unlink(filename);
			done(err);
		});

		let requestor: any;
		if (uri.startsWith('https')) {
			requestor = https;
		} else {
			requestor = http;
		}

		const request = requestor.get(uri, (res: any) => {
			// Check if response is success
			if (res.statusCode !== 200) {
				done(new Error(`Invalid response code: ${res.statusCode}`));
				return;
			}

			res.pipe(file);

			file.on('finish', function() {
				file.close();
				done();
			});
		});

		request.on('error', (err: Error) => {
			// Delete the target file
			fs.unlink(filename);
			done(err);
		});
	});
};

export const test = async (modifierStr: string, filename: string) => {
	const modifiers = parseModifiers(modifierStr, {
		'e': 'exists',
		'd': 'directory',
		'f': 'file',
	});

	console.log(`test: ${modifierStr} ${filename}`);

	const stat = await lstat(filename);

	if (modifiers.exists) {
		console.log(`test:     exists = ${stat !== null}`);
		return stat !== null;
	}

	if (modifiers.directory) {
		console.log(`test:     directory = ${stat !== null && stat.isDirectory()}`);
		return stat !== null && stat.isDirectory();
	}

	if (modifiers.file) {
		console.log(`test:     file = ${stat !== null && stat.isFile()}`);
		return stat !== null && stat.isFile();
	}

	return false;
}

//TODO: modifiers: -f = force
export const mv = async (source: string, dest: string) => {
	console.log(`mv: ${source} => ${dest}`);

	try {
		await rename(source, dest);
	} catch (err) {
		// Different partitions, try copy/delete
		if (err.code === 'EXDEV') {
			await cp('r', source, dest);
			await rm('rf', source);
		}
	}
};

redpajama_set_name: RedPajamaGithub


text:
package com.cloud.common.storageprocessor;

import com.cloud.legacymodel.communication.command.DownloadCommand.ResourceType;
import com.cloud.legacymodel.storage.TemplateFormatInfo;
import com.cloud.legacymodel.storage.TemplateProp;
import com.cloud.model.enumeration.ImageFormat;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.storage.StorageLayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TemplateLocation {
    public final static String Filename = "template.properties";
    private static final Logger s_logger = LoggerFactory.getLogger(TemplateLocation.class);
    StorageLayer _storage;
    String _templatePath;
    boolean _isCorrupted;
    ResourceType _resourceType = ResourceType.TEMPLATE;

    File _file;
    Properties _props;

    ArrayList<TemplateFormatInfo> _formats;

    public TemplateLocation(final StorageLayer storage, final String templatePath) {
        this._storage = storage;
        this._templatePath = templatePath;
        if (!this._templatePath.endsWith(File.separator)) {
            this._templatePath += File.separator;
        }
        this._formats = new ArrayList<>(5);
        this._props = new Properties();
        //TO DO - remove this hack
        if (this._templatePath.matches(".*" + "volumes" + ".*")) {
            this._file = this._storage.getFile(this._templatePath + "volume.properties");
            this._resourceType = ResourceType.VOLUME;
        } else {
            this._file = this._storage.getFile(this._templatePath + Filename);
        }
        this._isCorrupted = false;
    }

    public boolean create(final long id, final boolean isPublic, final String uniqueName) throws IOException {
        final boolean result = load();
        this._props.setProperty("id", Long.toString(id));
        this._props.setProperty("public", Boolean.toString(isPublic));
        this._props.setProperty("uniquename", uniqueName);

        return result;
    }

    public boolean load() throws IOException {
        try (final FileInputStream strm = new FileInputStream(this._file)) {
            this._props.load(strm);
        } catch (final IOException e) {
            s_logger.warn("Unable to load the template properties", e);
        }

        for (final ImageFormat format : ImageFormat.values()) {
            final String ext = this._props.getProperty(format.toString().toLowerCase());
            if (ext != null) {
                final TemplateFormatInfo info = new TemplateFormatInfo();
                info.format = format;
                info.filename = this._props.getProperty(format.toString().toLowerCase() + ".filename");
                if (info.filename == null) {
                    continue;
                }
                info.size = NumbersUtil.parseLong(this._props.getProperty(format.toString().toLowerCase() + ".size"), -1);
                this._props.setProperty("physicalSize", Long.toString(info.size));
                info.virtualSize = NumbersUtil.parseLong(this._props.getProperty(format.toString().toLowerCase() + ".virtualsize"), -1);
                this._formats.add(info);

                if (!checkFormatValidity(info)) {
                    this._isCorrupted = true;
                    s_logger.warn("Cleaning up inconsistent information for " + format);
                }
            }
        }

        if (this._props.getProperty("uniquename") == null || this._props.getProperty("virtualsize") == null) {
            return false;
        }

        return (this._formats.size() > 0);
    }

    protected boolean checkFormatValidity(final TemplateFormatInfo info) {
        return (info.format != null && info.size > 0 && info.virtualSize > 0 && info.filename != null);
    }

    public boolean purge() {
        boolean purged = true;
        final String[] files = this._storage.listFiles(this._templatePath);
        for (final String file : files) {
            final boolean r = this._storage.delete(file);
            if (!r) {
                purged = false;
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug((r ? "R" : "Unable to r") + "emove " + file);
            }
        }

        return purged;
    }

    public boolean save() {
        for (final TemplateFormatInfo info : this._formats) {
            this._props.setProperty(info.format.toString().toLowerCase(), "true");
            this._props.setProperty(info.format.toString().toLowerCase() + ".filename", info.filename);
            this._props.setProperty(info.format.toString().toLowerCase() + ".size", Long.toString(info.size));
            this._props.setProperty(info.format.toString().toLowerCase() + ".virtualsize", Long.toString(info.virtualSize));
        }
        try (final FileOutputStream strm = new FileOutputStream(this._file)) {
            this._props.store(strm, "");
        } catch (final IOException e) {
            s_logger.warn("Unable to save the template properties ", e);
            return false;
        }
        return true;
    }

    public TemplateProp getTemplateInfo() {
        final TemplateProp tmplInfo = new TemplateProp();
        tmplInfo.setId(Long.parseLong(this._props.getProperty("id")));
        tmplInfo.setInstallPath(this._templatePath + this._props.getProperty("filename")); // _templatePath endsWith /
        if (this._resourceType == ResourceType.VOLUME) {
            tmplInfo.setInstallPath(tmplInfo.getInstallPath().substring(tmplInfo.getInstallPath().indexOf("volumes")));
        } else {
            tmplInfo.setInstallPath(tmplInfo.getInstallPath().substring(tmplInfo.getInstallPath().indexOf("template")));
        }
        tmplInfo.setCorrupted(this._isCorrupted);
        tmplInfo.setPublic(Boolean.parseBoolean(this._props.getProperty("public")));
        tmplInfo.setTemplateName(this._props.getProperty("uniquename"));
        if (this._props.getProperty("virtualsize") != null) {
            tmplInfo.setSize(Long.parseLong(this._props.getProperty("virtualsize")));
        }
        if (this._props.getProperty("size") != null) {
            tmplInfo.setPhysicalSize(Long.parseLong(this._props.getProperty("size")));
        }

        return tmplInfo;
    }

    public TemplateFormatInfo getFormat(final ImageFormat format) {
        for (final TemplateFormatInfo info : this._formats) {
            if (info.format == format) {
                return info;
            }
        }

        return null;
    }

    public boolean addFormat(final TemplateFormatInfo newInfo) {
        deleteFormat(newInfo.format);

        if (!checkFormatValidity(newInfo)) {
            s_logger.warn("Format is invalid");
            s_logger.debug("Format: " + newInfo.format + " size: " + newInfo.size + " virtualsize: " + newInfo.virtualSize + " filename: " + newInfo.filename);
            s_logger.debug("format, filename cannot be null and size, virtual size should be  > 0 ");
            return false;
        }

        this._props.setProperty("virtualsize", Long.toString(newInfo.virtualSize));
        this._formats.add(newInfo);
        return true;
    }

    protected TemplateFormatInfo deleteFormat(final ImageFormat format) {
        final Iterator<TemplateFormatInfo> it = this._formats.iterator();
        while (it.hasNext()) {
            final TemplateFormatInfo info = it.next();
            if (info.format == format) {
                it.remove();
                this._props.remove(format.toString().toLowerCase());
                this._props.remove(format.toString().toLowerCase() + ".filename");
                this._props.remove(format.toString().toLowerCase() + ".size");
                this._props.remove(format.toString().toLowerCase() + ".virtualsize");
                return info;
            }
        }

        return null;
    }

    public void updateVirtualSize(final long virtualSize) {
        this._props.setProperty("virtualsize", Long.toString(virtualSize));
    }
}


text:
'use strict';
//
// compile TypeScript files
//

var	path     = require('path'),
	ts = require('gulp-typescript'),
	concat = require('gulp-concat'),
	sourcemaps = require('gulp-sourcemaps'),
	tslint = require('gulp-tslint');

module.exports = function(gulp) {

	var cfg = gulp.cfg;

	//
	// Lint all custom TypeScript files.
	//
	gulp.task('ts-lint', function () {
		console.log('linting ts files...');
		return gulp.src(cfg.fileset.ts).pipe(tslint()).pipe(tslint.report('prose'));
	});

	//
	// Compile TypeScript and include references to library and app .d.ts files.
	//
	gulp.task('ts', ['ts-lint'], function () {
		console.log('compiling ts files...');
		return gulp.src(cfg.fileset.ts)
		.pipe(sourcemaps.init()) // This means sourcemaps will be generated
		.pipe(ts(cfg.tsConfig))
		.pipe(sourcemaps.write()) // sourcemaps are added to the .js file
		.pipe(gulp.dest(path.join(cfg.dir.dist)));
	});
};


text:
module Hubspot
  class Properties

    PROPERTY_SPECS = {
      group_field_names: %w(name displayName displayOrder properties),
      field_names:       %w(name groupName description fieldType formField type displayOrder label options),
      valid_field_types: %w(textarea select text date file number radio checkbox),
      valid_types:       %w(string number bool datetime enumeration),
      options:           %w(description value label hidden displayOrder)
    }
    DEFAULT_PROPERTY = 'email'

    class << self
      # TODO: properties can be set as configuration
      # TODO: find the way how to set a list of Properties + merge same property key if present from opts
      def add_default_parameters(opts={})
        if opts.keys.map(&:to_s).include? 'property'
          opts
        else
          opts.merge(property: DEFAULT_PROPERTY)
        end
      end

      def all(path, opts={}, filter={})
        response = Hubspot::Connection.get_json(path, opts)
        filter_results(response, :groupName, filter[:include], filter[:exclude])
      end

      def groups(path, opts={}, filter={})
        response = Hubspot::Connection.get_json(path, opts)
        filter_results(response, :name, filter[:include], filter[:exclude])
      end

      def create!(path, params={})
        post_data = valid_property_params(params)
        return nil if post_data.blank?
        Hubspot::Connection.post_json(path, params: {}, body: post_data)
      end

      def update!(path, property_name, params={})
        post_data = valid_property_params(params)
        return nil if post_data.blank?
        Hubspot::Connection.put_json(path, params: { property_name: property_name }, body: post_data)
      end

      def delete!(path, property_name)
        response = Hubspot::Connection.delete_json(path, property_name: property_name)
        response.parsed_response
      end

      def create_group!(path, params={})
        post_data = valid_group_params(params)
        return nil if post_data.blank?
        Hubspot::Connection.post_json(path, params: {}, body: post_data)
      end

      def update_group!(path, group_name, params={})
        post_data = valid_group_params(params)
        return nil if post_data.blank?
        Hubspot::Connection.put_json(path, params: { group_name: group_name }, body: post_data)
      end

      def delete_group!(path, group_name)
        response = Hubspot::Connection.delete_json(path, group_name: group_name)
        response.parsed_response
      end

      def same?(src, dst)
        src_params = valid_params(src)
        dst_params = valid_params(dst)
        src_params.eql?(dst_params)
        # hash_same?(src_params, dst_params)
      end

      def valid_params(params={})
        valid_property_params(params)
      end

      private

      def filter_results(results, key, include, exclude)
        key = key.to_s
        results.select { |result|
          (include.blank? || include.include?(result[key])) &&
            (exclude.blank? || !exclude.include?(result[key]))
        }
      end

      def valid_property_params(params)
        return {} if params.blank?
        result = params.slice(*PROPERTY_SPECS[:field_names])
        result.delete('fieldType') unless check_field_type(result['fieldType'])
        result.delete('type') unless check_type(result['type'])
        result['options'] = valid_option_params(result['options'])
        result
      end

      def valid_group_params(params)
        return {} if params.blank?
        result = params.slice(*PROPERTY_SPECS[:group_field_names])
        result['properties'] = valid_property_params(result['properties']) unless result['properties'].blank?
        result
      end

      def check_field_type(val)
        return true if PROPERTY_SPECS[:valid_field_types].include?(val)
        puts "Invalid field type: #{val}"
        false
      end

      def check_type(val)
        return true if PROPERTY_SPECS[:valid_types].include?(val)
        puts "Invalid type: #{val}"
        false
      end

      def valid_option_params(options)
        return [] if options.blank?
        options.map { |o| o.slice(*PROPERTY_SPECS[:options]) }
      end
    end
  end
end


text:
using System.Linq;
using VocabInstaller.Models;

namespace VocabInstaller.ViewModels {
    public abstract class AbstractViewModel {
        protected AbstractViewModel(int itemsPerPage, int pageSkip) {
            this.ItemsPerPage = itemsPerPage;
            this.PageSkip = pageSkip;
            Page = 0;
        }

        protected AbstractViewModel() { }

        public int ItemsPerPage { get; set; }
        public int PageSkip { get; set; }
        public int ItemNum { get; set; }
        public int Page { get; set; }

        public int LastPage {
            get {
                return (ItemNum > 0) ? (ItemNum - 1) / ItemsPerPage : 0;
            }
        }

        public bool HasPrevPage(int n) {
            return 0 <= Page - n;
        }

        public bool HasNextPage(int n) {
            return (Page + n) * ItemsPerPage < ItemNum;
        }

        private IQueryable<Card> cards;
        public IQueryable<Card> Cards {
            get { return cards; }
            set {
                cards = value;
                ItemNum = cards == null ? 0 : cards.Count();
            }
        }

        public IQueryable<Card> GetCardsInPage(int? page = null) {
            int pg = page ?? Page;
            return Cards.Skip(pg * ItemsPerPage).Take(ItemsPerPage);
        }
    }
}


text:
-- phpMyAdmin SQL Dump
-- version 4.1.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: May 25, 2015 at 05:45 AM
-- Server version: 5.6.16
-- PHP Version: 5.5.11

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `merobazaar`
--

-- --------------------------------------------------------

--
-- Table structure for table `rescue_calls`
--

CREATE TABLE IF NOT EXISTS `rescue_calls` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `lat` double DEFAULT NULL,
  `lon` double DEFAULT NULL,
  `pos_acc` varchar(255) DEFAULT NULL,
  `injury` varchar(255) DEFAULT NULL,
  `trap` varchar(255) DEFAULT NULL,
  `complications` text,
  `hazards` text,
  `description` text,
  `locality` varchar(255) DEFAULT NULL,
  `street` varchar(255) DEFAULT NULL,
  `city_vdc` varchar(255) DEFAULT NULL,
  `region` varchar(255) DEFAULT NULL,
  `zip_code` varchar(255) DEFAULT NULL,
  `rescue_status` varchar(255) DEFAULT NULL,
  `call_received_date_time` datetime DEFAULT NULL,
  `call_ack_date_time` datetime DEFAULT NULL,
  `rescued_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `rescue_calls`
--

INSERT INTO `rescue_calls` (`id`, `name`, `phone`, `address`, `lat`, `lon`, `pos_acc`, `injury`, `trap`, `complications`, `hazards`, `description`, `locality`, `street`, `city_vdc`, `region`, `zip_code`, `rescue_status`, `call_received_date_time`, `call_ack_date_time`, `rescued_date_time`) VALUES
(1, 'raj', '11111', 'Timba Sirak Factory, Patan 44700, Nepal\r\n\r\n', 27.657416, 85.318379, '25', 'Minor', 'trapped_and_immobile', 'suffocating, loosing consciousness', 'fire, chemical', NULL, NULL, NULL, NULL, NULL, NULL, 'rescued', NULL, NULL, NULL),
(2, 'raja', '22222', 'Lagankhel Road, Patan 44700, Nepal', 27.659696, 85.324387, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
<?php

Simpletheme_Kirki::add_section( $section_id, array(
    'priority'       => 1001,
    'capability'     => CAPATIBILITY_EDIT_THEME_OPTIONS,
    'theme_supports' => '',
    'title'          => simpletheme_translate('Custom CSS'),
    'description'    => simpletheme_translate('Custom CSS for simpletheme'),
    'panel'          => $panel_id,
) );

Simpletheme_Kirki::add_field( THEME_TEXTDOMAIN, array(
	'type'        => 'code',
	'settings'    => 'custom_css',
	'label'       => simpletheme_esc_attr( 'Custom CSS' ),
	'section'     => $section_id,
	'default'     => sprintf( "/*\n%s\n*/", simpletheme_translate( "You can add your own CSS here." ) ),
	'priority'    => 10,
	'choices'     => array(
		'language' => 'css',
		'theme'    => 'monokai',
		'height'   => 250,
	),
) );


text:
using UnityEngine;
using System.Collections;

public class DifferentStartHandler : MonoBehaviour {

	// Use this for initialization
	void Start () {
        this.GetComponent<PhenoSpeed>().setDefaultFlagellaCount(0);
	}

	// Update is called once per frame
	void Update () {

	}
}


text:
define('dataservice.session',
    ['amplify'],
    function (amplify) {
        var
            init = function () {

                amplify.request.define('sessions', 'ajax', {
                    url: '/api/sessions',
                    dataType: 'json',
                    type: 'GET'
                });

                // Pass Resource Id, Request Type, and Settings
                amplify.request.define('session-briefs', 'ajax', {
                    url: '/api/sessionbriefs',
                    dataType: 'json',
                    type: 'GET'
                    //cache: true
                    //cache: 60000 // 1 minute
                    //cache: 'persist'
                });

                amplify.request.define('session', 'ajax', {
                    url: '/api/sessions/{id}',
                    dataType: 'json',
                    type: 'GET'
                });

                amplify.request.define('sessionUpdate', 'ajax', {
                    url: '/api/sessions',
                    dataType: 'json',
                    type: 'PUT',
                    contentType: 'application/json; charset=utf-8'
                });
            },

            getSessions = function (callbacks) {
                return amplify.request({
                    resourceId: 'sessions',
                    success: callbacks.success,
                    error: callbacks.error
                });
            },

            getSessionBriefs = function (callbacks) {
                return amplify.request({
                    resourceId: 'session-briefs',
                    success: callbacks.success,
                    error: callbacks.error
                });
            },

            getSession = function (callbacks, id) {
                return amplify.request({
                    resourceId: 'session',
                    data: { id: id },
                    success: callbacks.success,
                    error: callbacks.error
                });
            },

            updateSession = function (callbacks, data) {
                return amplify.request({
                    resourceId: 'sessionUpdate',
                    data: data,
                    success: callbacks.success,
                    error: callbacks.error
                });
            };

        init();

        return {
            getSessions: getSessions,
            getSessionBriefs: getSessionBriefs,
            getSession: getSession,
            updateSession: updateSession
        };
    });


text:
/* Usage
    private static string GetCurrentLoadedScripts()
    {
        string value = null;
        ActionCallingContext actionCallingContext = new ActionCallingContext();
        new CommandLineInterpreter().Execute("GetCurrentLoadedScripts", actionCallingContext);
        actionCallingContext.GetParameter("value", ref value);
        return value;
    }
*/

using System.Text;
using Eplan.EplApi.Base;
using Eplan.EplApi.Scripting;

namespace EplanScriptingProjectBySuplanus.GetCurrentLoadedScripts
{
    public class GetCurrentLoadedScripts
    {
        [DeclareAction("GetCurrentLoadedScripts")]
        public void Action(out string value)
        {
            Settings settings = new Settings();
            var settingsUrlScripts = "STATION.EplanEplApiScriptGui.Scripts";
            int countOfScripts = settings.GetCountOfValues(settingsUrlScripts);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < countOfScripts; i++)
            {
                string scriptPath = settings.GetStringSetting(settingsUrlScripts, i);
                stringBuilder.Append(scriptPath);

                // not last one
                if (i != countOfScripts - 1)
                {
                    stringBuilder.Append("|");
                }
            }

            // returns list: "\\path\script1.cs|\\path\script2.vb"
            value = stringBuilder.ToString();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--居中显示城市名、居右显示更新时间-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/nav_button"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="@drawable/ic_home"/>
    <!--将控制置于垂直、水平的中心位置-->
    <TextView
        android:id="@+id/title_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="20sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <!--将控件的右边缘和父控件的右边缘对齐-->
    <TextView
        android:id="@+id/title_update_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textColor="#fff"
        android:textSize="16sp"/>

</RelativeLayout>


text:
.class public Landroid/telecom/PhoneAccount$Builder;
.super Ljava/lang/Object;
.source "PhoneAccount.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/telecom/PhoneAccount;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "Builder"
.end annotation

# instance fields
.field private mAccountHandle:Landroid/telecom/PhoneAccountHandle;

.field private mAddress:Landroid/net/Uri;

.field private mCapabilities:I

.field private mExtras:Landroid/os/Bundle;

.field private mGroupId:Ljava/lang/String;

.field private mHighlightColor:I

.field private mIcon:Landroid/graphics/drawable/Icon;

.field private mIsEnabled:Z

.field private mLabel:Ljava/lang/CharSequence;

.field private mShortDescription:Ljava/lang/CharSequence;

.field private mSubscriptionAddress:Landroid/net/Uri;

.field private mSupportedAudioRoutes:I

.field private mSupportedUriSchemes:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>(Landroid/telecom/PhoneAccount;)V
    .locals 2

    const/4 v1, 0x0

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

    const/16 v0, 0xf

    iput v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedAudioRoutes:I

    iput v1, p0, Landroid/telecom/PhoneAccount$Builder;->mHighlightColor:I

    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    iput-boolean v1, p0, Landroid/telecom/PhoneAccount$Builder;->mIsEnabled:Z

    const-string/jumbo v0, ""

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getAccountHandle()Landroid/telecom/PhoneAccountHandle;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mAccountHandle:Landroid/telecom/PhoneAccountHandle;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getAddress()Landroid/net/Uri;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mAddress:Landroid/net/Uri;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getSubscriptionAddress()Landroid/net/Uri;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSubscriptionAddress:Landroid/net/Uri;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getCapabilities()I

    move-result v0

    iput v0, p0, Landroid/telecom/PhoneAccount$Builder;->mCapabilities:I

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getHighlightColor()I

    move-result v0

    iput v0, p0, Landroid/telecom/PhoneAccount$Builder;->mHighlightColor:I

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getLabel()Ljava/lang/CharSequence;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mLabel:Ljava/lang/CharSequence;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getShortDescription()Ljava/lang/CharSequence;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mShortDescription:Ljava/lang/CharSequence;

    iget-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getSupportedUriSchemes()Ljava/util/List;

    move-result-object v1

    invoke-interface {v0, v1}, Ljava/util/List;->addAll(Ljava/util/Collection;)Z

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getIcon()Landroid/graphics/drawable/Icon;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mIcon:Landroid/graphics/drawable/Icon;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->isEnabled()Z

    move-result v0

    iput-boolean v0, p0, Landroid/telecom/PhoneAccount$Builder;->mIsEnabled:Z

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getExtras()Landroid/os/Bundle;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mExtras:Landroid/os/Bundle;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getGroupId()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    invoke-virtual {p1}, Landroid/telecom/PhoneAccount;->getSupportedAudioRoutes()I

    move-result v0

    iput v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedAudioRoutes:I

    return-void
.end method

.method public constructor <init>(Landroid/telecom/PhoneAccountHandle;Ljava/lang/CharSequence;)V
    .locals 2

    const/4 v1, 0x0

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

    const/16 v0, 0xf

    iput v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedAudioRoutes:I

    iput v1, p0, Landroid/telecom/PhoneAccount$Builder;->mHighlightColor:I

    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    iput-boolean v1, p0, Landroid/telecom/PhoneAccount$Builder;->mIsEnabled:Z

    const-string/jumbo v0, ""

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mAccountHandle:Landroid/telecom/PhoneAccountHandle;

    iput-object p2, p0, Landroid/telecom/PhoneAccount$Builder;->mLabel:Ljava/lang/CharSequence;

    return-void
.end method

# virtual methods
.method public addSupportedUriScheme(Ljava/lang/String;)Landroid/telecom/PhoneAccount$Builder;
    .locals 1

    invoke-static {p1}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z

    move-result v0

    if-nez v0, :cond_0

    iget-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->contains(Ljava/lang/Object;)Z

    move-result v0

    xor-int/lit8 v0, v0, 0x1

    if-eqz v0, :cond_0

    iget-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    :cond_0
    return-object p0
.end method

.method public build()Landroid/telecom/PhoneAccount;
    .locals 15

    iget-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    invoke-interface {v0}, Ljava/util/List;->isEmpty()Z

    move-result v0

    if-eqz v0, :cond_0

    const-string/jumbo v0, "tel"

    invoke-virtual {p0, v0}, Landroid/telecom/PhoneAccount$Builder;->addSupportedUriScheme(Ljava/lang/String;)Landroid/telecom/PhoneAccount$Builder;

    :cond_0
    new-instance v0, Landroid/telecom/PhoneAccount;

    iget-object v1, p0, Landroid/telecom/PhoneAccount$Builder;->mAccountHandle:Landroid/telecom/PhoneAccountHandle;

    iget-object v2, p0, Landroid/telecom/PhoneAccount$Builder;->mAddress:Landroid/net/Uri;

    iget-object v3, p0, Landroid/telecom/PhoneAccount$Builder;->mSubscriptionAddress:Landroid/net/Uri;

    iget v4, p0, Landroid/telecom/PhoneAccount$Builder;->mCapabilities:I

    iget-object v5, p0, Landroid/telecom/PhoneAccount$Builder;->mIcon:Landroid/graphics/drawable/Icon;

    iget v6, p0, Landroid/telecom/PhoneAccount$Builder;->mHighlightColor:I

    iget-object v7, p0, Landroid/telecom/PhoneAccount$Builder;->mLabel:Ljava/lang/CharSequence;

    iget-object v8, p0, Landroid/telecom/PhoneAccount$Builder;->mShortDescription:Ljava/lang/CharSequence;

    iget-object v9, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    iget-object v10, p0, Landroid/telecom/PhoneAccount$Builder;->mExtras:Landroid/os/Bundle;

    iget v11, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedAudioRoutes:I

    iget-boolean v12, p0, Landroid/telecom/PhoneAccount$Builder;->mIsEnabled:Z

    iget-object v13, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    const/4 v14, 0x0

    invoke-direct/range {v0 .. v14}, Landroid/telecom/PhoneAccount;-><init>(Landroid/telecom/PhoneAccountHandle;Landroid/net/Uri;Landroid/net/Uri;ILandroid/graphics/drawable/Icon;ILjava/lang/CharSequence;Ljava/lang/CharSequence;Ljava/util/List;Landroid/os/Bundle;IZLjava/lang/String;Landroid/telecom/PhoneAccount;)V

    return-object v0
.end method

.method public setAddress(Landroid/net/Uri;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mAddress:Landroid/net/Uri;

    return-object p0
.end method

.method public setCapabilities(I)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput p1, p0, Landroid/telecom/PhoneAccount$Builder;->mCapabilities:I

    return-object p0
.end method

.method public setExtras(Landroid/os/Bundle;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mExtras:Landroid/os/Bundle;

    return-object p0
.end method

.method public setGroupId(Ljava/lang/String;)Landroid/telecom/PhoneAccount$Builder;
    .locals 1

    if-eqz p1, :cond_0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    :goto_0
    return-object p0

    :cond_0
    const-string/jumbo v0, ""

    iput-object v0, p0, Landroid/telecom/PhoneAccount$Builder;->mGroupId:Ljava/lang/String;

    goto :goto_0
.end method

.method public setHighlightColor(I)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput p1, p0, Landroid/telecom/PhoneAccount$Builder;->mHighlightColor:I

    return-object p0
.end method

.method public setIcon(Landroid/graphics/drawable/Icon;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mIcon:Landroid/graphics/drawable/Icon;

    return-object p0
.end method

.method public setIsEnabled(Z)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-boolean p1, p0, Landroid/telecom/PhoneAccount$Builder;->mIsEnabled:Z

    return-object p0
.end method

.method public setLabel(Ljava/lang/CharSequence;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mLabel:Ljava/lang/CharSequence;

    return-object p0
.end method

.method public setShortDescription(Ljava/lang/CharSequence;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mShortDescription:Ljava/lang/CharSequence;

    return-object p0
.end method

.method public setSubscriptionAddress(Landroid/net/Uri;)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput-object p1, p0, Landroid/telecom/PhoneAccount$Builder;->mSubscriptionAddress:Landroid/net/Uri;

    return-object p0
.end method

.method public setSupportedAudioRoutes(I)Landroid/telecom/PhoneAccount$Builder;
    .locals 0

    iput p1, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedAudioRoutes:I

    return-object p0
.end method

.method public setSupportedUriSchemes(Ljava/util/List;)Landroid/telecom/PhoneAccount$Builder;
    .locals 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;)",
            "Landroid/telecom/PhoneAccount$Builder;"
        }
    .end annotation

    iget-object v2, p0, Landroid/telecom/PhoneAccount$Builder;->mSupportedUriSchemes:Ljava/util/List;

    invoke-interface {v2}, Ljava/util/List;->clear()V

    if-eqz p1, :cond_0

    invoke-interface {p1}, Ljava/util/List;->isEmpty()Z

    move-result v2

    xor-int/lit8 v2, v2, 0x1

    if-eqz v2, :cond_0

    invoke-interface {p1}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v1

    :goto_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_0

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    invoke-virtual {p0, v0}, Landroid/telecom/PhoneAccount$Builder;->addSupportedUriScheme(Ljava/lang/String;)Landroid/telecom/PhoneAccount$Builder;

    goto :goto_0

    :cond_0
    return-object p0
.end method


text:
<?php namespace App\Events\Stats;

use App\Events\Event;

class VocabularyAnsweredHiragana extends Event
{
}


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V11.Resources {

  /// Holder for reflection information generated from google/ads/googleads/v11/resources/campaign_criterion_simulation.proto
  public static partial class CampaignCriterionSimulationReflection {

    #region Descriptor
    /// File descriptor for google/ads/googleads/v11/resources/campaign_criterion_simulation.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static CampaignCriterionSimulationReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CkZnb29nbGUvYWRzL2dvb2dsZWFkcy92MTEvcmVzb3VyY2VzL2NhbXBhaWdu",
            "X2NyaXRlcmlvbl9zaW11bGF0aW9uLnByb3RvEiJnb29nbGUuYWRzLmdvb2ds",
            "ZWFkcy52MTEucmVzb3VyY2VzGjBnb29nbGUvYWRzL2dvb2dsZWFkcy92MTEv",
            "Y29tbW9uL3NpbXVsYXRpb24ucHJvdG8aQ2dvb2dsZS9hZHMvZ29vZ2xlYWRz",
            "L3YxMS9lbnVtcy9zaW11bGF0aW9uX21vZGlmaWNhdGlvbl9tZXRob2QucHJv",
            "dG8aNGdvb2dsZS9hZHMvZ29vZ2xlYWRzL3YxMS9lbnVtcy9zaW11bGF0aW9u",
            "X3R5cGUucHJvdG8aH2dvb2dsZS9hcGkvZmllbGRfYmVoYXZpb3IucHJvdG8a",
            "GWdvb2dsZS9hcGkvcmVzb3VyY2UucHJvdG8ivAYKG0NhbXBhaWduQ3JpdGVy",
            "aW9uU2ltdWxhdGlvbhJTCg1yZXNvdXJjZV9uYW1lGAEgASgJQjzgQQP6QTYK",
            "NGdvb2dsZWFkcy5nb29nbGVhcGlzLmNvbS9DYW1wYWlnbkNyaXRlcmlvblNp",
            "bXVsYXRpb24SHQoLY2FtcGFpZ25faWQYCSABKANCA+BBA0gBiAEBEh4KDGNy",
            "aXRlcmlvbl9pZBgKIAEoA0ID4EEDSAKIAQESVAoEdHlwZRgEIAEoDjJBLmdv",
            "b2dsZS5hZHMuZ29vZ2xlYWRzLnYxMS5lbnVtcy5TaW11bGF0aW9uVHlwZUVu",
            "dW0uU2ltdWxhdGlvblR5cGVCA+BBAxJ/ChNtb2RpZmljYXRpb25fbWV0aG9k",
            "GAUgASgOMl0uZ29vZ2xlLmFkcy5nb29nbGVhZHMudjExLmVudW1zLlNpbXVs",
            "YXRpb25Nb2RpZmljYXRpb25NZXRob2RFbnVtLlNpbXVsYXRpb25Nb2RpZmlj",
            "YXRpb25NZXRob2RCA+BBAxIcCgpzdGFydF9kYXRlGAsgASgJQgPgQQNIA4gB",
            "ARIaCghlbmRfZGF0ZRgMIAEoCUID4EEDSASIAQESZwoXYmlkX21vZGlmaWVy",
            "X3BvaW50X2xpc3QYCCABKAsyPy5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTEu",
            "Y29tbW9uLkJpZE1vZGlmaWVyU2ltdWxhdGlvblBvaW50TGlzdEID4EEDSAA6",
            "wwHqQb8BCjRnb29nbGVhZHMuZ29vZ2xlYXBpcy5jb20vQ2FtcGFpZ25Dcml0",
            "ZXJpb25TaW11bGF0aW9uEoYBY3VzdG9tZXJzL3tjdXN0b21lcl9pZH0vY2Ft",
            "cGFpZ25Dcml0ZXJpb25TaW11bGF0aW9ucy97Y2FtcGFpZ25faWR9fntjcml0",
            "ZXJpb25faWR9fnt0eXBlfX57bW9kaWZpY2F0aW9uX21ldGhvZH1+e3N0YXJ0",
            "X2RhdGV9fntlbmRfZGF0ZX1CDAoKcG9pbnRfbGlzdEIOCgxfY2FtcGFpZ25f",
            "aWRCDwoNX2NyaXRlcmlvbl9pZEINCgtfc3RhcnRfZGF0ZUILCglfZW5kX2Rh",
            "dGVCkgIKJmNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTEucmVzb3VyY2Vz",
            "QiBDYW1wYWlnbkNyaXRlcmlvblNpbXVsYXRpb25Qcm90b1ABWktnb29nbGUu",
            "Z29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMv",
            "djExL3Jlc291cmNlcztyZXNvdXJjZXOiAgNHQUGqAiJHb29nbGUuQWRzLkdv",
            "b2dsZUFkcy5WMTEuUmVzb3VyY2VzygIiR29vZ2xlXEFkc1xHb29nbGVBZHNc",
            "VjExXFJlc291cmNlc+oCJkdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYxMTo6",
            "UmVzb3VyY2VzYgZwcm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V11.Common.SimulationReflection.Descriptor, global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodReflection.Descriptor, global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeReflection.Descriptor, global::Google.Api.FieldBehaviorReflection.Descriptor, global::Google.Api.ResourceReflection.Descriptor, },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V11.Resources.CampaignCriterionSimulation), global::Google.Ads.GoogleAds.V11.Resources.CampaignCriterionSimulation.Parser, new[]{ "ResourceName", "CampaignId", "CriterionId", "Type", "ModificationMethod", "StartDate", "EndDate", "BidModifierPointList" }, new[]{ "PointList", "CampaignId", "CriterionId", "StartDate", "EndDate" }, null, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// A campaign criterion simulation. Supported combinations of advertising
  /// channel type, criterion ids, simulation type and simulation modification
  /// method is detailed below respectively.
  ///
  /// 1. SEARCH - 30000,30001,30002 - BID_MODIFIER - UNIFORM
  /// 2. DISPLAY - 30001 - BID_MODIFIER - UNIFORM
  ///
  public sealed partial class CampaignCriterionSimulation : pb::IMessage<CampaignCriterionSimulation>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<CampaignCriterionSimulation> _parser = new pb::MessageParser<CampaignCriterionSimulation>(() => new CampaignCriterionSimulation());
    private pb::UnknownFieldSet _unknownFields;
    private int _hasBits0;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<CampaignCriterionSimulation> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Ads.GoogleAds.V11.Resources.CampaignCriterionSimulationReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public CampaignCriterionSimulation() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public CampaignCriterionSimulation(CampaignCriterionSimulation other) : this() {
      _hasBits0 = other._hasBits0;
      resourceName_ = other.resourceName_;
      campaignId_ = other.campaignId_;
      criterionId_ = other.criterionId_;
      type_ = other.type_;
      modificationMethod_ = other.modificationMethod_;
      startDate_ = other.startDate_;
      endDate_ = other.endDate_;
      switch (other.PointListCase) {
        case PointListOneofCase.BidModifierPointList:
          BidModifierPointList = other.BidModifierPointList.Clone();
          break;
      }

      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public CampaignCriterionSimulation Clone() {
      return new CampaignCriterionSimulation(this);
    }

    /// Field number for the "resource_name" field.
    public const int ResourceNameFieldNumber = 1;
    private string resourceName_ = "";
    ///
    /// Output only. The resource name of the campaign criterion simulation.
    /// Campaign criterion simulation resource names have the form:
    ///
    /// `customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}`
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string ResourceName {
      get { return resourceName_; }
      set {
        resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }

    /// Field number for the "campaign_id" field.
    public const int CampaignIdFieldNumber = 9;
    private long campaignId_;
    ///
    /// Output only. Campaign ID of the simulation.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public long CampaignId {
      get { if ((_hasBits0 & 1) != 0) { return campaignId_; } else { return 0L; } }
      set {
        _hasBits0 |= 1;
        campaignId_ = value;
      }
    }
    /// Gets whether the "campaign_id" field is set
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool HasCampaignId {
      get { return (_hasBits0 & 1) != 0; }
    }
    /// Clears the value of the "campaign_id" field
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearCampaignId() {
      _hasBits0 &= ~1;
    }

    /// Field number for the "criterion_id" field.
    public const int CriterionIdFieldNumber = 10;
    private long criterionId_;
    ///
    /// Output only. Criterion ID of the simulation.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public long CriterionId {
      get { if ((_hasBits0 & 2) != 0) { return criterionId_; } else { return 0L; } }
      set {
        _hasBits0 |= 2;
        criterionId_ = value;
      }
    }
    /// Gets whether the "criterion_id" field is set
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool HasCriterionId {
      get { return (_hasBits0 & 2) != 0; }
    }
    /// Clears the value of the "criterion_id" field
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearCriterionId() {
      _hasBits0 &= ~2;
    }

    /// Field number for the "type" field.
    public const int TypeFieldNumber = 4;
    private global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType type_ = global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified;
    ///
    /// Output only. The field that the simulation modifies.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType Type {
      get { return type_; }
      set {
        type_ = value;
      }
    }

    /// Field number for the "modification_method" field.
    public const int ModificationMethodFieldNumber = 5;
    private global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod modificationMethod_ = global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified;
    ///
    /// Output only. How the simulation modifies the field.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod ModificationMethod {
      get { return modificationMethod_; }
      set {
        modificationMethod_ = value;
      }
    }

    /// Field number for the "start_date" field.
    public const int StartDateFieldNumber = 11;
    private string startDate_;
    ///
    /// Output only. First day on which the simulation is based, in YYYY-MM-DD format.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string StartDate {
      get { return startDate_ ?? ""; }
      set {
        startDate_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }
    /// Gets whether the "start_date" field is set
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool HasStartDate {
      get { return startDate_ != null; }
    }
    /// Clears the value of the "start_date" field
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearStartDate() {
      startDate_ = null;
    }

    /// Field number for the "end_date" field.
    public const int EndDateFieldNumber = 12;
    private string endDate_;
    ///
    /// Output only. Last day on which the simulation is based, in YYYY-MM-DD format.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public string EndDate {
      get { return endDate_ ?? ""; }
      set {
        endDate_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
      }
    }
    /// Gets whether the "end_date" field is set
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool HasEndDate {
      get { return endDate_ != null; }
    }
    /// Clears the value of the "end_date" field
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearEndDate() {
      endDate_ = null;
    }

    /// Field number for the "bid_modifier_point_list" field.
    public const int BidModifierPointListFieldNumber = 8;
    ///
    /// Output only. Simulation points if the simulation type is BID_MODIFIER.
    ///
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList BidModifierPointList {
      get { return pointListCase_ == PointListOneofCase.BidModifierPointList ? (global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList) pointList_ : null; }
      set {
        pointList_ = value;
        pointListCase_ = value == null ? PointListOneofCase.None : PointListOneofCase.BidModifierPointList;
      }
    }

    private object pointList_;
    /// Enum of possible cases for the "point_list" oneof.
    public enum PointListOneofCase {
      None = 0,
      BidModifierPointList = 8,
    }
    private PointListOneofCase pointListCase_ = PointListOneofCase.None;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public PointListOneofCase PointListCase {
      get { return pointListCase_; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void ClearPointList() {
      pointListCase_ = PointListOneofCase.None;
      pointList_ = null;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as CampaignCriterionSimulation);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(CampaignCriterionSimulation other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      if (ResourceName != other.ResourceName) return false;
      if (CampaignId != other.CampaignId) return false;
      if (CriterionId != other.CriterionId) return false;
      if (Type != other.Type) return false;
      if (ModificationMethod != other.ModificationMethod) return false;
      if (StartDate != other.StartDate) return false;
      if (EndDate != other.EndDate) return false;
      if (!object.Equals(BidModifierPointList, other.BidModifierPointList)) return false;
      if (PointListCase != other.PointListCase) return false;
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode();
      if (HasCampaignId) hash ^= CampaignId.GetHashCode();
      if (HasCriterionId) hash ^= CriterionId.GetHashCode();
      if (Type != global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) hash ^= Type.GetHashCode();
      if (ModificationMethod != global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) hash ^= ModificationMethod.GetHashCode();
      if (HasStartDate) hash ^= StartDate.GetHashCode();
      if (HasEndDate) hash ^= EndDate.GetHashCode();
      if (pointListCase_ == PointListOneofCase.BidModifierPointList) hash ^= BidModifierPointList.GetHashCode();
      hash ^= (int) pointListCase_;
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (ResourceName.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(ResourceName);
      }
      if (Type != global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) {
        output.WriteRawTag(32);
        output.WriteEnum((int) Type);
      }
      if (ModificationMethod != global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) {
        output.WriteRawTag(40);
        output.WriteEnum((int) ModificationMethod);
      }
      if (pointListCase_ == PointListOneofCase.BidModifierPointList) {
        output.WriteRawTag(66);
        output.WriteMessage(BidModifierPointList);
      }
      if (HasCampaignId) {
        output.WriteRawTag(72);
        output.WriteInt64(CampaignId);
      }
      if (HasCriterionId) {
        output.WriteRawTag(80);
        output.WriteInt64(CriterionId);
      }
      if (HasStartDate) {
        output.WriteRawTag(90);
        output.WriteString(StartDate);
      }
      if (HasEndDate) {
        output.WriteRawTag(98);
        output.WriteString(EndDate);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (ResourceName.Length != 0) {
        output.WriteRawTag(10);
        output.WriteString(ResourceName);
      }
      if (Type != global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) {
        output.WriteRawTag(32);
        output.WriteEnum((int) Type);
      }
      if (ModificationMethod != global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) {
        output.WriteRawTag(40);
        output.WriteEnum((int) ModificationMethod);
      }
      if (pointListCase_ == PointListOneofCase.BidModifierPointList) {
        output.WriteRawTag(66);
        output.WriteMessage(BidModifierPointList);
      }
      if (HasCampaignId) {
        output.WriteRawTag(72);
        output.WriteInt64(CampaignId);
      }
      if (HasCriterionId) {
        output.WriteRawTag(80);
        output.WriteInt64(CriterionId);
      }
      if (HasStartDate) {
        output.WriteRawTag(90);
        output.WriteString(StartDate);
      }
      if (HasEndDate) {
        output.WriteRawTag(98);
        output.WriteString(EndDate);
      }
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (ResourceName.Length != 0) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName);
      }
      if (HasCampaignId) {
        size += 1 + pb::CodedOutputStream.ComputeInt64Size(CampaignId);
      }
      if (HasCriterionId) {
        size += 1 + pb::CodedOutputStream.ComputeInt64Size(CriterionId);
      }
      if (Type != global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
      }
      if (ModificationMethod != global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) {
        size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ModificationMethod);
      }
      if (HasStartDate) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(StartDate);
      }
      if (HasEndDate) {
        size += 1 + pb::CodedOutputStream.ComputeStringSize(EndDate);
      }
      if (pointListCase_ == PointListOneofCase.BidModifierPointList) {
        size += 1 + pb::CodedOutputStream.ComputeMessageSize(BidModifierPointList);
      }
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(CampaignCriterionSimulation other) {
      if (other == null) {
        return;
      }
      if (other.ResourceName.Length != 0) {
        ResourceName = other.ResourceName;
      }
      if (other.HasCampaignId) {
        CampaignId = other.CampaignId;
      }
      if (other.HasCriterionId) {
        CriterionId = other.CriterionId;
      }
      if (other.Type != global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType.Unspecified) {
        Type = other.Type;
      }
      if (other.ModificationMethod != global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod.Unspecified) {
        ModificationMethod = other.ModificationMethod;
      }
      if (other.HasStartDate) {
        StartDate = other.StartDate;
      }
      if (other.HasEndDate) {
        EndDate = other.EndDate;
      }
      switch (other.PointListCase) {
        case PointListOneofCase.BidModifierPointList:
          if (BidModifierPointList == null) {
            BidModifierPointList = new global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList();
          }
          BidModifierPointList.MergeFrom(other.BidModifierPointList);
          break;
      }

      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
          case 10: {
            ResourceName = input.ReadString();
            break;
          }
          case 32: {
            Type = (global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType) input.ReadEnum();
            break;
          }
          case 40: {
            ModificationMethod = (global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod) input.ReadEnum();
            break;
          }
          case 66: {
            global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList();
            if (pointListCase_ == PointListOneofCase.BidModifierPointList) {
              subBuilder.MergeFrom(BidModifierPointList);
            }
            input.ReadMessage(subBuilder);
            BidModifierPointList = subBuilder;
            break;
          }
          case 72: {
            CampaignId = input.ReadInt64();
            break;
          }
          case 80: {
            CriterionId = input.ReadInt64();
            break;
          }
          case 90: {
            StartDate = input.ReadString();
            break;
          }
          case 98: {
            EndDate = input.ReadString();
            break;
          }
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
          case 10: {
            ResourceName = input.ReadString();
            break;
          }
          case 32: {
            Type = (global::Google.Ads.GoogleAds.V11.Enums.SimulationTypeEnum.Types.SimulationType) input.ReadEnum();
            break;
          }
          case 40: {
            ModificationMethod = (global::Google.Ads.GoogleAds.V11.Enums.SimulationModificationMethodEnum.Types.SimulationModificationMethod) input.ReadEnum();
            break;
          }
          case 66: {
            global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList subBuilder = new global::Google.Ads.GoogleAds.V11.Common.BidModifierSimulationPointList();
            if (pointListCase_ == PointListOneofCase.BidModifierPointList) {
              subBuilder.MergeFrom(BidModifierPointList);
            }
            input.ReadMessage(subBuilder);
            BidModifierPointList = subBuilder;
            break;
          }
          case 72: {
            CampaignId = input.ReadInt64();
            break;
          }
          case 80: {
            CriterionId = input.ReadInt64();
            break;
          }
          case 90: {
            StartDate = input.ReadString();
            break;
          }
          case 98: {
            EndDate = input.ReadString();
            break;
          }
        }
      }
    }
    #endif

  }

  #endregion

}

#endregion Designer generated code


text:
from io import BytesIO
import os.path
import subprocess

import requests as req

import mvz.const as const

def download(youtube_id: str, bust_cache: bool = False) -> str:
    url = const.url_for_youtube_id % {'yt_id': youtube_id}
    video = BytesIO(req.get(url).content)
    video_fn = const.video_fn(youtube_id)

    if not os.path.exists(const.cache_dir):
        os.makedirs(const.cache_dir)

    if not os.path.exists(video_fn) or bust_cache:
        with open(video_fn, 'wb') as f:
            f.write(video.read())

        split_into_frames(youtube_id)

    return video_fn

def split_into_frames(youtube_id: str) -> None:
    command = (
        "ffmpeg -i %(video_fn)s -vsync 1 -r 15 -s 1280x720"
        " -f image2 '%(output_fn_template)s'") % {
            'video_fn': const.video_fn(youtube_id),
            'output_fn_template': const.frame_fn_template(youtube_id)}
    subprocess.call(command, shell=True)


text:
package org.gradle.configuration;

import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.api.internal.DocumentationRegistry;
import org.gradle.api.internal.file.FileLookup;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.internal.initialization.ScriptHandlerFactory;
import org.gradle.api.internal.plugins.PluginAwareInternal;
import org.gradle.api.internal.plugins.PluginManagerInternal;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.project.ProjectScript;
import org.gradle.groovy.scripts.*;
import org.gradle.groovy.scripts.internal.*;
import org.gradle.internal.Actions;
import org.gradle.internal.Factory;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.serialize.BaseSerializerFactory;
import org.gradle.internal.service.DefaultServiceRegistry;
import org.gradle.logging.LoggingManagerInternal;
import org.gradle.model.dsl.internal.transform.ClosureCreationInterceptingVerifier;
import org.gradle.model.dsl.internal.transform.ModelBlockTransformer;
import org.gradle.model.internal.inspect.ModelRuleSourceDetector;
import org.gradle.plugin.use.internal.PluginRequestApplicator;
import org.gradle.plugin.use.internal.PluginRequests;
import org.gradle.plugin.use.internal.PluginRequestsSerializer;

public class DefaultScriptPluginFactory implements ScriptPluginFactory {

    private final ScriptCompilerFactory scriptCompilerFactory;
    private final Factory<LoggingManagerInternal> loggingManagerFactory;
    private final Instantiator instantiator;
    private final ScriptHandlerFactory scriptHandlerFactory;
    private final PluginRequestApplicator pluginRequestApplicator;
    private final FileLookup fileLookup;
    private final DocumentationRegistry documentationRegistry;
    private final ModelRuleSourceDetector modelRuleSourceDetector;

    public DefaultScriptPluginFactory(ScriptCompilerFactory scriptCompilerFactory,
                                      Factory<LoggingManagerInternal> loggingManagerFactory,
                                      Instantiator instantiator,
                                      ScriptHandlerFactory scriptHandlerFactory,
                                      PluginRequestApplicator pluginRequestApplicator,
                                      FileLookup fileLookup,
                                      DocumentationRegistry documentationRegistry,
                                      ModelRuleSourceDetector modelRuleSourceDetector) {
        this.scriptCompilerFactory = scriptCompilerFactory;
        this.loggingManagerFactory = loggingManagerFactory;
        this.instantiator = instantiator;
        this.scriptHandlerFactory = scriptHandlerFactory;
        this.pluginRequestApplicator = pluginRequestApplicator;
        this.fileLookup = fileLookup;
        this.documentationRegistry = documentationRegistry;
        this.modelRuleSourceDetector = modelRuleSourceDetector;
    }

    public ScriptPlugin create(ScriptSource scriptSource, ScriptHandler scriptHandler, ClassLoaderScope targetScope, ClassLoaderScope baseScope, String classpathClosureName, Class<? extends BasicScript> scriptClass, boolean ownerScript) {
        return new ScriptPluginImpl(scriptSource, scriptHandler, targetScope, baseScope, classpathClosureName, scriptClass, ownerScript);
    }

    private class ScriptPluginImpl implements ScriptPlugin {
        private final ScriptSource scriptSource;
        private final ClassLoaderScope targetScope;
        private final ClassLoaderScope baseScope;
        private final String classpathClosureName;
        private final Class<? extends BasicScript> scriptType;
        private final ScriptHandler scriptHandler;
        private final boolean ownerScript;

        public ScriptPluginImpl(ScriptSource scriptSource, ScriptHandler scriptHandler, ClassLoaderScope targetScope, ClassLoaderScope baseScope, String classpathClosureName, Class<? extends BasicScript> scriptType, boolean ownerScript) {
            this.scriptSource = scriptSource;
            this.targetScope = targetScope;
            this.baseScope = baseScope;
            this.classpathClosureName = classpathClosureName;
            this.scriptHandler = scriptHandler;
            this.scriptType = scriptType;
            this.ownerScript = ownerScript;
        }

        public ScriptSource getSource() {
            return scriptSource;
        }

        public void apply(final Object target) {
            final DefaultServiceRegistry services = new DefaultServiceRegistry();
            services.add(ScriptPluginFactory.class, DefaultScriptPluginFactory.this);
            services.add(ScriptHandlerFactory.class, scriptHandlerFactory);
            services.add(ClassLoaderScope.class, targetScope);
            services.add(LoggingManagerInternal.class, loggingManagerFactory.create());
            services.add(Instantiator.class, instantiator);
            services.add(ScriptHandler.class, scriptHandler);
            services.add(FileLookup.class, fileLookup);
            services.add(ModelRuleSourceDetector.class, modelRuleSourceDetector);

            final ScriptCompiler compiler = scriptCompilerFactory.createCompiler(scriptSource);

            // Pass 1, extract plugin requests and execute buildscript {}, ignoring (i.e. not even compiling) anything else

            boolean supportsPluginsBlock = ProjectScript.class.isAssignableFrom(scriptType);
            String onPluginBlockError = supportsPluginsBlock ? null : "Only Project build scripts can contain plugins {} blocks";

            InitialPassStatementTransformer initialPassStatementTransformer = new InitialPassStatementTransformer(classpathClosureName, onPluginBlockError, scriptSource, documentationRegistry);
            SubsetScriptTransformer initialTransformer = new SubsetScriptTransformer(initialPassStatementTransformer);
            CompileOperation<PluginRequests> initialOperation = new FactoryBackedCompileOperation<PluginRequests>(classpathClosureName, initialTransformer, initialPassStatementTransformer, PluginRequestsSerializer.INSTANCE);

            ScriptRunner<? extends BasicScript, PluginRequests> initialRunner = compiler.compile(scriptType, initialOperation, baseScope.getExportClassLoader(), classpathClosureName, Actions.doNothing());
            initialRunner.getScript().init(target, services);
            initialRunner.run();

            PluginRequests pluginRequests = initialRunner.getCompiledScript().getData();
            PluginManagerInternal pluginManager = target instanceof PluginAwareInternal ? ((PluginAwareInternal) target).getPluginManager() : null;
            pluginRequestApplicator.applyPlugins(pluginRequests, scriptHandler, pluginManager, targetScope);

            // Pass 2, compile everything except buildscript {} and plugin requests, then run

            BuildScriptTransformer buildScriptTransformer = new BuildScriptTransformer(classpathClosureName, scriptSource);
            String operationId = "no_" + classpathClosureName;
            if (ModelBlockTransformer.isEnabled()) {
                operationId = "m_".concat(operationId);
            }
            CompileOperation<Boolean> operation = new FactoryBackedCompileOperation<Boolean>(operationId, buildScriptTransformer, buildScriptTransformer, BaseSerializerFactory.BOOLEAN_SERIALIZER);

            final ScriptRunner<? extends BasicScript, Boolean> runner = compiler.compile(scriptType, operation, targetScope.getLocalClassLoader(), classpathClosureName, ClosureCreationInterceptingVerifier.INSTANCE);

            Runnable buildScriptRunner = new Runnable() {
                public void run() {
                    BasicScript script = runner.getScript();
                    script.init(target, services);
                    if (ownerScript && target instanceof ScriptAware) {
                        ((ScriptAware) target).setScript(script);
                    }
                    runner.run();
                }
            };

            Boolean hasImperativeStatements = runner.getCompiledScript().getData();
            if (!hasImperativeStatements && target instanceof ProjectInternal) {
                ((ProjectInternal) target).addDeferredConfiguration(buildScriptRunner);
            } else {
                buildScriptRunner.run();
            }
        }
    }
}


text:
package io.airlift.concurrent;

import com.google.common.base.Throwables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.isEmpty;
import static java.util.Objects.requireNonNull;

public final class MoreFutures
{
    private MoreFutures() { }

    /**
     * Returns a future that can not be completed or canceled.
     */
    public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future)
    {
        requireNonNull(future, "future is null");

        UnmodifiableCompletableFuture<V> unmodifiableFuture = new UnmodifiableCompletableFuture<>();
        future.whenComplete((value, exception) -> {
            if (exception != null) {
                unmodifiableFuture.internalCompleteExceptionally(exception);
            }
            else {
                unmodifiableFuture.internalComplete(value);
            }
        });
        return unmodifiableFuture;
    }

    /**
     * Returns a failed future containing the specified throwable.
     */
    public static <V> CompletableFuture<V> failedFuture(Throwable throwable)
    {
        requireNonNull(throwable, "throwable is null");
        CompletableFuture<V> future = new CompletableFuture<>();
        future.completeExceptionally(throwable);
        return future;
    }

    /**
     * Waits for the value from the future. If the future is failed, the exception
     * is thrown directly if unchecked or wrapped in a RuntimeException. If the
     * thread is interrupted, the thread interruption flag is set and the original
     * InterruptedException is wrapped in a RuntimeException and thrown.
     */
    public static <V> V getFutureValue(Future<V> future)
    {
        return getFutureValue(future, RuntimeException.class);
    }

    /**
     * Waits for the value from the future. If the future is failed, the exception
     * is thrown directly if it is an instance of the specified exception type or
     * unchecked, or it is wrapped in a RuntimeException. If the thread is
     * interrupted, the thread interruption flag is set and the original
     * InterruptedException is wrapped in a RuntimeException and thrown.
     */
    public static <V, E extends Exception> V getFutureValue(Future<V> future, Class<E> exceptionType)
            throws E
    {
        requireNonNull(future, "future is null");
        requireNonNull(exceptionType, "exceptionType is null");

        try {
            return future.get();
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("interrupted", e);
        }
        catch (ExecutionException e) {
            Throwable cause = e.getCause() == null ? e : e.getCause();
            Throwables.propagateIfInstanceOf(cause, exceptionType);
            throw Throwables.propagate(cause);
        }
    }

    /**
     * Waits for the the value from the future for the specified time.  If the future
     * value is null, an empty Optional is still returned, and in this case the caller
     * must check the future directly for the null value.  If the future is failed,
     * the exception is thrown directly if unchecked or wrapped in a RuntimeException.
     * If the thread is interrupted, the thread interruption flag is set and the original
     * InterruptedException is wrapped in a RuntimeException and thrown.
     */
    public static <V> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit)
    {
        return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class);
    }

    /**
     * Waits for the the value from the future for the specified time.  If the future
     * value is null, an empty Optional is still returned, and in this case the caller
     * must check the future directly for the null value.  If the future is failed,
     * the exception is thrown directly if it is an instance of the specified exception
     * type or unchecked, or it is wrapped in a RuntimeException. If the thread is
     * interrupted, the thread interruption flag is set and the original
     * InterruptedException is wrapped in a RuntimeException and thrown.
     */
    public static <V, E extends Exception> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit, Class<E> exceptionType)
            throws E
    {
        requireNonNull(future, "future is null");
        checkArgument(timeout >= 0, "timeout is negative");
        requireNonNull(timeUnit, "timeUnit is null");
        requireNonNull(exceptionType, "exceptionType is null");

        try {
            return Optional.ofNullable(future.get(timeout, timeUnit));
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("interrupted", e);
        }
        catch (ExecutionException e) {
            Throwable cause = e.getCause() == null ? e : e.getCause();
            Throwables.propagateIfInstanceOf(cause, exceptionType);
            throw Throwables.propagate(cause);
        }
        catch (TimeoutException expected) {
            // expected
        }
        return Optional.empty();
    }

    /**
     * Creates a future that completes when the first future completes either normally
     * or exceptionally. Cancellation of the future does not propagate to the supplied
     * futures.
     */
    public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures)
    {
        requireNonNull(futures, "futures is null");
        checkArgument(!isEmpty(futures), "futures is empty");

        CompletableFuture<V> future = new CompletableFuture<>();
        for (CompletionStage<? extends V> stage : futures) {
            stage.whenComplete((value, exception) -> {
                if (exception != null) {
                    future.completeExceptionally(exception);
                }
                else {
                    future.complete(value);
                }
            });
        }
        return future;
    }

    /**
     * Converts a ListenableFuture to a CompletableFuture. Cancellation of the
     * CompletableFuture will be propagated to the ListenableFuture.
     */
    public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture)
    {
        requireNonNull(listenableFuture, "listenableFuture is null");

        CompletableFuture<V> future = new CompletableFuture<>();
        future.exceptionally(throwable -> {
            if (throwable instanceof CancellationException) {
                listenableFuture.cancel(true);
            }
            return null;
        });

        Futures.addCallback(listenableFuture, new FutureCallback<V>()
        {
            @Override
            public void onSuccess(V result)
            {
                future.complete(result);
            }

            @Override
            public void onFailure(Throwable t)
            {
                future.completeExceptionally(t);
            }
        });
        return future;
    }

    /**
     * Converts a CompletableFuture to a ListenableFuture. Cancellation of the
     * ListenableFuture will be propagated to the CompletableFuture.
     */
    public static <V> ListenableFuture<V> toListenableFuture(CompletableFuture<V> completableFuture)
    {
        requireNonNull(completableFuture, "completableFuture is null");
        SettableFuture<V> future = SettableFuture.create();
        Futures.addCallback(future, new FutureCallback<V>()
        {
            @Override
            public void onSuccess(V result)
            {
            }

            @Override
            public void onFailure(Throwable throwable)
            {
                if (throwable instanceof CancellationException) {
                    completableFuture.cancel(true);
                }
            }
        });

        completableFuture.whenComplete((value, exception) -> {
            if (exception != null) {
                future.setException(exception);
            }
            else {
                future.set(value);
            }
        });
        return future;
    }

    private static class UnmodifiableCompletableFuture<V>
            extends CompletableFuture<V>
    {
        void internalComplete(V value)
        {
            super.complete(value);
        }

        void internalCompleteExceptionally(Throwable ex)
        {
            super.completeExceptionally(ex);
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning)
        {
            // ignore cancellation
            return false;
        }

        @Override
        public boolean complete(V value)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean completeExceptionally(Throwable ex)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void obtrudeValue(V value)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void obtrudeException(Throwable ex)
        {
            throw new UnsupportedOperationException();
        }
    }
}