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

#include "engine.h"

#include "core/authors.gen.h"
#include "core/config/project_settings.h"
#include "core/donors.gen.h"
#include "core/io/json.h"
#include "core/license.gen.h"
#include "core/os/os.h"
#include "core/variant/typed_array.h"
#include "core/version.h"

void Engine::set_physics_ticks_per_second(int p_ips) {
	ERR_FAIL_COND_MSG(p_ips <= 0, "Engine iterations per second must be greater than 0.");
	ips = p_ips;
}

int Engine::get_physics_ticks_per_second() const {
	return ips;
}

void Engine::set_physics_jitter_fix(double p_threshold) {
	if (p_threshold < 0) {
		p_threshold = 0;
	}
	physics_jitter_fix = p_threshold;
}

double Engine::get_physics_jitter_fix() const {
	return physics_jitter_fix;
}

void Engine::set_target_fps(int p_fps) {
	_target_fps = p_fps > 0 ? p_fps : 0;
}

int Engine::get_target_fps() const {
	return _target_fps;
}

uint64_t Engine::get_frames_drawn() {
	return frames_drawn;
}

void Engine::set_frame_delay(uint32_t p_msec) {
	_frame_delay = p_msec;
}

uint32_t Engine::get_frame_delay() const {
	return _frame_delay;
}

void Engine::set_time_scale(double p_scale) {
	_time_scale = p_scale;
}

double Engine::get_time_scale() const {
	return _time_scale;
}

Dictionary Engine::get_version_info() const {
	Dictionary dict;
	dict["major"] = VERSION_MAJOR;
	dict["minor"] = VERSION_MINOR;
	dict["patch"] = VERSION_PATCH;
	dict["hex"] = VERSION_HEX;
	dict["status"] = VERSION_STATUS;
	dict["build"] = VERSION_BUILD;
	dict["year"] = VERSION_YEAR;

	String hash = String(VERSION_HASH);
	dict["hash"] = hash.is_empty() ? String("unknown") : hash;

	String stringver = String(dict["major"]) + "." + String(dict["minor"]);
	if ((int)dict["patch"] != 0) {
		stringver += "." + String(dict["patch"]);
	}
	stringver += "-" + String(dict["status"]) + " (" + String(dict["build"]) + ")";
	dict["string"] = stringver;

	return dict;
}

static Array array_from_info(const char *const *info_list) {
	Array arr;
	for (int i = 0; info_list[i] != nullptr; i++) {
		arr.push_back(String::utf8(info_list[i]));
	}
	return arr;
}

static Array array_from_info_count(const char *const *info_list, int info_count) {
	Array arr;
	for (int i = 0; i < info_count; i++) {
		arr.push_back(String::utf8(info_list[i]));
	}
	return arr;
}

Dictionary Engine::get_author_info() const {
	Dictionary dict;

	dict["lead_developers"] = array_from_info(AUTHORS_LEAD_DEVELOPERS);
	dict["project_managers"] = array_from_info(AUTHORS_PROJECT_MANAGERS);
	dict["founders"] = array_from_info(AUTHORS_FOUNDERS);
	dict["developers"] = array_from_info(AUTHORS_DEVELOPERS);

	return dict;
}

TypedArray<Dictionary> Engine::get_copyright_info() const {
	TypedArray<Dictionary> components;
	for (int component_index = 0; component_index < COPYRIGHT_INFO_COUNT; component_index++) {
		const ComponentCopyright &cp_info = COPYRIGHT_INFO[component_index];
		Dictionary component_dict;
		component_dict["name"] = String::utf8(cp_info.name);
		Array parts;
		for (int i = 0; i < cp_info.part_count; i++) {
			const ComponentCopyrightPart &cp_part = cp_info.parts[i];
			Dictionary part_dict;
			part_dict["files"] = array_from_info_count(cp_part.files, cp_part.file_count);
			part_dict["copyright"] = array_from_info_count(cp_part.copyright_statements, cp_part.copyright_count);
			part_dict["license"] = String::utf8(cp_part.license);
			parts.push_back(part_dict);
		}
		component_dict["parts"] = parts;

		components.push_back(component_dict);
	}
	return components;
}

Dictionary Engine::get_donor_info() const {
	Dictionary donors;
	donors["platinum_sponsors"] = array_from_info(DONORS_SPONSOR_PLATINUM);
	donors["gold_sponsors"] = array_from_info(DONORS_SPONSOR_GOLD);
	donors["silver_sponsors"] = array_from_info(DONORS_SPONSOR_SILVER);
	donors["bronze_sponsors"] = array_from_info(DONORS_SPONSOR_BRONZE);
	donors["mini_sponsors"] = array_from_info(DONORS_SPONSOR_MINI);
	donors["gold_donors"] = array_from_info(DONORS_GOLD);
	donors["silver_donors"] = array_from_info(DONORS_SILVER);
	donors["bronze_donors"] = array_from_info(DONORS_BRONZE);
	return donors;
}

Dictionary Engine::get_license_info() const {
	Dictionary licenses;
	for (int i = 0; i < LICENSE_COUNT; i++) {
		licenses[LICENSE_NAMES[i]] = LICENSE_BODIES[i];
	}
	return licenses;
}

String Engine::get_license_text() const {
	return String(GODOT_LICENSE_TEXT);
}

String Engine::get_architecture_name() const {
#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
	return "x86_64";

#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
	return "x86_32";

#elif defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)
	return "arm64";

#elif defined(__arm__) || defined(_M_ARM)
	return "arm32";

#elif defined(__riscv)
#if __riscv_xlen == 8
	return "rv64";
#else
	return "riscv";
#endif

#elif defined(__powerpc__)
#if defined(__powerpc64__)
	return "ppc64";
#else
	return "ppc";
#endif

#elif defined(__wasm__)
#if defined(__wasm64__)
	return "wasm64";
#elif defined(__wasm32__)
	return "wasm32";
#endif
#endif
}

bool Engine::is_abort_on_gpu_errors_enabled() const {
	return abort_on_gpu_errors;
}

int32_t Engine::get_gpu_index() const {
	return gpu_idx;
}

bool Engine::is_validation_layers_enabled() const {
	return use_validation_layers;
}

void Engine::set_print_error_messages(bool p_enabled) {
	CoreGlobals::print_error_enabled = p_enabled;
}

bool Engine::is_printing_error_messages() const {
	return CoreGlobals::print_error_enabled;
}

void Engine::add_singleton(const Singleton &p_singleton) {
	ERR_FAIL_COND_MSG(singleton_ptrs.has(p_singleton.name), "Can't register singleton that already exists: " + String(p_singleton.name));
	singletons.push_back(p_singleton);
	singleton_ptrs[p_singleton.name] = p_singleton.ptr;
}

Object *Engine::get_singleton_object(const StringName &p_name) const {
	HashMap<StringName, Object *>::ConstIterator E = singleton_ptrs.find(p_name);
	ERR_FAIL_COND_V_MSG(!E, nullptr, "Failed to retrieve non-existent singleton '" + String(p_name) + "'.");
	return E->value;
}

bool Engine::is_singleton_user_created(const StringName &p_name) const {
	ERR_FAIL_COND_V(!singleton_ptrs.has(p_name), false);

	for (const Singleton &E : singletons) {
		if (E.name == p_name && E.user_created) {
			return true;
		}
	}

	return false;
}
void Engine::remove_singleton(const StringName &p_name) {
	ERR_FAIL_COND(!singleton_ptrs.has(p_name));

	for (List<Singleton>::Element *E = singletons.front(); E; E = E->next()) {
		if (E->get().name == p_name) {
			singletons.erase(E);
			singleton_ptrs.erase(p_name);
			return;
		}
	}
}

bool Engine::has_singleton(const StringName &p_name) const {
	return singleton_ptrs.has(p_name);
}

void Engine::get_singletons(List<Singleton> *p_singletons) {
	for (const Singleton &E : singletons) {
		p_singletons->push_back(E);
	}
}

String Engine::get_write_movie_path() const {
	return write_movie_path;
}

void Engine::set_write_movie_path(const String &p_path) {
	write_movie_path = p_path;
}

void Engine::set_shader_cache_path(const String &p_path) {
	shader_cache_path = p_path;
}
String Engine::get_shader_cache_path() const {
	return shader_cache_path;
}

Engine *Engine::singleton = nullptr;

Engine *Engine::get_singleton() {
	return singleton;
}

Engine::Engine() {
	singleton = this;
}

void Engine::startup_begin() {
	startup_benchmark_total_from = OS::get_singleton()->get_ticks_usec();
}

void Engine::startup_benchmark_begin_measure(const String &p_what) {
	startup_benchmark_section = p_what;
	startup_benchmark_from = OS::get_singleton()->get_ticks_usec();
}
void Engine::startup_benchmark_end_measure() {
	uint64_t total = OS::get_singleton()->get_ticks_usec() - startup_benchmark_from;
	double total_f = double(total) / double(1000000);

	startup_benchmark_json[startup_benchmark_section] = total_f;
}

void Engine::startup_dump(const String &p_to_file) {
	uint64_t total = OS::get_singleton()->get_ticks_usec() - startup_benchmark_total_from;
	double total_f = double(total) / double(1000000);
	startup_benchmark_json["total_time"] = total_f;

	if (!p_to_file.is_empty()) {
		Ref<FileAccess> f = FileAccess::open(p_to_file, FileAccess::WRITE);
		if (f.is_valid()) {
			Ref<JSON> json;
			json.instantiate();
			f->store_string(json->stringify(startup_benchmark_json, "\t", false, true));
		}
	} else {
		List<Variant> keys;
		startup_benchmark_json.get_key_list(&keys);
		print_line("STARTUP BENCHMARK:");
		for (const Variant &K : keys) {
			print_line("\t-", K, ": ", startup_benchmark_json[K], +" sec.");
		}
	}
}

Engine::Singleton::Singleton(const StringName &p_name, Object *p_ptr, const StringName &p_class_name) :
		name(p_name),
		ptr(p_ptr),
		class_name(p_class_name) {
#ifdef DEBUG_ENABLED
	RefCounted *rc = Object::cast_to<RefCounted>(p_ptr);
	if (rc && !rc->is_referenced()) {
		WARN_PRINT("You must use Ref<> to ensure the lifetime of a RefCounted object intended to be used as a singleton.");
	}
#endif
}


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

class Rentals extends CI_Controller {
	var $http_header;
	var $request_method;

	public function __construct() {
		parent::__construct();

		header("Content-Type: application/json");

		// Get PHP Header
		$this->http_header = getallheaders();

		// Get request method (GET, POST, PUT, DELETE)
		$this->request_method = $this->input->server('REQUEST_METHOD');

		// Check header accept parameter
		if($this->http_header['Accept'] != "application/json") {
			echo deliver_response(400, "fail", "Content Type Not Supported");
			exit;
		}
	}

	public function index($id = NULL) {
		if($this->request_method == "POST") {
			// if request method is POST, then insert rental

			// Check required parameter
			if(empty($this->input->post('car-id')) || empty($this->input->post('client-id')) || empty($this->input->post('date-from')) || empty($this->input->post('date-to'))) {
				echo deliver_response(400, "fail", "All fields are required.");
				exit;
			}

			// * Car id and client id must be exists.
			$car = $this->cars_m->get_car_by_id($this->input->post('car-id'))->result_array();
			$client = $this->clients_m->get_client_by_id($this->input->post('client-id'))->result_array();
			if(empty($car) || empty($client)) {
				echo deliver_response(400, "fail", "Car id and client id must be exists.");
				exit;
			}

			// * Client is not rent another car at selected rent date.
			$client_rent_car = $this->rentals_m->get_rental_by_client_id_and_rent_date($this->input->post('client-id'), $this->input->post('car-id'), $this->input->post('date-from'), $this->input->post('date-to'))->result_array();
			if($client_rent_car || !empty($client_rent_car)) {
				echo deliver_response(400, "fail", "Client is rented another car at selected rent date.");
				exit;
			}

			// * Car is not rented at selected rent date.
			$car_not_available = $this->rentals_m->get_rental_by_car_id_and_rent_date($this->input->post('car-id'), $this->input->post('date-from'), $this->input->post('date-to'), $this->input->post('id'))->result_array();
			if(!empty($car_not_available) || $car_not_available) {
				echo deliver_response(400, "fail", "Car is rented at selected rent date.");
				exit;
			}

			// * Rented duration max 3 days
			if(strtotime($this->input->post('date-to')) > strtotime("+3 days", strtotime($this->input->post('date-from')))) {
				echo deliver_response(400, "fail", "Rented duration max 3 days");
				exit;
			}

			// * Rent date only between current day + 1 days until current date +7 days.
			if(strtotime($this->input->post('date-to')) < strtotime($this->input->post('date-from'))
				|| ((strtotime($this->input->post('date-from')) < strtotime("today") || strtotime($this->input->post('date-from')) > strtotime("+1 days"))
				&& (strtotime($this->input->post('date-from')) > strtotime("today +7") || strtotime($this->input->post('date-to')) > strtotime("+7 days")))
				) {
				echo deliver_response(400, "fail", "Rent date only between current day +1 days until current date +7 days.");
				exit;
			}

			// Insert rental data
			$id = $this->rentals_m->add_rental();
			echo car_rental_response("id", $id);
			exit;
		}
		elseif($this->request_method == "PUT") {
			// if request method is PUT, then edit current rental data

			// This is how we get data when the server request is DELETE / PUT, for POST and GET can use normal $_GET / $_POST
			parse_str(file_get_contents("php://input"), $put_data);

			// Check required parameter
			if(empty($put_data['id']) || empty($put_data['car-id']) || empty($put_data['client-id']) || empty($put_data['date-from']) || empty($put_data['date-to'])) {
				echo deliver_response(400, "fail", "All fields are required.");
				exit;
			}

			// * Car id and client id must be exists.
			$car = $this->cars_m->get_car_by_id($put_data['car-id'])->result_array();
			$client = $this->clients_m->get_client_by_id($put_data['client-id'])->result_array();
			if(empty($car) || empty($client)) {
				echo deliver_response(400, "fail", "Car id and client id must be exists.");
				exit;
			}

			// * Client is not rent another car at selected rent date.
			$client_rent_car = $this->rentals_m->get_rental_by_client_id_and_rent_date($put_data['client-id'], $put_data['car-id'], $put_data['date-from'], $put_data['date-to'])->result_array();
			if($client_rent_car || !empty($client_rent_car)) {
				echo deliver_response(400, "fail", "Client is rented another car at selected rent date.");
				exit;
			}

			// * Car is not rented at selected rent date.
			$car_not_available = $this->rentals_m->get_rental_by_car_id_and_rent_date($put_data['car-id'], $put_data['date-from'], $put_data['date-to'], $put_data['id'])->result_array();
			if(!empty($car_not_available) || $car_not_available) {
				echo deliver_response(400, "fail", "Car is rented at selected rent date.");
				exit;
			}

			// * Rented duration max 3 days
			if(strtotime($put_data['date-to']) > strtotime("+3 days", strtotime($put_data['date-from']))) {
				echo deliver_response(400, "fail", "Rented duration max 3 days");
				exit;
			}

			// * Rent date only between current day + 1 days until current date +7 days.
			if(strtotime($put_data['date-to']) < strtotime($put_data['date-from'])
				|| ((strtotime($put_data['date-from']) < strtotime("today") || strtotime($put_data['date-from']) > strtotime("+1 days"))
				&& (strtotime($put_data['date-from']) > strtotime("today +7") || strtotime($put_data['date-to']) > strtotime("+7 days")))
				) {
				echo deliver_response(400, "fail", "Rent date only between current day +1 days until current date +7 days.");
				exit;
			}

			// Check current id on database
			$car = $this->rentals_m->get_rental_by_id($put_data['id'])->result_array();
			if(empty($car)) {
				echo deliver_response(400, "ok", "The ID must be exists on the database");
				exit;
			}

			// Update current rental data
			if($this->rentals_m->edit_rental($put_data['id'], $put_data)) {
				echo car_rental_response("status", "Update successful.");
				exit;
			}
			else {
				echo deliver_response(500, "fail", "The ID must be exists on the database");
				exit;
			}
		}
		elseif($this->request_method == "DELETE") {
			// if request method is DELETE, then delete current rental data

			// This is how we get data when the server request is DELETE / PUT, for POST and GET can use normal $_GET / $_POST
			parse_str(file_get_contents("php://input"), $delete_data);

			// Check required parameter
			if(empty($delete_data['id'])) {
				echo deliver_response(400, "fail", "All fields are required.");
				exit;
			}

			// Check current id on database
			$rental = $this->rentals_m->get_rental_by_id($delete_data['id'])->result_array();
			if(empty($rental)) {
				echo deliver_response(400, "ok", "The ID must be exists on the database");
				exit;
			}

			// Delete current rental data
			if($this->rentals_m->delete_rental($delete_data['id'])) {
				echo car_rental_response("status", "Delete successful.");
				exit;
			}
			else {
				echo deliver_response(500, "fail", "The ID must be exists on the database");
				exit;
			}
		}
		elseif($this->request_method == "GET") {
			// if request method is GET, then retrieve all rentals data

			$rentals = $this->rentals_m->get_all_rentals()->result_array();
			foreach($rentals as $rental) {
				$set_of_rentals[] = $rental;
			}

			echo car_rental_response("data", $set_of_rentals);
			exit;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
var async = require('async');

/**
 * Populates relationships on a document or array of documents
 *
 * WARNING: This is currently highly inefficient and should only be used in development, or for
 * small data sets. There are lots of things that can be done to improve performance... later.
 *
 * @api public
 */

module.exports = function populateRelated(docs, relationships, callback) {
	if (Array.isArray(docs)) {
		async.each(docs, function(doc, done) {
			doc.populateRelated(relationships, done);
		}, callback);
	} else if (docs && docs.populateRelated) {
		docs.populateRelated(relationships, callback);
	} else {
		callback();
	}
	return this;
};


text:
/*
Name: VS2012
Description: Visual Studio 2012 Light Theme
Version: 0.1
Author: Nikolay Zahariev
Url: http://nikolayzahariev.com/
*/
.crayon-theme-vs2012 {
	border-width: 1px !important;
	border-color: #999 !important;
	border-style: solid !important;
	text-shadow: none !important;
	background: #ffffff !important;
}
.crayon-theme-vs2012-inline {
	border-width: 1px !important;
	border-color: #ddd !important;
	border-style: solid !important;
	background: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-table .crayon-nums {
	background: #ffffff !important;
	color: #8ac1f8 !important;
}
.crayon-theme-vs2012 .crayon-striped-line {
	background: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-striped-num {
	background: #ffffff !important;
	color: #8ac1f8 !important;
}
.crayon-theme-vs2012 .crayon-marked-line {
	background: #d7dfe3 !important;
	border-width: 1px !important;
	border-color: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-marked-num {
	color: #8ac1f8 !important;
	background: #ffffff !important;
	border-width: 1px !important;
	border-color: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-marked-line.crayon-striped-line {
	background: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-marked-num.crayon-striped-num {
	background: #ffffff !important;
	color: #8ac1f8 !important;
}
.crayon-theme-vs2012 .crayon-marked-line.crayon-top {
	border-top-style: solid !important;
}
.crayon-theme-vs2012 .crayon-marked-num.crayon-top {
	border-top-style: solid !important;
}
.crayon-theme-vs2012 .crayon-marked-line.crayon-bottom {
	border-bottom-style: solid !important;
}
.crayon-theme-vs2012 .crayon-marked-num.crayon-bottom {
	border-bottom-style: solid !important;
}
.crayon-theme-vs2012 .crayon-info {
	background: #faf9d7 !important;
	border-bottom-width: 1px !important;
	border-bottom-color: #b1af5e !important;
	border-bottom-style: solid !important;
	color: #7e7d34 !important;
}
.crayon-theme-vs2012 .crayon-toolbar {
	background: #DDD !important;
	border-bottom-width: 1px !important;
	border-bottom-color: #BBB !important;
	border-bottom-style: solid !important;
}
.crayon-theme-vs2012 .crayon-toolbar > div {
	float: left !important;
}
.crayon-theme-vs2012 .crayon-toolbar .crayon-tools {
	float: right !important;
}
.crayon-theme-vs2012 .crayon-title {
	color: #333 !important;
}
.crayon-theme-vs2012 .crayon-language {
	color: #999 !important;
}
.crayon-theme-vs2012 a.crayon-button {
	background-color: transparent !important;
}
.crayon-theme-vs2012 a.crayon-button:hover {
	background-color: #EEE !important;
	color: #666;
}
.crayon-theme-vs2012 a.crayon-button.crayon-pressed:hover {
	background-color: #EEE !important;
	color: #666;
}
.crayon-theme-vs2012 a.crayon-button.crayon-pressed {
	background-color: #BCBCBC !important;
	color: #FFF;
}
.crayon-theme-vs2012 a.crayon-button.crayon-pressed:active {
	background-color: #BCBCBC !important;
	color: #FFF;
}
.crayon-theme-vs2012 a.crayon-button:active {
	background-color: #BCBCBC !important;
	color: #FFF;
}
.crayon-theme-vs2012 .crayon-pre .crayon-c {
	color: #008000 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-s {
	color: #6e1717 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-p {
	color: #b85c00 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-ta {
	color: #FF0000 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-k {
	color: #3215eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-st {
	color: #3215eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-r {
	color: #3215eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-t {
	color: #3215eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-m {
	color: #3215eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-i {
	color: #15a6eb !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-e {
	color: #000000 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-v {
	color: #002D7A !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-cn {
	color: #000000 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-o {
	color: #006fe0 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-sy {
	color: #333 !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-n {
	color: #666 !important;
	font-style: italic !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-f {
	color: #ffffff !important;
}
.crayon-theme-vs2012 .crayon-pre .crayon-h {
	color: #006fe0 !important;
}


text:
#ifndef MILL_CR_INCLUDED
#define MILL_CR_INCLUDED

#include <stdint.h>

#include "debug.h"
#include "list.h"
#include "slist.h"
#include "utils.h"

enum mill_state {
    MILL_READY,
    MILL_MSLEEP,
    MILL_FDWAIT,
    MILL_CHR,
    MILL_CHS,
    MILL_CHOOSE
};

struct mill_ready {
    struct mill_slist_item item;
};

/* This structure covers fdwait and msleep operations. */
struct mill_fdwait {
    /* Item in the global list of timers. */
    struct mill_list_item item;
    /* The timepoint when the timer expires. */
    int64_t expiry;
};

/* This structure covers chr, chs and choose operations. */
struct mill_choose {
    /* List of clauses in the 'choose' statement. */
    struct mill_slist clauses;
    /* 1 if there is 'otherwise' clause. 0 if there is not. */
    int othws;
    /* Number of clauses that are immediately available. */
    int available;
};

/* The coroutine. The memory layout looks like this:

   +----------------------------------------------------+--------+---------+
   |                                              stack | valbuf | mill_cr |
   +----------------------------------------------------+--------+---------+

   - mill_cr contains generic book-keeping info about the coroutine
   - valbuf is a buffer for temporary storing values received from channels
   - stack is a standard C stack; it grows downwards

*/
struct mill_cr {
    /* Status of the coroutine. Used for debugging purposes. */
    enum mill_state state;

    struct mill_ready u_ready;
    struct mill_fdwait u_fdwait;
    struct mill_choose u_choose;

    /* Stored coroutine context while it is not executing. */
    struct mill_ctx ctx;

    /* Argument to resume() call being passed to the blocked suspend() call. */
    int result;

    /* If size of the valbuf needs to be larger than mill_valbuf size it is
       allocated dyncamically and the pointer, along with the size of the buffer
       is stored here. */
    void *valbuf;
    size_t valbuf_sz;

    /* Coroutine-local storage. */
    void *cls;

    /* Debugging info. */
    struct mill_debug_cr debug;
};

/* Fake coroutine corresponding to the main thread of execution. */
extern struct mill_cr mill_main;

/* The coroutine that is running at the moment. */
extern struct mill_cr *mill_running;

/* Suspend running coroutine. Move to executing different coroutines. Once
   someone resumes this coroutine using mill_resume function 'result' argument
   of that function will be returned. */
int mill_suspend(void);

/* Schedules preiously suspended coroutine for execution. Keep in mind that
   it doesn't immediately run it, just puts it into the queue of ready
   coroutines. */
void mill_resume(struct mill_cr *cr, int result);

/* Returns pointer to the value buffer. The returned buffer is guaranteed
   to be at least 'size' bytes long. */
void *mill_valbuf(struct mill_cr *cr, size_t size);

#endif


text:
package com.haulmont.cuba.web.widgets.client.addons.aceeditor;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;

public class GwtTextDiff{

	public static final int DIFF_DELETE = -1;
	public static final int DIFF_INSERT = 1;
	public static final int DIFF_EQUAL = 0;

	public static final class Patch extends JavaScriptObject {

		protected Patch() {

		}

		native int getStart1() /*-{
			return this.start1;
		}-*/;

		native public JsArray<Diff> getDiffsJsArray() /*-{
			return this.diffs;
		}-*/;

		public List<Diff> getDiffs() {
			JsArray<Diff> diffs = getDiffsJsArray();
			LinkedList<Diff> dili = new LinkedList<Diff>();
			for (int i=0; i<diffs.length(); ++i) {
				dili.add(diffs.get(i));
			}
			return dili;
		}
	}

	public static final class Diff extends JavaScriptObject {

		protected Diff() {

		}

		public native int getOperation() /*-{
			return this[0];
		}-*/;

		public native String getText() /*-{
			return this[1];
		}-*/;
	}

	private static final DiffMatchPatchJSNI dmp = DiffMatchPatchJSNI
			.newInstance();

	private JsArray<Patch> patches;

//	public static final GwtTextDiff IDENTITY = new GwtTextDiff(Patch.createArray());

	public static GwtTextDiff diff(String v1, String v2) {
		return new GwtTextDiff(v1, v2);
	}

	private static GwtTextDiff fromPatches(JsArray<Patch> patches) {
		return new GwtTextDiff(patches);
	}

	private GwtTextDiff(JsArray<Patch> patches) {
		this.patches = patches;
	}

	private GwtTextDiff(String v1, String v2) {
		this.patches = dmp.patch_make_diff_main(v1, v2);
	}

	public String applyTo(String value) {
		return dmp.patch_apply(patches, value);
	}

	public boolean isIdentity() {
		return patches.length() == 0;
	}

	public String getDiffString() {
		return getDMP().patch_toText(patches);
	}

	public static int positionInNewText(String text1, int cursorPos,
			String text2) {
		// TODO: calculating the difference every time is a bit slow
		return dmp.diff_xIndex(dmp.diff_main(text1, text2), cursorPos);
	}

	public static DiffMatchPatchJSNI getDMP() {
		return dmp;
	}

	public static GwtTextDiff fromString(String s) {
		return fromPatches(dmp.patch_fromText(s));
	}

	public int adjustPosition(int pos) {
		return dmp.diff_xIndex_patches(patches, pos);
	}

	public List<Patch> getPatches() {
		LinkedList<Patch> pali = new LinkedList<Patch>();
		for (int i=0; i<patches.length(); ++i) {
			pali.add(patches.get(i));
		}
		return pali;
	}

}


text:
/*--------------------------------------------------------------------*/
/*--- System call wrappers, etc.                pub_core_syswrap.h ---*/
/*--------------------------------------------------------------------*/

/*
   This file is part of Valgrind, a dynamic binary instrumentation
   framework.

   Copyright (C) 2000-2015 Julian Seward
      jseward@acm.org

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307, USA.

   The GNU General Public License is contained in the file COPYING.
*/

#ifndef __PUB_CORE_SYSWRAP_H
#define __PUB_CORE_SYSWRAP_H

#include "pub_core_basics.h"        // VG_ macro
#include "pub_core_threadstate.h"   // ThreadArchState
#include "pub_core_tooliface.h"     // CorePart

//--------------------------------------------------------------------
// PURPOSE: This module contains all the syscall junk:  mostly PRE/POST
// wrappers, but also the main syscall jacketing code.
//--------------------------------------------------------------------

// Allocates a stack for the first thread, then runs it,
// as if the thread had been set up by clone()
extern void VG_(main_thread_wrapper_NORETURN)(ThreadId tid);

extern void VG_(client_syscall) ( ThreadId tid, UInt trc );

extern void VG_(post_syscall)   ( ThreadId tid );

/* Clear this module's private state for thread 'tid' */
extern void VG_(clear_syscallInfo) ( Int tid );

// Returns True if the given thread is currently in a system call
extern Bool VG_(is_in_syscall) ( Int tid );

// Fix up a thread's state when syscall is interrupted by a signal.
extern void VG_(fixup_guest_state_after_syscall_interrupted)(
               ThreadId tid,
               Addr     ip,
               SysRes   sysret,
               Bool     restart,
               struct vki_ucontext *uc
            );

#if defined(VGO_solaris)
// Determine if in a blocking syscall.
extern Bool VG_(is_ip_in_blocking_syscall)(ThreadId tid, Addr ip);
#endif

// Wait until all other threads are dead
extern void VG_(reap_threads)(ThreadId self);

// Release resources held by this thread
extern void VG_(cleanup_thread) ( ThreadArchState* );

/* fd leakage calls. */
extern void VG_(init_preopened_fds) ( void );
extern void VG_(show_open_fds) ( const HChar* when );

// When the final thread is done, where shall I call to shutdown the
// system cleanly?  Is set once at startup (in m_main) and never
// changes after that.  Is basically a pointer to the exit
// continuation.  This is all just a nasty hack to avoid calling
// directly from m_syswrap to m_main at exit, since that would cause
// m_main to become part of a module cycle, which is silly.
extern void (* VG_(address_of_m_main_shutdown_actions_NORETURN) )
            (ThreadId,VgSchedReturnCode);

#if defined(VGO_solaris)
extern void VG_(save_context)(ThreadId tid, vki_ucontext_t *uc,
                              CorePart part);
extern void VG_(restore_context)(ThreadId tid, vki_ucontext_t *uc,
                                 CorePart part, Bool esp_is_thrptr);
extern void VG_(syswrap_init)(void);
extern Bool VG_(setup_client_dataseg)(void);
extern void VG_(track_client_dataseg)(ThreadId tid);
#endif

#endif   // __PUB_CORE_SYSWRAP_H

/*--------------------------------------------------------------------*/
/*--- end                                                          ---*/
/*--------------------------------------------------------------------*/


text:
import sys
import json
import time
import datetime

from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from decimal import Decimal
from tempfile import NamedTemporaryFile

PY3 = sys.version_info[0] == 3

class PostgresToGoogleCloudStorageOperator(BaseOperator):
    """
    Copy data from Postgres to Google Cloud Storage in JSON format.
    """
    template_fields = ('sql', 'bucket', 'filename', 'schema_filename',
                       'parameters')
    template_ext = ('.sql', )
    ui_color = '#a0e08c'

    @apply_defaults
    def __init__(self,
                 sql,
                 bucket,
                 filename,
                 schema_filename=None,
                 approx_max_file_size_bytes=1900000000,
                 postgres_conn_id='postgres_default',
                 google_cloud_storage_conn_id='google_cloud_default',
                 delegate_to=None,
                 parameters=None,
                 *args,
                 **kwargs):
        """
        :param sql: The SQL to execute on the Postgres table.
        :type sql: str
        :param bucket: The bucket to upload to.
        :type bucket: str
        :param filename: The filename to use as the object name when uploading
            to Google Cloud Storage. A {} should be specified in the filename
            to allow the operator to inject file numbers in cases where the
            file is split due to size.
        :type filename: str
        :param schema_filename: If set, the filename to use as the object name
            when uploading a .json file containing the BigQuery schema fields
            for the table that was dumped from Postgres.
        :type schema_filename: str
        :param approx_max_file_size_bytes: This operator supports the ability
            to split large table dumps into multiple files (see notes in the
            filenamed param docs above). Google Cloud Storage allows for files
            to be a maximum of 4GB. This param allows developers to specify the
            file size of the splits.
        :type approx_max_file_size_bytes: long
        :param postgres_conn_id: Reference to a specific Postgres hook.
        :type postgres_conn_id: str
        :param google_cloud_storage_conn_id: Reference to a specific Google
            cloud storage hook.
        :type google_cloud_storage_conn_id: str
        :param delegate_to: The account to impersonate, if any. For this to
            work, the service account making the request must have domain-wide
            delegation enabled.
        :param parameters: a parameters dict that is substituted at query runtime.
        :type parameters: dict
        """
        super(PostgresToGoogleCloudStorageOperator, self).__init__(*args, **kwargs)
        self.sql = sql
        self.bucket = bucket
        self.filename = filename
        self.schema_filename = schema_filename
        self.approx_max_file_size_bytes = approx_max_file_size_bytes
        self.postgres_conn_id = postgres_conn_id
        self.google_cloud_storage_conn_id = google_cloud_storage_conn_id
        self.delegate_to = delegate_to
        self.parameters = parameters

    def execute(self, context):
        cursor = self._query_postgres()
        files_to_upload = self._write_local_data_files(cursor)

        # If a schema is set, create a BQ schema JSON file.
        if self.schema_filename:
            files_to_upload.update(self._write_local_schema_file(cursor))

        # Flush all files before uploading
        for file_handle in files_to_upload.values():
            file_handle.flush()

        self._upload_to_gcs(files_to_upload)

        # Close all temp file handles.
        for file_handle in files_to_upload.values():
            file_handle.close()

    def _query_postgres(self):
        """
        Queries Postgres and returns a cursor to the results.
        """
        postgres = PostgresHook(postgres_conn_id=self.postgres_conn_id)
        conn = postgres.get_conn()
        cursor = conn.cursor()
        cursor.execute(self.sql, self.parameters)
        return cursor

    def _write_local_data_files(self, cursor):
        """
        Takes a cursor, and writes results to a local file.

        :return: A dictionary where keys are filenames to be used as object
            names in GCS, and values are file handles to local files that
            contain the data for the GCS objects.
        """
        schema = list(map(lambda schema_tuple: schema_tuple[0], cursor.description))
        file_no = 0
        tmp_file_handle = NamedTemporaryFile(delete=True)
        tmp_file_handles = {self.filename.format(file_no): tmp_file_handle}

        for row in cursor:
            # Convert datetime objects to utc seconds, and decimals to floats
            row = map(self.convert_types, row)
            row_dict = dict(zip(schema, row))

            s = json.dumps(row_dict, sort_keys=True)
            if PY3:
                s = s.encode('utf-8')
            tmp_file_handle.write(s)

            # Append newline to make dumps BigQuery compatible.
            tmp_file_handle.write(b'\n')

            # Stop if the file exceeds the file size limit.
            if tmp_file_handle.tell() >= self.approx_max_file_size_bytes:
                file_no += 1
                tmp_file_handle = NamedTemporaryFile(delete=True)
                tmp_file_handles[self.filename.format(file_no)] = tmp_file_handle

        return tmp_file_handles

    def _write_local_schema_file(self, cursor):
        """
        Takes a cursor, and writes the BigQuery schema for the results to a
        local file system.

        :return: A dictionary where key is a filename to be used as an object
            name in GCS, and values are file handles to local files that
            contains the BigQuery schema fields in .json format.
        """
        schema = []
        for field in cursor.description:
            # See PEP 249 for details about the description tuple.
            field_name = field[0]
            field_type = self.type_map(field[1])
            field_mode = 'REPEATED' if field[1] in (1009, 1005, 1007,
                                                    1016) else 'NULLABLE'
            schema.append({
                'name': field_name,
                'type': field_type,
                'mode': field_mode,
            })

        self.log.info('Using schema for %s: %s', self.schema_filename, schema)
        tmp_schema_file_handle = NamedTemporaryFile(delete=True)
        s = json.dumps(schema, sort_keys=True)
        if PY3:
            s = s.encode('utf-8')
        tmp_schema_file_handle.write(s)
        return {self.schema_filename: tmp_schema_file_handle}

    def _upload_to_gcs(self, files_to_upload):
        """
        Upload all of the file splits (and optionally the schema .json file) to
        Google Cloud Storage.
        """
        hook = GoogleCloudStorageHook(
            google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,
            delegate_to=self.delegate_to)
        for object, tmp_file_handle in files_to_upload.items():
            hook.upload(self.bucket, object, tmp_file_handle.name,
                        'application/json')

    @classmethod
    def convert_types(cls, value):
        """
        Takes a value from Postgres, and converts it to a value that's safe for
        JSON/Google Cloud Storage/BigQuery. Dates are converted to UTC seconds.
        Decimals are converted to floats. Times are converted to seconds.
        """
        if type(value) in (datetime.datetime, datetime.date):
            return time.mktime(value.timetuple())
        elif type(value) == datetime.time:
            formated_time = time.strptime(str(value), "%H:%M:%S")
            return datetime.timedelta(
                hours=formated_time.tm_hour,
                minutes=formated_time.tm_min,
                seconds=formated_time.tm_sec).seconds
        elif isinstance(value, Decimal):
            return float(value)
        else:
            return value

    @classmethod
    def type_map(cls, postgres_type):
        """
        Helper function that maps from Postgres fields to BigQuery fields. Used
        when a schema_filename is set.
        """
        d = {
            1114: 'TIMESTAMP',
            1184: 'TIMESTAMP',
            1082: 'TIMESTAMP',
            1083: 'TIMESTAMP',
            1005: 'INTEGER',
            1007: 'INTEGER',
            1016: 'INTEGER',
            20: 'INTEGER',
            21: 'INTEGER',
            23: 'INTEGER',
            16: 'BOOLEAN',
            700: 'FLOAT',
            701: 'FLOAT',
            1700: 'FLOAT'
        }

        return d[postgres_type] if postgres_type in d else 'STRING'


text:
class Admin::ProductsController < Admin::BaseController
  include AdminActions # See /app/concerns/admin_actions.rb

private
  def strong_params
    %w(
      active name price resume preview description
      seo_title seo_h1 seo_description seo_keywords
    )
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Simple Node Express</title>
    <link rel="stylesheet" href="css/app.css" media="screen" title="no title">

Test HTML Output

Powered by Node and Express © 2016-2017 Codedungeon


text:
package org.conqat.engine.core.bundle;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

import org.apache.tools.ant.BuildException;
import org.conqat.lib.commons.filesystem.FileOnlyFilter;
import org.conqat.lib.commons.filesystem.FileSystemUtils;

/**
 * This task creates a single jar file for a bundles classes and libraries plus
 * all classes the bundle depends on. Additional libraries and directories, e.g.
 * the libraries ConQAT core depends on, may be added manually. The name of the
 * jar file is <bundle-id>.jar.
 *

 * See conqat-ant-base for usage of this task.
 *
 * @author deissenb
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 8739CB14CFA75EB87032FA77F2E37309
 */
public class BundleJarTask extends BundleTaskBase {

	/** List of additional libraries. */
	private final List<AntElement> libraries = new ArrayList<AntElement>();

	/** List of additional directories. */
	private final List<AntElement> directories = new ArrayList<AntElement>();

	/** Set of libraries that should be excluded from jar file. */
	private final HashSet<String> excludedLibraries = new HashSet<String>();

	/**
	 * This set is used to prevent duplicate entries in the jar file causing
	 * exceptions.
	 */
	private final HashSet<String> jarEntries = new HashSet<String>();

	/** Counts the number of files added to jar for logging purposes. */
	private int fileCount;

	/** This stream is used to create the jar file. */
	private JarOutputStream outStream;

	/** Add an additional library. Called by ANT for <library>-elements. */
	public void addLibrary(AntElement library) {
		libraries.add(library);
	}

	/**
	 * Add an additional directory. Called by ANT for
	 * <directory>-elements.
	 */
	public void addDirectory(AntElement directory) {
		directories.add(directory);
	}

	/**
	 * Set comma separated list of libraries to exclude, eg.
	 * servlet-api.jar, ant.jar. This is encoded in a single string
	 * to allow users of conqat-ant-base to set this parameter by
	 * specifying a property.
	 */
	public void setExcludedLibraries(String libraries) {
		for (String library : libraries.split(",")) {
			excludedLibraries.add(library.trim());
		}
	}

	/** Create jar file. */
	@Override
	protected void execute(Set<BundleInfo> bundleClosure) throws BuildException {

		File jarFile = new File(getProject().getBaseDir().getName() + ".jar");
		jarEntries.clear();
		fileCount = 0;

		try {

			outStream = new JarOutputStream(new FileOutputStream(jarFile));

			addBundles(bundleClosure);

			// add additional libraries and directories
			for (AntElement library : libraries) {
				addJar(new File(library.getName()));
			}
			for (AntElement directory : directories) {
				addDirectory(new File(directory.getName()));
			}

			outStream.close();

			System.out.println("Created " + jarFile.getName() + " from "
					+ fileCount + " files.");

		} catch (IOException e) {
			throw new BuildException(e);
		}

	}

	/** Add all bundles of the bundle closure. */
	private void addBundles(Set<BundleInfo> bundleClosure) throws IOException {
		for (BundleInfo bundleInfo : bundleClosure) {
			addBundle(bundleInfo);
		}
	}

	/** Add libraries and classes directory for a bundle to the jar file. */
	private void addBundle(BundleInfo bundleInfo) throws IOException {
		for (File library : bundleInfo.getLibraries()) {
			addJar(library);

		}
		if (bundleInfo.hasClasses()) {
			addDirectory(bundleInfo.getClassesDirectory());
		}
	}

	/** Add all members of a jar file to the result jar file. */
	private void addJar(File jarFile) throws IOException {

		if (excludedLibraries.contains(jarFile.getName())) {
			System.out.println("Skipping excluded library " + jarFile.getName()
					+ ".");
			return;
		}

		JarFile jar = new JarFile(jarFile);
		Enumeration<JarEntry> entries = jar.entries();

		while (entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
			if (!entry.isDirectory()) {
				InputStream entryStream = jar.getInputStream(entry);
				createJarEntry(entryStream, entry.getName());
			}
		}

	}

	/** Add all files of a directory to the result jar file. */
	private void addDirectory(File directory) throws IOException {
		List<File> files = FileSystemUtils.listFilesRecursively(directory,
				new FileOnlyFilter());

		for (File file : files) {
			FileInputStream input = new FileInputStream(file);
			String entryName = file.getAbsolutePath().substring(
					directory.getAbsolutePath().length() + 1);
			// works for forward slashes only
			entryName = entryName.replace(File.separatorChar, '/');

			createJarEntry(input, entryName);
		}
	}

	/**
	 * Create new jar entry. This creates the entry, copies the input stream to
	 * the jar file and closes the input stream.
	 */
	private void createJarEntry(InputStream input, String entryName)
			throws IOException {
		if (jarEntries.contains(entryName)) {
			System.out.println("Skipping duplicate entry " + entryName + ".");
			return;
		}
		outStream.putNextEntry(new ZipEntry(entryName));
		FileSystemUtils.copy(input, outStream);
		outStream.closeEntry();
		input.close();
		jarEntries.add(entryName);
		fileCount++;
	}

}


text:
package org.pa.library.dao;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.pa.library.model.Library;
public class XMLHelper {

	public static void writeToXML(Library library) {
		try {
			JAXBContext context = JAXBContext.newInstance(Library.class);
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			FileWriter fileWriter = new FileWriter(Library.LIBRARY_FILE, false);
			marshaller.marshal(library, fileWriter);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Library readFromXML() {
		File libraryFile = new File(Library.LIBRARY_FILE);
		boolean fileExists = libraryFile.exists() && libraryFile.length()>0;
		if (! fileExists)
			throw new RuntimeException("File '" + libraryFile.getPath() + "' does not exist.");

		try {
			JAXBContext context = JAXBContext.newInstance(Library.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();

			FileReader fileReader = new FileReader(libraryFile);
			Library unmarshalledLibrary = (Library) unmarshaller.unmarshal(fileReader);
			return unmarshalledLibrary;

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}


text:
@implementation GestureControlViewController {
  GMSMapView *_mapView;
  UISwitch *_zoomSwitch;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-25.5605
                                                          longitude:133.605097
                                                               zoom:3];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

  self.view = [[UIView alloc] initWithFrame:CGRectZero];
  [self.view addSubview:_mapView];

  UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 59)];
  holder.autoresizingMask =
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
  holder.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8f];
  [self.view addSubview:holder];

  // Zoom label.
  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 200, 29)];
  label.text = @"Zooming?";
  label.font = [UIFont boldSystemFontOfSize:18.0f];
  label.textAlignment = NSTextAlignmentLeft;
  label.backgroundColor = [UIColor clearColor];
  label.layer.shadowColor = [[UIColor whiteColor] CGColor];
  label.layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
  label.layer.shadowOpacity = 1.0f;
  label.layer.shadowRadius = 0.0f;
  [holder addSubview:label];

  // Control zooming.
  _zoomSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(-90, 16, 0, 0)];
  _zoomSwitch.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  [_zoomSwitch addTarget:self
                  action:@selector(didChangeZoomSwitch)
        forControlEvents:UIControlEventValueChanged];
  _zoomSwitch.on = YES;
  [holder addSubview:_zoomSwitch];
}

- (void)didChangeZoomSwitch {
  _mapView.settings.zoomGestures = _zoomSwitch.isOn;
}

@end


text:
import collections
from functools import partial
import operator

from .. import graph_util
from ..namegen import NameGen
from ..ssa import objtypes
from ..verifier.descriptors import parseMethodDescriptor

from . import ast, ast2, astgen, boolize, graphproxy, mergevariables, structuring

class DeclInfo(object):
    __slots__ = "declScope scope defs".split()
    def __init__(self):
        self.declScope = self.scope = None
        self.defs = []

def findVarDeclInfo(root, predeclared):
    info = collections.OrderedDict()
    def visit(scope, expr):
        for param in expr.params:
            visit(scope, param)

        if expr.isLocalAssign():
            left, right = expr.params
            info[left].defs.append(right)
        elif isinstance(expr, (ast.Local, ast.Literal)):
            # this would be so much nicer if we had Ordered defaultdicts
            info.setdefault(expr, DeclInfo())
            info[expr].scope = ast.StatementBlock.join(info[expr].scope, scope)

    def visitDeclExpr(scope, expr):
        info.setdefault(expr, DeclInfo())
        assert scope is not None and info[expr].declScope is None
        info[expr].declScope = scope

    for expr in predeclared:
        visitDeclExpr(root, expr)

    stack = [(root,root)]
    while stack:
        scope, stmt = stack.pop()
        if isinstance(stmt, ast.StatementBlock):
            stack.extend((stmt,sub) for sub in stmt.statements)
        else:
            stack.extend((subscope,subscope) for subscope in stmt.getScopes())
            # temp hack
            if stmt.expr is not None:
                visit(scope, stmt.expr)
            if isinstance(stmt, ast.TryStatement):
                for catchdecl, body in stmt.pairs:
                    visitDeclExpr(body, catchdecl.local)
    return info

def reverseBoolExpr(expr):
    assert expr.dtype == objtypes.BoolTT
    if isinstance(expr, ast.BinaryInfix):
        symbols = "== != < >= > <=".split()
        floatts = (objtypes.FloatTT, objtypes.DoubleTT)
        if expr.opstr in symbols:
            sym2 = symbols[symbols.index(expr.opstr) ^ 1]
            left, right = expr.params
            # be sure not to reverse floating point comparisons since it's not equivalent for NaN
            if expr.opstr in symbols[:2] or (left.dtype not in floatts and right.dtype not in floatts):
                return ast.BinaryInfix(sym2, [left, right], objtypes.BoolTT)
    elif isinstance(expr, ast.UnaryPrefix) and expr.opstr == '!':
        return expr.params[0]
    return ast.UnaryPrefix('!', expr)

def getSubscopeIter(root):
    stack = [root]
    while stack:
        scope = stack.pop()
        if isinstance(scope, ast.StatementBlock):
            stack.extend(scope.statements)
            yield scope
        else:
            stack.extend(scope.getScopes())

def mayBreakTo(root, forbidden):
    assert None not in forbidden
    for scope in getSubscopeIter(root):
        if scope.jumpKey in forbidden:
            # We return true if scope has forbidden jump and is reachable
            # We assume there is no unreachable code, so in order for a scope
            # jump to be unreachable, it must end in a return, throw, or a
            # compound statement, all of which are not reachable or do not
            # break out of the statement. We omit adding last.breakKey to
            # forbidden since it should always match scope.jumpKey anyway
            if not scope.statements:
                return True
            last = scope.statements[-1]
            if not last.getScopes():
                if not isinstance(last, (ast.ReturnStatement, ast.ThrowStatement)):
                    return True
            else:
                # If and switch statements may allow fallthrough
                # A while statement with condition may break implicitly
                if isinstance(last, ast.IfStatement) and len(last.getScopes()) == 1:
                    return True
                if isinstance(last, ast.SwitchStatement) and not last.hasDefault():
                    return True
                if isinstance(last, ast.WhileStatement) and last.expr != ast.Literal.TRUE:
                    return True

                if not isinstance(last, ast.WhileStatement):
                    for sub in last.getScopes():
                        assert sub.breakKey == last.breakKey == scope.jumpKey
    return False

def replaceKeys(top, replace):
    assert None not in replace
    get = lambda k:replace.get(k,k)

    if top.getScopes():
        if isinstance(top, ast.StatementBlock) and get(top.breakKey) is None:
            # breakKey can be None with non-None jumpKey when we're a scope in a switch statement that falls through
            # and the end of the switch statement is unreachable
            assert get(top.jumpKey) is None or not top.labelable

        top.breakKey = get(top.breakKey)
        if isinstance(top, ast.StatementBlock):
            top.jumpKey = get(top.jumpKey)
            for item in top.statements:
                replaceKeys(item, replace)
        else:
            for scope in top.getScopes():
                replaceKeys(scope, replace)

NONE_SET = frozenset([None])
def _preorder(scope, func):
    newitems = []
    for i, item in enumerate(scope.statements):
        for sub in item.getScopes():
            _preorder(sub, func)

        val = func(scope, item)
        vals = [item] if val is None else val
        newitems.extend(vals)
    scope.statements = newitems

def _fixObjectCreations(scope, item):
    '''Combines new/invokeinit pairs into Java constructor calls'''
    # Thanks to the uninitialized variable merging prior to AST generation,
    # we can safely assume there are no copies to worry about
    expr = item.expr
    if isinstance(expr, ast.Assignment):
        left, right = expr.params
        if isinstance(right, ast.Dummy) and right.isNew:
            return [] # remove item
    elif isinstance(expr, ast.MethodInvocation) and expr.name == '<init>':
        left = expr.params[0]
        newexpr = ast.ClassInstanceCreation(ast.TypeName(left.dtype), expr.tts[1:], expr.params[1:])
        item.expr = ast.Assignment(left, newexpr)

def _pruneRethrow_cb(item):
    '''Convert try{A} catch(T t) {throw t;} to {A}'''
    while item.pairs:
        decl, body = item.pairs[-1]
        caught, lines = decl.local, body.statements

        if len(lines) == 1:
            line = lines[0]
            if isinstance(line, ast.ThrowStatement) and line.expr == caught:
                item.pairs = item.pairs[:-1]
                continue
        break
    if not item.pairs:
        new = item.tryb
        assert new.breakKey == item.breakKey
        assert new.continueKey == item.continueKey
        assert not new.labelable
        new.labelable = True
        return new
    return item

def _pruneIfElse_cb(item):
    '''Convert if(A) {B} else {} to if(A) {B}'''
    if len(item.scopes) > 1:
        tblock, fblock = item.scopes

        # if true block is empty, swap it with false so we can remove it
        if not tblock.statements and tblock.doesFallthrough():
            item.expr = reverseBoolExpr(item.expr)
            tblock, fblock = item.scopes = fblock, tblock

        if not fblock.statements and fblock.doesFallthrough():
            item.scopes = tblock,

    # if(A) {B throw/return ... } else {C} -> if(A) {B throw/return ...} {C}
    if len(item.scopes) > 1:
        # How much we want the block to be first, or (3, 0) if it can't be simplified
        def priority(block):
            # If an empty block survives to this point, it must end in a break so we can simplify in this case too
            if not block.statements:
                return 2, 0
            # If any complex statements, there might be a labeled break, so it's not safe
            if any(stmt.getScopes() for stmt in block.statements):
                return 3, 0
            # prefer if(...) {throw...} return... to if(...) {return...} throw...
            if isinstance(block.statements[-1], ast.ThrowStatement):
                return 0, len(block.statements)
            elif isinstance(block.statements[-1], ast.ReturnStatement):
                return 1, len(block.statements)
            return 3, 0

        if priority(fblock) < priority(tblock):
            item.expr = reverseBoolExpr(item.expr)
            tblock, fblock = item.scopes = fblock, tblock

        if priority(tblock) < (3, 0):
            assert tblock.statements or not tblock.doesFallthrough()
            item.scopes = tblock,
            item.breakKey = fblock.continueKey
            fblock.labelable = True
            return [item], fblock

        # If cond is !(x), reverse it back to simplify cond
        if isinstance(item.expr, ast.UnaryPrefix) and item.expr.opstr == '!':
            item.expr = reverseBoolExpr(item.expr)
            tblock, fblock = item.scopes = fblock, tblock

    # if(A) {if(B) {C}} -> if(A && B) {C}
    tblock = item.scopes[0]
    if len(item.scopes) == 1 and len(tblock.statements) == 1 and tblock.doesFallthrough():
        first = tblock.statements[0]
        if isinstance(first, ast.IfStatement) and len(first.scopes) == 1:
            item.expr = ast.BinaryInfix('&&',[item.expr, first.expr], objtypes.BoolTT)
            item.scopes = first.scopes
    return [], item

def _whileCondition_cb(item):
    '''Convert while(true) {if(A) {B break;} else {C} D} to while(!A) {{C} D} {B}
        and while(A) {if(B) {break;} else {C} D} to while(A && !B) {{C} D}'''
    failure = [], item # what to return if we didn't inline
    body = item.getScopes()[0]
    if not body.statements or not isinstance(body.statements[0], ast.IfStatement):
        return failure

    head = body.statements[0]
    cond = head.expr
    trueb, falseb = (head.getScopes() + (None,))[:2]

    # Make sure it doesn't continue the loop or break out of the if statement
    badjumps1 = frozenset([head.breakKey, item.continueKey]) - NONE_SET
    if mayBreakTo(trueb, badjumps1):
        if falseb is not None and not mayBreakTo(falseb, badjumps1):
            cond = reverseBoolExpr(cond)
            trueb, falseb = falseb, trueb
        else:
            return failure
    assert not mayBreakTo(trueb, badjumps1)

    trivial = not trueb.statements and trueb.jumpKey == item.breakKey
    # If we already have a condition, only a simple break is allowed
    if not trivial and item.expr != ast.Literal.TRUE:
        return failure

    # If break body is nontrival, we can't insert this after the end of the loop unless
    # We're sure that nothing else in the loop breaks out
    badjumps2 = frozenset([item.breakKey]) - NONE_SET
    if not trivial:
        restloop = [falseb] if falseb is not None else []
        restloop += body.statements[1:]
        if body.jumpKey == item.breakKey or any(mayBreakTo(s, badjumps2) for s in restloop):
            return failure

    # Now inline everything
    item.expr = _simplifyExpressions(ast.BinaryInfix('&&', [item.expr, reverseBoolExpr(cond)]))
    if falseb is None:
        body.continueKey = body.statements.pop(0).breakKey
    else:
        body.continueKey = falseb.continueKey
        body.statements[0] = falseb
        falseb.labelable = True
    trueb.labelable = True

    if item.breakKey is None: # Make sure to maintain invariant that bkey=None -> jkey=None
        assert trueb.doesFallthrough()
        trueb.jumpKey = trueb.breakKey = None
    trueb.breakKey = item.breakKey
    assert trueb.continueKey is not None
    if not trivial:
        item.breakKey = trueb.continueKey

    # Trueb doesn't break to head.bkey but there might be unreacahble jumps, so we replace
    # it too. We don't replace item.ckey because it should never appear, even as an
    # unreachable jump
    replaceKeys(trueb, {head.breakKey:trueb.breakKey, item.breakKey:trueb.breakKey})
    return [item], trueb

def _simplifyBlocksSub(scope, item, isLast):
    rest = []
    if isinstance(item, ast.TryStatement):
        item = _pruneRethrow_cb(item)
    elif isinstance(item, ast.IfStatement):
        rest, item = _pruneIfElse_cb(item)
    elif isinstance(item, ast.WhileStatement):
        rest, item = _whileCondition_cb(item)

    if isinstance(item, ast.StatementBlock):
        assert item.breakKey is not None or item.jumpKey is None
        # If bkey is None, it can't be broken to
        # If contents can also break to enclosing scope, it's always safe to inline
        bkey = item.breakKey
        if bkey is None or (bkey == scope.breakKey and scope.labelable):
            rest, item.statements = rest + item.statements, []
        # Now inline statements at the beginning of the scope that don't need to break to it
        for sub in item.statements[:]:
            if sub.getScopes() and sub.breakKey != bkey and mayBreakTo(sub, frozenset([bkey])):
                break
            rest.append(item.statements.pop(0))

        if not item.statements:
            if item.jumpKey != bkey:
                assert isLast
                scope.jumpKey = item.jumpKey
                assert scope.breakKey is not None or scope.jumpKey is None
            return rest
    return rest + [item]

def _simplifyBlocks(scope):
    newitems = []
    for item in reversed(scope.statements):
        isLast = not newitems # may be true if all subsequent items pruned
        if isLast and item.getScopes():
            if item.breakKey != scope.jumpKey:# and item.breakKey is not None:
                replaceKeys(item, {item.breakKey: scope.jumpKey})

        for sub in reversed(item.getScopes()):
            _simplifyBlocks(sub)
        vals = _simplifyBlocksSub(scope, item, isLast)
        newitems += reversed(vals)
    scope.statements = newitems[::-1]

_op2bits = {'==':2, '!=':13, '<':1, '<=':3, '>':4, '>=':6}
_bit2ops_float = {v:k for k,v in _op2bits.items()}
_bit2ops = {(v & 7):k for k,v in _op2bits.items()}

def _getBitfield(expr):
    if isinstance(expr, ast.BinaryInfix):
        if expr.opstr in ('==','!=','<','<=','>','>='):
            # We don't want to merge expressions if they could have side effects
            # so only allow literals and locals
            if all(isinstance(p, (ast.Literal, ast.Local)) for p in expr.params):
                return _op2bits[expr.opstr], list(expr.params)
        elif expr.opstr in ('&','&&','|','||'):
            bits1, args1 = _getBitfield(expr.params[0])
            bits2, args2 = _getBitfield(expr.params[1])
            if args1 == args2:
                bits = (bits1 & bits2) if '&' in expr.opstr else (bits1 | bits2)
                return bits, args1
    elif isinstance(expr, ast.UnaryPrefix) and expr.opstr == '!':
        bits, args = _getBitfield(expr.params[0])
        return ~bits, args
    return 0, None

def _mergeComparisons(expr):
    # a <= b && a != b -> a < b, etc.
    bits, args = _getBitfield(expr)
    if args is None:
        return expr

    assert not hasSideEffects(args[0]) and not hasSideEffects(args[1])
    if args[0].dtype in (objtypes.FloatTT, objtypes.DoubleTT):
        mask, d = 15, _bit2ops_float
    else:
        mask, d = 7, _bit2ops

    bits &= mask
    notbits = (~bits) & mask

    if bits == 0:
        return ast.Literal.TRUE
    elif notbits == 0:
        return ast.Literal.FALSE
    elif bits in d:
        return ast.BinaryInfix(d[bits], args, objtypes.BoolTT)
    elif notbits in d:
        return ast.UnaryPrefix('!', ast.BinaryInfix(d[notbits], args, objtypes.BoolTT))
    return expr

def _simplifyExpressions(expr):
    TRUE, FALSE = ast.Literal.TRUE, ast.Literal.FALSE
    bools = {True:TRUE, False:FALSE}
    opfuncs = {'<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge}

    simplify = _simplifyExpressions
    expr.params = map(simplify, expr.params)

    if isinstance(expr, ast.BinaryInfix):
        left, right = expr.params
        op = expr.opstr
        if op in ('==','!=','<','<=','>','>=') and isinstance(right, ast.Literal):
            # la cmp lb -> result (i.e. constant propagation on literal comparisons)
            if isinstance(left, ast.Literal):
                if op in ('==','!='):
                    # these could be string or class literals, but those are always nonnull so it still works
                    res = (left == right) == (op == '==')
                else:
                    assert left.dtype == right.dtype
                    res = opfuncs[op](left.val, right.val)
                expr = bools[res]
            # (a ? lb : c) cmp ld -> a ? (lb cmp ld) : (c cmp ld)
            elif isinstance(left, ast.Ternary) and isinstance(left.params[1], ast.Literal):
                left.params[1] = simplify(ast.BinaryInfix(op, [left.params[1], right], expr._dtype))
                left.params[2] = simplify(ast.BinaryInfix(op, [left.params[2], right], expr._dtype))
                expr = left

    # a ? true : b -> a || b
    # a ? false : b -> !a && b
    if isinstance(expr, ast.Ternary) and expr.dtype == objtypes.BoolTT:
        cond, val1, val2 = expr.params
        if not isinstance(val1, ast.Literal): # try to get bool literal to the front
            cond, val1, val2 = reverseBoolExpr(cond), val2, val1

        if val1 == TRUE:
            expr = ast.BinaryInfix('||', [cond, val2], objtypes.BoolTT)
        elif val1 == FALSE:
            expr = ast.BinaryInfix('&&', [reverseBoolExpr(cond), val2], objtypes.BoolTT)

    # true && a -> a, etc.
    if isinstance(expr, ast.BinaryInfix) and expr.opstr in ('&&','||'):
        left, right = expr.params
        if expr.opstr == '&&':
            if left == TRUE or (right == FALSE and not hasSideEffects(left)):
                expr = right
            elif left == FALSE or right == TRUE:
                expr = left
        else:
            if left == TRUE or right == FALSE:
                expr = left
            elif left == FALSE or (right == TRUE and not hasSideEffects(left)):
                expr = right
        # a > b || a == b -> a >= b, etc.
        expr = _mergeComparisons(expr)

    # a == true -> a
    # a == false -> !a
    if isinstance(expr, ast.BinaryInfix) and expr.opstr in ('==, !=') and expr.params[0].dtype == objtypes.BoolTT:
        left, right = expr.params
        if not isinstance(left, ast.Literal): # try to get bool literal to the front
            left, right = right, left
        if isinstance(left, ast.Literal):
            flip = (left == TRUE) != (expr.opstr == '==')
            expr = reverseBoolExpr(right) if flip else right

    # !a ? b : c -> a ? c : b
    if isinstance(expr, ast.Ternary) and isinstance(expr.params[0], ast.UnaryPrefix):
        cond, val1, val2 = expr.params
        if cond.opstr == '!':
            expr.params = [reverseBoolExpr(cond), val2, val1]

    # 0 - a -> -a
    if isinstance(expr, ast.BinaryInfix) and expr.opstr == '-':
        if expr.params[0] == ast.Literal.ZERO or expr.params[0] == ast.Literal.LZERO:
            expr = ast.UnaryPrefix('-', expr.params[1])

    # (double)4.2f -> 4.2, etc.
    if isinstance(expr, ast.Cast) and isinstance(expr.params[1], ast.Literal):
        expr = ast.makeCastExpr(expr.dtype, expr.params[1])

    return expr

def _setScopeParents(scope):
    for item in scope.statements:
        for sub in item.getScopes():
            sub.bases = scope.bases + (sub,)
            _setScopeParents(sub)

def _replaceExpressions(scope, item, rdict):
    # Must be done before local declarations are created since it doesn't touch/remove them
    if item.expr is not None:
        item.expr = item.expr.replaceSubExprs(rdict)
    # remove redundant assignments i.e. x=x;
    if isinstance(item.expr, ast.Assignment):
        assert isinstance(item, ast.ExpressionStatement)
        left, right = item.expr.params
        if left == right:
            return []
    return [item]

def _oldMergeVariables(root, predeclared):
    _setScopeParents(root)
    info = findVarDeclInfo(root, predeclared)

    lvars = [expr for expr in info if isinstance(expr, ast.Local)]
    forbidden = set()
    # If var has any defs which aren't a literal or local, mark it as a leaf node (it can't be merged into something)
    for var in lvars:
        if not all(isinstance(expr, (ast.Local, ast.Literal)) for expr in info[var].defs):
            forbidden.add(var)
        elif info[var].declScope is not None:
            forbidden.add(var)

    sccs = graph_util.tarjanSCC(lvars, lambda var:([] if var in forbidden else info[var].defs))
    # the sccs will be in topolgical order
    varmap = {}
    for scc in sccs:
        if forbidden.isdisjoint(scc):
            alldefs = []
            for expr in scc:
                for def_ in info[expr].defs:
                    if def_ not in scc:
                        alldefs.append(varmap[def_])
            if len(set(alldefs)) == 1:
                target = alldefs[0]
                if all(var.dtype == target.dtype for var in scc):
                    scope = ast.StatementBlock.join(*(info[var].scope for var in scc))
                    scope = ast.StatementBlock.join(scope, info[target].declScope) # scope is unchanged if declScope is none like usual
                    if info[target].declScope is None or info[target].declScope == scope:
                        for var in scc:
                            varmap[var] = target
                        info[target].scope = ast.StatementBlock.join(scope, info[target].scope)
                        continue
        # fallthrough if merging is impossible
        for var in scc:
            varmap[var] = var
            if len(info[var].defs) > 1:
                forbidden.add(var)
    _preorder(root, partial(_replaceExpressions, rdict=varmap))

def _mergeVariables(root, predeclared, isstatic):
    _oldMergeVariables(root, predeclared)

    rdict = mergevariables.mergeVariables(root, isstatic, predeclared)
    _preorder(root, partial(_replaceExpressions, rdict=rdict))

_oktypes = ast.BinaryInfix, ast.Local, ast.Literal, ast.Parenthesis, ast.Ternary, ast.TypeName, ast.UnaryPrefix
def hasSideEffects(expr):
    if not isinstance(expr, _oktypes):
        return True
    # check for division by 0. If it's a float or dividing by nonzero literal, it's ok
    elif isinstance(expr, ast.BinaryInfix) and expr.opstr in ('/','%'):
        if expr.dtype not in (objtypes.FloatTT, objtypes.DoubleTT):
            divisor = expr.params[-1]
            if not isinstance(divisor, ast.Literal) or divisor.val == 0:
                return True
    return False

def _inlineVariables(root):
    # first find all variables with a single def and use
    defs = collections.defaultdict(list)
    uses = collections.defaultdict(int)

    def visitExprFindDefs(expr):
        if expr.isLocalAssign():
            defs[expr.params[0]].append(expr)
        elif isinstance(expr, ast.Local):
            uses[expr] += 1

    def visitFindDefs(scope, item):
        if item.expr is not None:
            stack = [item.expr]
            while stack:
                expr = stack.pop()
                visitExprFindDefs(expr)
                stack.extend(expr.params)

    _preorder(root, visitFindDefs)
    # These should have 2 uses since the initial assignment also counts
    replacevars = {k for k,v in defs.items() if len(v)==1 and uses[k]==2 and k.dtype == v[0].params[1].dtype}
    def doReplacement(item, pairs):
        old, new = item.expr.params
        assert isinstance(old, ast.Local) and old.dtype == new.dtype
        stack = [(True, (True, item2, expr)) for item2, expr in reversed(pairs) if expr is not None]
        while stack:
            recurse, args = stack.pop()

            if recurse:
                canReplace, parent, expr = args
                stack.append((False, expr))

                # TODO - fix this for real
                if expr.complexity() > 30:
                    canReplace = False

                # For ternaries, we don't want to replace into the conditionally
                # evaluated part, but we still need to check those parts for
                # barriers. For both ternaries and short circuit operators, the
                # first param is always evaluated, so it is safe
                if isinstance(expr, ast.Ternary) or isinstance(expr, ast.BinaryInfix) and expr.opstr in ('&&','||'):
                    for param in reversed(expr.params[1:]):
                        stack.append((True, (False, expr, param)))
                    stack.append((True, (canReplace, expr, expr.params[0])))
                # For assignments, we unroll the LHS arguments, because if assigning
                # to an array or field, we don't want that to serve as a barrier
                elif isinstance(expr, ast.Assignment):
                    left, right = expr.params
                    stack.append((True, (canReplace, expr, right)))
                    if isinstance(left, (ast.ArrayAccess, ast.FieldAccess)):
                        for param in reversed(left.params):
                            stack.append((True, (canReplace, left, param)))
                    else:
                        assert isinstance(left, ast.Local)
                else:
                    for param in reversed(expr.params):
                        stack.append((True, (canReplace, expr, param)))

                if expr == old:
                    if canReplace:
                        if isinstance(parent, ast.JavaExpression):
                            params = parent.params = list(parent.params)
                            params[params.index(old)] = new
                        else: # replacing in a top level statement
                            assert parent.expr == old
                            parent.expr = new
                    return canReplace
            else:
                expr = args
                if hasSideEffects(expr):
                    return False
        return False

    def visitReplace(scope):
        newstatements = []
        for item in reversed(scope.statements):
            for sub in item.getScopes():
                visitReplace(sub)

            if isinstance(item.expr, ast.Assignment) and item.expr.params[0] in replacevars:
                expr_roots = []
                for item2 in newstatements:
                    # Don't inline into a while condition as it may be evaluated more than once
                    if not isinstance(item2, ast.WhileStatement):
                        expr_roots.append((item2, item2.expr))
                    if item2.getScopes():
                        break
                success = doReplacement(item, expr_roots)
                if success:
                    continue
            newstatements.insert(0, item)
        scope.statements = newstatements
    visitReplace(root)

def _createDeclarations(root, predeclared):
    _setScopeParents(root)
    info = findVarDeclInfo(root, predeclared)
    localdefs = collections.defaultdict(list)
    newvars = [var for var in info if isinstance(var, ast.Local) and info[var].declScope is None]
    remaining = set(newvars)

    def mdVisitVarUse(var):
        decl = ast.VariableDeclarator(ast.TypeName(var.dtype), var)
        # The compiler treats statements as if they can throw any exception at any time, so
        # it may think variables are not definitely assigned even when they really are.
        # Therefore, we give an unused initial value to every variable declaration
        # TODO - find a better way to handle this
        right = ast.dummyLiteral(var.dtype)
        localdefs[info[var].scope].append(ast.LocalDeclarationStatement(decl, right))
        remaining.remove(var)

    def mdVisitScope(scope):
        if isinstance(scope, ast.StatementBlock):
            for i,stmt in enumerate(scope.statements):
                if isinstance(stmt, ast.ExpressionStatement):
                    if isinstance(stmt.expr, ast.Assignment):
                        var, right = stmt.expr.params
                        if var in remaining and scope == info[var].scope:
                            decl = ast.VariableDeclarator(ast.TypeName(var.dtype), var)
                            new = ast.LocalDeclarationStatement(decl, right)
                            scope.statements[i] = new
                            remaining.remove(var)
                if stmt.expr is not None:
                    top = stmt.expr
                    for expr in top.postFlatIter():
                        if expr in remaining:
                            mdVisitVarUse(expr)
                for sub in stmt.getScopes():
                    mdVisitScope(sub)

    mdVisitScope(root)
    # print remaining
    assert not remaining
    assert None not in localdefs
    for scope, ldefs in localdefs.items():
        scope.statements = ldefs + scope.statements

def _createTernaries(scope, item):
    if isinstance(item, ast.IfStatement) and len(item.getScopes()) == 2:
        block1, block2 = item.getScopes()

        if (len(block1.statements) == len(block2.statements) == 1) and block1.jumpKey == block2.jumpKey:
            s1, s2 = block1.statements[0], block2.statements[0]
            e1, e2 = s1.expr, s2.expr

            if isinstance(s1, ast.ReturnStatement) and isinstance(s2, ast.ReturnStatement):
                expr = None if e1 is None else ast.Ternary(item.expr, e1, e2)
                item = ast.ReturnStatement(expr, s1.tt)
            elif isinstance(s1, ast.ExpressionStatement) and isinstance(s2, ast.ExpressionStatement):
                if isinstance(e1, ast.Assignment) and isinstance(e2, ast.Assignment):
                    # if e1.params[0] == e2.params[0] and max(e1.params[1].complexity(), e2.params[1].complexity()) <= 1:
                    if e1.params[0] == e2.params[0]:
                        expr = ast.Ternary(item.expr, e1.params[1], e2.params[1])
                        temp = ast.ExpressionStatement(ast.Assignment(e1.params[0], expr))

                        if not block1.doesFallthrough():
                            assert not block2.doesFallthrough()
                            item = ast.StatementBlock(item.func, item.continueKey, item.breakKey, [temp], block1.jumpKey)
                        else:
                            item = temp
    if item.expr is not None:
        item.expr = _simplifyExpressions(item.expr)
    return [item]

def _fixExprStatements(scope, item, namegen):
    if isinstance(item, ast.ExpressionStatement):
        right = item.expr
        if not isinstance(right, (ast.Assignment, ast.ClassInstanceCreation, ast.MethodInvocation)) and right.dtype is not None:
            left = ast.Local(right.dtype, lambda expr:namegen.getPrefix('dummy'))
            decl = ast.VariableDeclarator(ast.TypeName(left.dtype), left)
            item = ast.LocalDeclarationStatement(decl, right)
    return [item]

def _fixLiterals(scope, item):
    item.fixLiterals()

def _addCastsAndParens(scope, item, env):
    item.addCastsAndParens(env)

def _fallsThrough(scope, usedBreakTargets):
    # Check if control reaches end of scope and there is no break statement
    # We don't have to check keys since breaks should have already been generated for child scopes
    # for main scope there won't be one yet, but we don't care since we're just looking for
    # whether end of scope is reached on the main scope
    if not scope.statements:
        return True
    last = scope.statements[-1]
    if isinstance(last, (ast.JumpStatement, ast.ReturnStatement, ast.ThrowStatement)):
        return False
    elif not last.getScopes():
        return True
    # Scope ends with a complex statement. Determine whether it can fallthrough
    if last in usedBreakTargets:
        return True
    # Less strict than Java reachability rules, but we aren't bothering to follow them exactly
    if isinstance(last, ast.WhileStatement):
        return last.expr != ast.Literal.TRUE
    elif isinstance(last, ast.SwitchStatement):
        return not last.hasDefault() or _fallsThrough(last.getScopes()[-1], usedBreakTargets)
    else:
        if isinstance(last, ast.IfStatement) and len(last.getScopes()) < 2:
            return True
        return any(_fallsThrough(sub, usedBreakTargets) for sub in last.getScopes())

def _chooseJump(choices, breakPair, continuePair):
    assert None not in choices
    if breakPair in choices:
        return breakPair
    if continuePair in choices:
        return continuePair
    # Try to find an already labeled target
    for b, t in choices:
        if b.label is not None:
            return b, t
    return choices[0]

def _generateJumps(scope, usedBreakTargets, targets=collections.defaultdict(tuple), breakPair=None, continuePair=None, fallthroughs=NONE_SET, dryRun=False):
    assert None in fallthroughs
    newfallthroughs = fallthroughs
    newcontinuePair = continuePair
    newbreakPair = breakPair

    if scope.jumpKey not in fallthroughs:
        newfallthroughs = frozenset([None, scope.jumpKey])

    for item in reversed(scope.statements):
        if not item.getScopes():
            newfallthroughs = NONE_SET
            continue

        if isinstance(item, ast.WhileStatement):
            newfallthroughs = frozenset([None, item.continueKey])
        else:
            newfallthroughs |= frozenset([item.breakKey])

        newtargets = targets.copy()
        if isinstance(item, ast.WhileStatement):
            newtargets[item.continueKey] += ((item, True),)
            newcontinuePair = item, True
        if isinstance(item, (ast.WhileStatement, ast.SwitchStatement)):
            newbreakPair = item, False
        newtargets[item.breakKey] += ((item, False),)

        for subscope in reversed(item.getScopes()):
            _generateJumps(subscope, usedBreakTargets, newtargets, newbreakPair, newcontinuePair, newfallthroughs, dryRun=dryRun)
            if isinstance(item, ast.SwitchStatement):
                newfallthroughs = frozenset([None, subscope.continueKey])
        newfallthroughs = frozenset([None, item.continueKey])

    for item in scope.statements:
        if isinstance(item, ast.StatementBlock) and item.statements:
            if isinstance(item.statements[-1], ast.JumpStatement):
                assert item is scope.statements[-1] or item in usedBreakTargets

    # Now that we've visited children, decide if we need a jump for this scope, and if so, generate it
    if scope.jumpKey not in fallthroughs:
        # Figure out if this jump is actually reachable
        if _fallsThrough(scope, usedBreakTargets):
            target, isContinue = pair = _chooseJump(targets[scope.jumpKey], breakPair, continuePair)
            if not isContinue:
                usedBreakTargets.add(target)
            if pair == breakPair or pair == continuePair:
                target = None
            # Now actually add the jump statement
            if not dryRun:
                scope.statements.append(ast.JumpStatement(target, isContinue))

def _pruneVoidReturn(scope):
    if scope.statements:
        last = scope.statements[-1]
        if isinstance(last, ast.ReturnStatement) and last.expr is None:
            scope.statements.pop()

def generateAST(method, graph, forbidden_identifiers):
    env = method.class_.env
    namegen = NameGen(forbidden_identifiers)
    class_ = method.class_
    inputTypes = parseMethodDescriptor(method.descriptor, unsynthesize=False)[0]
    tts = objtypes.verifierToSynthetic_seq(inputTypes)

    if graph is not None:
        graph.splitDualInedges()
        graph.fixLoops()
        entryNode, nodes = graphproxy.createGraphProxy(graph)
        if not method.static:
            entryNode.invars[0].name = 'this'

        setree = structuring.structure(entryNode, nodes, (method.name == '<clinit>'))
        ast_root, varinfo = astgen.createAST(method, graph, setree, namegen)

        argsources = [varinfo.var(entryNode, var) for var in entryNode.invars]
        disp_args = argsources if method.static else argsources[1:]
        for expr, tt in zip(disp_args, tts):
            expr.dtype = tt

        decls = [ast.VariableDeclarator(ast.TypeName(expr.dtype), expr) for expr in disp_args]
        ################################################################################################
        ast_root.bases = (ast_root,) # needed for our setScopeParents later

        assert _generateJumps(ast_root, set(), dryRun=True) is None
        _preorder(ast_root, _fixObjectCreations)
        boolize.boolizeVars(ast_root, argsources)
        boolize.interfaceVars(env, ast_root, argsources)
        _simplifyBlocks(ast_root)
        assert _generateJumps(ast_root, set(), dryRun=True) is None

        _mergeVariables(ast_root, argsources, method.static)

        _preorder(ast_root, _createTernaries)
        _inlineVariables(ast_root)
        _simplifyBlocks(ast_root)
        _preorder(ast_root, _createTernaries)
        _inlineVariables(ast_root)
        _simplifyBlocks(ast_root)

        _createDeclarations(ast_root, argsources)
        _preorder(ast_root, partial(_fixExprStatements, namegen=namegen))
        _preorder(ast_root, _fixLiterals)
        _preorder(ast_root, partial(_addCastsAndParens, env=env))
        _generateJumps(ast_root, set())
        _pruneVoidReturn(ast_root)
    else: # abstract or native method
        ast_root = None
        argsources = [ast.Local(tt, lambda expr:namegen.getPrefix('arg')) for tt in tts]
        decls = [ast.VariableDeclarator(ast.TypeName(expr.dtype), expr) for expr in argsources]

    flags = method.flags - set(['BRIDGE','SYNTHETIC','VARARGS'])
    if method.name == '<init>': # More arbtirary restrictions. Yay!
        flags = flags - set(['ABSTRACT','STATIC','FINAL','NATIVE','STRICTFP','SYNCHRONIZED'])

    flagstr = ' '.join(map(str.lower, sorted(flags)))
    inputTypes, returnTypes = parseMethodDescriptor(method.descriptor, unsynthesize=False)
    ret_tt = objtypes.verifierToSynthetic(returnTypes[0]) if returnTypes else objtypes.VoidTT
    return ast2.MethodDef(class_, flagstr, method.name, method.descriptor, ast.TypeName(ret_tt), decls, ast_root)