text:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <dirent.h>
#include <pwd.h>

#include <string>
#include <sstream>
#include "../partitions.hpp"
#include "../twrp-functions.hpp"
#include "../openrecoveryscript.hpp"

#include "../adb_install.h"
#include "../fuse_sideload.h"
#include "blanktimer.hpp"
extern "C" {
#include "../twcommon.h"
#include "../minuitwrp/minui.h"
#include "../variables.h"
#include "../twinstall.h"
#include "cutils/properties.h"
#include "../minadbd/adb.h"
#include "../adb_install.h"
#include "../set_metadata.h"
};

#include "rapidxml.hpp"
#include "objects.hpp"
#include "../tw_atomic.hpp"

void curtainClose(void);

GUIAction::mapFunc GUIAction::mf;
std::set<string> GUIAction::setActionsRunningInCallerThread;
static string zip_queue[10];
static int zip_queue_index;
static pthread_t terminal_command;
pid_t sideload_child_pid;

static void *ActionThread_work_wrapper(void *data);

class ActionThread
{
public:
	ActionThread();
	~ActionThread();

	void threadActions(GUIAction *act);
	void run(void *data);
private:
	friend void *ActionThread_work_wrapper(void*);
	struct ThreadData
	{
		ActionThread *this_;
		GUIAction *act;
		ThreadData(ActionThread *this_, GUIAction *act) : this_(this_), act(act) {}
	};

	pthread_t m_thread;
	bool m_thread_running;
	pthread_mutex_t m_act_lock;
};

static ActionThread action_thread;	// for all kinds of longer running actions
static ActionThread cancel_thread;	// for longer running "cancel" actions

static void *ActionThread_work_wrapper(void *data)
{
	static_cast<ActionThread::ThreadData*>(data)->this_->run(data);
	return NULL;
}

ActionThread::ActionThread()
{
	m_thread_running = false;
	pthread_mutex_init(&m_act_lock, NULL);
}

ActionThread::~ActionThread()
{
	pthread_mutex_lock(&m_act_lock);
	if(m_thread_running) {
		pthread_mutex_unlock(&m_act_lock);
		pthread_join(m_thread, NULL);
	} else {
		pthread_mutex_unlock(&m_act_lock);
	}
	pthread_mutex_destroy(&m_act_lock);
}

void ActionThread::threadActions(GUIAction *act)
{
	pthread_mutex_lock(&m_act_lock);
	if (m_thread_running) {
		pthread_mutex_unlock(&m_act_lock);
		LOGERR("Another threaded action is already running -- not running %u actions starting with '%s'\n",
				act->mActions.size(), act->mActions[0].mFunction.c_str());
	} else {
		m_thread_running = true;
		pthread_mutex_unlock(&m_act_lock);
		ThreadData *d = new ThreadData(this, act);
		pthread_create(&m_thread, NULL, &ActionThread_work_wrapper, d);
	}
}

void ActionThread::run(void *data)
{
	ThreadData *d = (ThreadData*)data;
	GUIAction* act = d->act;

	std::vector<GUIAction::Action>::iterator it;
	for (it = act->mActions.begin(); it != act->mActions.end(); ++it)
		act->doAction(*it);

	pthread_mutex_lock(&m_act_lock);
	m_thread_running = false;
	pthread_mutex_unlock(&m_act_lock);
	delete d;
}

GUIAction::GUIAction(xml_node<>* node)
	: GUIObject(node)
{
	xml_node<>* child;
	xml_node<>* actions;
	xml_attribute<>* attr;

	if (!node)  return;

	if (mf.empty()) {
#define ADD_ACTION(n) mf[#n] = &GUIAction::n
#define ADD_ACTION_EX(name, func) mf[name] = &GUIAction::func
		// These actions will be run in the caller's thread
		ADD_ACTION(reboot);
		ADD_ACTION(home);
		ADD_ACTION(key);
		ADD_ACTION(page);
		ADD_ACTION(reload);
		ADD_ACTION(readBackup);
		ADD_ACTION(set);
		ADD_ACTION(clear);
		ADD_ACTION(mount);
		ADD_ACTION(unmount);
		ADD_ACTION_EX("umount", unmount);
		ADD_ACTION(restoredefaultsettings);
		ADD_ACTION(copylog);
		ADD_ACTION(compute);
		ADD_ACTION_EX("addsubtract", compute);
		ADD_ACTION(setguitimezone);
		ADD_ACTION(overlay);
		ADD_ACTION(queuezip);
		ADD_ACTION(cancelzip);
		ADD_ACTION(queueclear);
		ADD_ACTION(sleep);
		ADD_ACTION(appenddatetobackupname);
		ADD_ACTION(generatebackupname);
		ADD_ACTION(checkpartitionlist);
		ADD_ACTION(getpartitiondetails);
		ADD_ACTION(screenshot);
		ADD_ACTION(setbrightness);
		ADD_ACTION(fileexists);
		ADD_ACTION(killterminal);
		ADD_ACTION(checkbackupname);
		ADD_ACTION(adbsideloadcancel);
		ADD_ACTION(fixsu);
		ADD_ACTION(startmtp);
		ADD_ACTION(stopmtp);
		ADD_ACTION(cancelbackup);

		// remember actions that run in the caller thread
		for (mapFunc::const_iterator it = mf.begin(); it != mf.end(); ++it)
			setActionsRunningInCallerThread.insert(it->first);

		// These actions will run in a separate thread
		ADD_ACTION(flash);
		ADD_ACTION(wipe);
		ADD_ACTION(refreshsizes);
		ADD_ACTION(nandroid);
		ADD_ACTION(fixpermissions);
		ADD_ACTION(dd);
		ADD_ACTION(partitionsd);
		ADD_ACTION(installhtcdumlock);
		ADD_ACTION(htcdumlockrestoreboot);
		ADD_ACTION(htcdumlockreflashrecovery);
		ADD_ACTION(cmd);
		ADD_ACTION(terminalcommand);
		ADD_ACTION(reinjecttwrp);
		ADD_ACTION(decrypt);
		ADD_ACTION(adbsideload);
		ADD_ACTION(openrecoveryscript);
		ADD_ACTION(installsu);
		ADD_ACTION(decrypt_backup);
		ADD_ACTION(repair);
		ADD_ACTION(changefilesystem);
		ADD_ACTION(flashimage);
	}

	// First, get the action
	actions = FindNode(node, "actions");
	if (actions)	child = FindNode(actions, "action");
	else			child = FindNode(node, "action");

	if (!child) return;

	while (child)
	{
		Action action;

		attr = child->first_attribute("function");
		if (!attr)  return;

		action.mFunction = attr->value();
		action.mArg = child->value();
		mActions.push_back(action);

		child = child->next_sibling("action");
	}

	// Now, let's get either the key or region
	child = FindNode(node, "touch");
	if (child)
	{
		attr = child->first_attribute("key");
		if (attr)
		{
			std::vector<std::string> keys = TWFunc::Split_String(attr->value(), "+");
			for(size_t i = 0; i < keys.size(); ++i)
			{
				const int key = getKeyByName(keys[i]);
				mKeys[key] = false;
			}
		}
		else
		{
			attr = child->first_attribute("x");
			if (!attr)  return;
			mActionX = atol(attr->value());
			attr = child->first_attribute("y");
			if (!attr)  return;
			mActionY = atol(attr->value());
			attr = child->first_attribute("w");
			if (!attr)  return;
			mActionW = atol(attr->value());
			attr = child->first_attribute("h");
			if (!attr)  return;
			mActionH = atol(attr->value());
		}
	}
}

int GUIAction::NotifyTouch(TOUCH_STATE state, int x, int y)
{
	if (state == TOUCH_RELEASE)
		doActions();

	return 0;
}

int GUIAction::NotifyKey(int key, bool down)
{
	if (mKeys.empty())
		return 0;

	std::map<int, bool>::iterator itr = mKeys.find(key);
	if(itr == mKeys.end())
		return 0;

	bool prevState = itr->second;
	itr->second = down;

	// If there is only one key for this action, wait for key up so it
	// doesn't trigger with multi-key actions.
	// Else, check if all buttons are pressed, then consume their release events
	// so they don't trigger one-button actions and reset mKeys pressed status
	if(mKeys.size() == 1) {
		if(!down && prevState)
			doActions();
	} else if(down) {
		for(itr = mKeys.begin(); itr != mKeys.end(); ++itr) {
			if(!itr->second)
				return 0;
		}

		// Passed, all req buttons are pressed, reset them and consume release events
		HardwareKeyboard *kb = PageManager::GetHardwareKeyboard();
		for(itr = mKeys.begin(); itr != mKeys.end(); ++itr) {
			kb->ConsumeKeyRelease(itr->first);
			itr->second = false;
		}

		doActions();
	}

	return 0;
}

int GUIAction::NotifyVarChange(const std::string& varName, const std::string& value)
{
	GUIObject::NotifyVarChange(varName, value);

	if (varName.empty() && !isConditionValid() && mKeys.empty() && !mActionW)
		doActions();
	else if((varName.empty() || IsConditionVariable(varName)) && isConditionValid() && isConditionTrue())
		doActions();

	return 0;
}

void GUIAction::simulate_progress_bar(void)
{
	gui_print("Simulating actions...\n");
	for (int i = 0; i < 5; i++)
	{
		if (PartitionManager.stop_backup.get_value()) {
			DataManager::SetValue("tw_cancel_backup", 1);
			gui_print("Backup Canceled.\n");
			DataManager::SetValue("ui_progress", 0);
			PartitionManager.stop_backup.set_value(0);
			return;
		}
		usleep(500000);
		DataManager::SetValue("ui_progress", i * 20);
	}
}

int GUIAction::flash_zip(std::string filename, int* wipe_cache)
{
	int ret_val = 0;

	DataManager::SetValue("ui_progress", 0);

	if (filename.empty())
	{
		LOGERR("No file specified.\n");
		return -1;
	}

	if (!PartitionManager.Mount_By_Path(filename, true))
		return -1;

	if (simulate) {
		simulate_progress_bar();
	} else {
		ret_val = TWinstall_zip(filename.c_str(), wipe_cache);

		// Now, check if we need to ensure TWRP remains installed...
		struct stat st;
		if (stat("/sbin/installTwrp", &st) == 0)
		{
			DataManager::SetValue("tw_operation", "Configuring TWRP");
			DataManager::SetValue("tw_partition", "");
			gui_print("Configuring TWRP...\n");
			if (TWFunc::Exec_Cmd("/sbin/installTwrp reinstall") < 0)
			{
				gui_print("Unable to configure TWRP with this kernel.\n");
			}
		}
	}

	// Done
	DataManager::SetValue("ui_progress", 100);
	DataManager::SetValue("ui_progress", 0);
	return ret_val;
}

GUIAction::ThreadType GUIAction::getThreadType(const GUIAction::Action& action)
{
	string func = gui_parse_text(action.mFunction);
	bool needsThread = setActionsRunningInCallerThread.find(func) == setActionsRunningInCallerThread.end();
	if (needsThread) {
		if (func == "cancelbackup")
			return THREAD_CANCEL;
		else
			return THREAD_ACTION;
	}
	return THREAD_NONE;
}

int GUIAction::doActions()
{
	if (mActions.size() < 1)
		return -1;

	// Determine in which thread to run the actions.
	// Do it for all actions at once before starting, so that we can cancel the whole batch if the thread is already busy.
	ThreadType threadType = THREAD_NONE;
	std::vector<Action>::iterator it;
	for (it = mActions.begin(); it != mActions.end(); ++it) {
		ThreadType tt = getThreadType(*it);
		if (tt == THREAD_NONE)
			continue;
		if (threadType == THREAD_NONE)
			threadType = tt;
		else if (threadType != tt) {
			LOGERR("Can't mix normal and cancel actions in the same list.\n"
				"Running the whole batch in the cancel thread.\n");
			threadType = THREAD_CANCEL;
			break;
		}
	}

	// Now run the actions in the desired thread.
	switch (threadType) {
		case THREAD_ACTION:
			action_thread.threadActions(this);
			break;

		case THREAD_CANCEL:
			cancel_thread.threadActions(this);
			break;

		default: {
			// no iterators here because theme reloading might kill our object
			const size_t cnt = mActions.size();
			for (size_t i = 0; i < cnt; ++i)
				doAction(mActions[i]);
		}
	}

	return 0;
}

int GUIAction::doAction(Action action)
{
	DataManager::GetValue(TW_SIMULATE_ACTIONS, simulate);

	std::string function = gui_parse_text(action.mFunction);
	std::string arg = gui_parse_text(action.mArg);

	// find function and execute it
	mapFunc::const_iterator funcitr = mf.find(function);
	if (funcitr != mf.end())
		return (this->*funcitr->second)(arg);

	LOGERR("Unknown action '%s'\n", function.c_str());
	return -1;
}

void GUIAction::operation_start(const string operation_name)
{
	LOGINFO("operation_start: '%s'\n", operation_name.c_str());
	time(&Start);
	DataManager::SetValue(TW_ACTION_BUSY, 1);
	DataManager::SetValue("ui_progress", 0);
	DataManager::SetValue("tw_operation", operation_name);
	DataManager::SetValue("tw_operation_state", 0);
	DataManager::SetValue("tw_operation_status", 0);
}

void GUIAction::operation_end(const int operation_status)
{
	time_t Stop;
	int simulate_fail;
	DataManager::SetValue("ui_progress", 100);
	if (simulate) {
		DataManager::GetValue(TW_SIMULATE_FAIL, simulate_fail);
		if (simulate_fail != 0)
			DataManager::SetValue("tw_operation_status", 1);
		else
			DataManager::SetValue("tw_operation_status", 0);
	} else {
		if (operation_status != 0) {
			DataManager::SetValue("tw_operation_status", 1);
		}
		else {
			DataManager::SetValue("tw_operation_status", 0);
		}
	}
	DataManager::SetValue("tw_operation_state", 1);
	DataManager::SetValue(TW_ACTION_BUSY, 0);
	blankTimer.resetTimerAndUnblank();
	time(&Stop);
	if ((int) difftime(Stop, Start) > 10)
		DataManager::Vibrate("tw_action_vibrate");
	LOGINFO("operation_end - status=%d\n", operation_status);
}

int GUIAction::reboot(std::string arg)
{
	//curtainClose(); this sometimes causes a crash

	sync();
	DataManager::SetValue("tw_gui_done", 1);
	DataManager::SetValue("tw_reboot_arg", arg);

	return 0;
}

int GUIAction::home(std::string arg)
{
	PageManager::SelectPackage("TWRP");
	gui_changePage("main");
	return 0;
}

int GUIAction::key(std::string arg)
{
	const int key = getKeyByName(arg);
	PageManager::NotifyKey(key, true);
	PageManager::NotifyKey(key, false);
	return 0;
}

int GUIAction::page(std::string arg)
{
	std::string page_name = gui_parse_text(arg);
	return gui_changePage(page_name);
}

int GUIAction::reload(std::string arg)
{
	int check = 0, ret_val = 0;
	std::string theme_path;

	theme_path = DataManager::GetSettingsStoragePath();
	if (PartitionManager.Mount_By_Path(theme_path.c_str(), 1) < 0) {
		LOGERR("Unable to mount %s during reload function startup.\n", theme_path.c_str());
		check = 1;
	}

	theme_path += "/TWRP/theme/ui.zip";
	if (check != 0 || PageManager::ReloadPackage("TWRP", theme_path) != 0)
	{
		// Loading the custom theme failed - try loading the stock theme
		LOGINFO("Attempting to reload stock theme...\n");
		if (PageManager::ReloadPackage("TWRP", TWRES "ui.xml"))
		{
			LOGERR("Failed to load base packages.\n");
			ret_val = 1;
		}
	}
	return 0;
}

int GUIAction::readBackup(std::string arg)
{
	string Restore_Name;
	DataManager::GetValue("tw_restore", Restore_Name);
	PartitionManager.Set_Restore_Files(Restore_Name);
	return 0;
}

int GUIAction::set(std::string arg)
{
	if (arg.find('=') != string::npos)
	{
		string varName = arg.substr(0, arg.find('='));
		string value = arg.substr(arg.find('=') + 1, string::npos);

		DataManager::GetValue(value, value);
		DataManager::SetValue(varName, value);
	}
	else
		DataManager::SetValue(arg, "1");
	return 0;
}

int GUIAction::clear(std::string arg)
{
	DataManager::SetValue(arg, "0");
	return 0;
}

int GUIAction::mount(std::string arg)
{
	if (arg == "usb") {
		DataManager::SetValue(TW_ACTION_BUSY, 1);
		if (!simulate)
			PartitionManager.usb_storage_enable();
		else
			gui_print("Simulating actions...\n");
	} else if (!simulate) {
		PartitionManager.Mount_By_Path(arg, true);
		PartitionManager.Add_MTP_Storage(arg);
	} else
		gui_print("Simulating actions...\n");
	return 0;
}

int GUIAction::unmount(std::string arg)
{
	if (arg == "usb") {
		if (!simulate)
			PartitionManager.usb_storage_disable();
		else
			gui_print("Simulating actions...\n");
		DataManager::SetValue(TW_ACTION_BUSY, 0);
	} else if (!simulate) {
		PartitionManager.UnMount_By_Path(arg, true);
	} else
		gui_print("Simulating actions...\n");
	return 0;
}

int GUIAction::restoredefaultsettings(std::string arg)
{
	operation_start("Restore Defaults");
	if (simulate) // Simulated so that people don't accidently wipe out the "simulation is on" setting
		gui_print("Simulating actions...\n");
	else {
		DataManager::ResetDefaults();
		PartitionManager.Update_System_Details();
		PartitionManager.Mount_Current_Storage(true);
	}
	operation_end(0);
	return 0;
}

int GUIAction::copylog(std::string arg)
{
	operation_start("Copy Log");
	if (!simulate)
	{
		string dst;
		PartitionManager.Mount_Current_Storage(true);
		dst = DataManager::GetCurrentStoragePath() + "/recovery.log";
		TWFunc::copy_file("/tmp/recovery.log", dst.c_str(), 0755);
		tw_set_default_metadata(dst.c_str());
		sync();
		gui_print("Copied recovery log to %s.\n", DataManager::GetCurrentStoragePath().c_str());
	} else
		simulate_progress_bar();
	operation_end(0);
	return 0;
}

int GUIAction::compute(std::string arg)
{
	if (arg.find("+") != string::npos)
	{
		string varName = arg.substr(0, arg.find('+'));
		string string_to_add = arg.substr(arg.find('+') + 1, string::npos);
		int amount_to_add = atoi(string_to_add.c_str());
		int value;

		DataManager::GetValue(varName, value);
		DataManager::SetValue(varName, value + amount_to_add);
		return 0;
	}
	if (arg.find("-") != string::npos)
	{
		string varName = arg.substr(0, arg.find('-'));
		string string_to_subtract = arg.substr(arg.find('-') + 1, string::npos);
		int amount_to_subtract = atoi(string_to_subtract.c_str());
		int value;

		DataManager::GetValue(varName, value);
		value -= amount_to_subtract;
		if (value <= 0)
			value = 0;
		DataManager::SetValue(varName, value);
		return 0;
	}
	if (arg.find("*") != string::npos)
	{
		string varName = arg.substr(0, arg.find('*'));
		string multiply_by_str = gui_parse_text(arg.substr(arg.find('*') + 1, string::npos));
		int multiply_by = atoi(multiply_by_str.c_str());
		int value;

		DataManager::GetValue(varName, value);
		DataManager::SetValue(varName, value*multiply_by);
		return 0;
	}
	if (arg.find("/") != string::npos)
	{
		string varName = arg.substr(0, arg.find('/'));
		string divide_by_str = gui_parse_text(arg.substr(arg.find('/') + 1, string::npos));
		int divide_by = atoi(divide_by_str.c_str());
		int value;

		if(divide_by != 0)
		{
			DataManager::GetValue(varName, value);
			DataManager::SetValue(varName, value/divide_by);
		}
		return 0;
	}
	LOGERR("Unable to perform compute '%s'\n", arg.c_str());
	return -1;
}

int GUIAction::setguitimezone(std::string arg)
{
	string SelectedZone;
	DataManager::GetValue(TW_TIME_ZONE_GUISEL, SelectedZone); // read the selected time zone into SelectedZone
	string Zone = SelectedZone.substr(0, SelectedZone.find(';')); // parse to get time zone
	string DSTZone = SelectedZone.substr(SelectedZone.find(';') + 1, string::npos); // parse to get DST component

	int dst;
	DataManager::GetValue(TW_TIME_ZONE_GUIDST, dst); // check wether user chose to use DST

	string offset;
	DataManager::GetValue(TW_TIME_ZONE_GUIOFFSET, offset); // pull in offset

	string NewTimeZone = Zone;
	if (offset != "0")
		NewTimeZone += ":" + offset;

	if (dst != 0)
		NewTimeZone += DSTZone;

	DataManager::SetValue(TW_TIME_ZONE_VAR, NewTimeZone);
	DataManager::update_tz_environment_variables();
	return 0;
}

int GUIAction::overlay(std::string arg)
{
	return gui_changeOverlay(arg);
}

int GUIAction::queuezip(std::string arg)
{
	if (zip_queue_index >= 10) {
		gui_print("Maximum zip queue reached!\n");
		return 0;
	}
	DataManager::GetValue("tw_filename", zip_queue[zip_queue_index]);
	if (strlen(zip_queue[zip_queue_index].c_str()) > 0) {
		zip_queue_index++;
		DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
	}
	return 0;
}

int GUIAction::cancelzip(std::string arg)
{
	if (zip_queue_index <= 0) {
		gui_print("Minimum zip queue reached!\n");
		return 0;
	} else {
		zip_queue_index--;
		DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
	}
	return 0;
}

int GUIAction::queueclear(std::string arg)
{
	zip_queue_index = 0;
	DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
	return 0;
}

int GUIAction::sleep(std::string arg)
{
	operation_start("Sleep");
	usleep(atoi(arg.c_str()));
	operation_end(0);
	return 0;
}

int GUIAction::appenddatetobackupname(std::string arg)
{
	operation_start("AppendDateToBackupName");
	string Backup_Name;
	DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
	Backup_Name += TWFunc::Get_Current_Date();
	if (Backup_Name.size() > MAX_BACKUP_NAME_LEN)
		Backup_Name.resize(MAX_BACKUP_NAME_LEN);
	DataManager::SetValue(TW_BACKUP_NAME, Backup_Name);
	operation_end(0);
	return 0;
}

int GUIAction::generatebackupname(std::string arg)
{
	operation_start("GenerateBackupName");
	TWFunc::Auto_Generate_Backup_Name();
	operation_end(0);
	return 0;
}

int GUIAction::checkpartitionlist(std::string arg)
{
	string Wipe_List, wipe_path;
	int count = 0;

	DataManager::GetValue("tw_wipe_list", Wipe_List);
	LOGINFO("checkpartitionlist list '%s'\n", Wipe_List.c_str());
	if (!Wipe_List.empty()) {
		size_t start_pos = 0, end_pos = Wipe_List.find(";", start_pos);
		while (end_pos != string::npos && start_pos < Wipe_List.size()) {
			wipe_path = Wipe_List.substr(start_pos, end_pos - start_pos);
			LOGINFO("checkpartitionlist wipe_path '%s'\n", wipe_path.c_str());
			if (wipe_path == "/and-sec" || wipe_path == "DALVIK" || wipe_path == "INTERNAL") {
				// Do nothing
			} else {
				count++;
			}
			start_pos = end_pos + 1;
			end_pos = Wipe_List.find(";", start_pos);
		}
		DataManager::SetValue("tw_check_partition_list", count);
	} else {
		DataManager::SetValue("tw_check_partition_list", 0);
	}
		return 0;
}

int GUIAction::getpartitiondetails(std::string arg)
{
	string Wipe_List, wipe_path;
	int count = 0;

	DataManager::GetValue("tw_wipe_list", Wipe_List);
	LOGINFO("getpartitiondetails list '%s'\n", Wipe_List.c_str());
	if (!Wipe_List.empty()) {
		size_t start_pos = 0, end_pos = Wipe_List.find(";", start_pos);
		while (end_pos != string::npos && start_pos < Wipe_List.size()) {
			wipe_path = Wipe_List.substr(start_pos, end_pos - start_pos);
			LOGINFO("getpartitiondetails wipe_path '%s'\n", wipe_path.c_str());
			if (wipe_path == "/and-sec" || wipe_path == "DALVIK" || wipe_path == "INTERNAL") {
				// Do nothing
			} else {
				DataManager::SetValue("tw_partition_path", wipe_path);
				break;
			}
			start_pos = end_pos + 1;
			end_pos = Wipe_List.find(";", start_pos);
		}
		if (!wipe_path.empty()) {
			TWPartition* Part = PartitionManager.Find_Partition_By_Path(wipe_path);
			if (Part) {
				unsigned long long mb = 1048576;

				DataManager::SetValue("tw_partition_name", Part->Display_Name);
				DataManager::SetValue("tw_partition_mount_point", Part->Mount_Point);
				DataManager::SetValue("tw_partition_file_system", Part->Current_File_System);
				DataManager::SetValue("tw_partition_size", Part->Size / mb);
				DataManager::SetValue("tw_partition_used", Part->Used / mb);
				DataManager::SetValue("tw_partition_free", Part->Free / mb);
				DataManager::SetValue("tw_partition_backup_size", Part->Backup_Size / mb);
				DataManager::SetValue("tw_partition_removable", Part->Removable);
				DataManager::SetValue("tw_partition_is_present", Part->Is_Present);

				if (Part->Can_Repair())
					DataManager::SetValue("tw_partition_can_repair", 1);
				else
					DataManager::SetValue("tw_partition_can_repair", 0);
				if (TWFunc::Path_Exists("/sbin/mkdosfs"))
					DataManager::SetValue("tw_partition_vfat", 1);
				else
					DataManager::SetValue("tw_partition_vfat", 0);
				if (TWFunc::Path_Exists("/sbin/mkfs.exfat"))
					DataManager::SetValue("tw_partition_exfat", 1);
				else
					DataManager::SetValue("tw_partition_exfat", 0);
				if (TWFunc::Path_Exists("/sbin/mkfs.f2fs"))
					DataManager::SetValue("tw_partition_f2fs", 1);
				else
					DataManager::SetValue("tw_partition_f2fs", 0);
				if (TWFunc::Path_Exists("/sbin/mke2fs"))
					DataManager::SetValue("tw_partition_ext", 1);
				else
					DataManager::SetValue("tw_partition_ext", 0);
				return 0;
			} else {
				LOGERR("Unable to locate partition: '%s'\n", wipe_path.c_str());
			}
		}
	}
	DataManager::SetValue("tw_partition_name", "");
	DataManager::SetValue("tw_partition_file_system", "");
	return 0;
}

int GUIAction::screenshot(std::string arg)
{
	time_t tm;
	char path[256];
	int path_len;
	uid_t uid = -1;
	gid_t gid = -1;

	struct passwd *pwd = getpwnam("media_rw");
	if(pwd) {
		uid = pwd->pw_uid;
		gid = pwd->pw_gid;
	}

	const std::string storage = DataManager::GetCurrentStoragePath();
	if(PartitionManager.Is_Mounted_By_Path(storage)) {
		snprintf(path, sizeof(path), "%s/Pictures/Screenshots/", storage.c_str());
	} else {
		strcpy(path, "/tmp/");
	}

	if(!TWFunc::Create_Dir_Recursive(path, 0666, uid, gid))
		return 0;

	tm = time(NULL);
	path_len = strlen(path);

	// Screenshot_2014-01-01-18-21-38.png
	strftime(path+path_len, sizeof(path)-path_len, "Screenshot_%Y-%m-%d-%H-%M-%S.png", localtime(&tm));

	int res = gr_save_screenshot(path);
	if(res == 0) {
		chmod(path, 0666);
		chown(path, uid, gid);

		gui_print("Screenshot was saved to %s\n", path);

		// blink to notify that the screenshow was taken
		gr_color(255, 255, 255, 255);
		gr_fill(0, 0, gr_fb_width(), gr_fb_height());
		gr_flip();
		gui_forceRender();
	} else {
		LOGERR("Failed to take a screenshot!\n");
	}
	return 0;
}

int GUIAction::setbrightness(std::string arg)
{
	return TWFunc::Set_Brightness(arg);
}

int GUIAction::fileexists(std::string arg)
{
	struct stat st;
	string newpath = arg + "/.";

	operation_start("FileExists");
	if (stat(arg.c_str(), &st) == 0 || stat(newpath.c_str(), &st) == 0)
		operation_end(0);
	else
		operation_end(1);
	return 0;
}

void GUIAction::reinject_after_flash()
{
	if (DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 && DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) {
		gui_print("Injecting TWRP into boot image...\n");
		if (simulate) {
			simulate_progress_bar();
		} else {
			TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
			if (Boot == NULL || Boot->Current_File_System != "emmc")
				TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
			else {
				string injectcmd = "injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash bd=" + Boot->Actual_Block_Device;
				TWFunc::Exec_Cmd(injectcmd);
			}
			gui_print("TWRP injection complete.\n");
		}
	}
}

int GUIAction::flash(std::string arg)
{
	int i, ret_val = 0, wipe_cache = 0;
	// We're going to jump to this page first, like a loading page
	gui_changePage(arg);
	for (i=0; i<zip_queue_index; i++) {
		operation_start("Flashing");
		DataManager::SetValue("tw_filename", zip_queue[i]);
		DataManager::SetValue(TW_ZIP_INDEX, (i + 1));

		TWFunc::SetPerformanceMode(true);
		ret_val = flash_zip(zip_queue[i], &wipe_cache);
		TWFunc::SetPerformanceMode(false);
		if (ret_val != 0) {
			gui_print("Error flashing zip '%s'\n", zip_queue[i].c_str());
			ret_val = 1;
			break;
		}
	}
	zip_queue_index = 0;

	if (wipe_cache) {
		gui_print("One or more zip requested a cache wipe\nWiping cache now.\n");
		PartitionManager.Wipe_By_Path("/cache");
	}

	reinject_after_flash();
	PartitionManager.Update_System_Details();
	operation_end(ret_val);
	DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index);
	return 0;
}

int GUIAction::wipe(std::string arg)
{
	operation_start("Format");
	DataManager::SetValue("tw_partition", arg);

	int ret_val = false;

	if (simulate) {
		simulate_progress_bar();
	} else {
		if (arg == "data")
			ret_val = PartitionManager.Factory_Reset();
		else if (arg == "battery")
			ret_val = PartitionManager.Wipe_Battery_Stats();
		else if (arg == "rotate")
			ret_val = PartitionManager.Wipe_Rotate_Data();
		else if (arg == "dalvik")
			ret_val = PartitionManager.Wipe_Dalvik_Cache();
		else if (arg == "DATAMEDIA") {
			ret_val = PartitionManager.Format_Data();
		} else if (arg == "INTERNAL") {
			int has_datamedia, dual_storage;

			DataManager::GetValue(TW_HAS_DATA_MEDIA, has_datamedia);
			if (has_datamedia) {
				ret_val = PartitionManager.Wipe_Media_From_Data();
			} else {
				ret_val = PartitionManager.Wipe_By_Path(DataManager::GetSettingsStoragePath());
			}
		} else if (arg == "EXTERNAL") {
			string External_Path;

			DataManager::GetValue(TW_EXTERNAL_PATH, External_Path);
			ret_val = PartitionManager.Wipe_By_Path(External_Path);
		} else if (arg == "ANDROIDSECURE") {
			ret_val = PartitionManager.Wipe_Android_Secure();
		} else if (arg == "LIST") {
			string Wipe_List, wipe_path;
			bool skip = false;
			ret_val = true;
			TWPartition* wipe_part = NULL;

			DataManager::GetValue("tw_wipe_list", Wipe_List);
			LOGINFO("wipe list '%s'\n", Wipe_List.c_str());
			if (!Wipe_List.empty()) {
				size_t start_pos = 0, end_pos = Wipe_List.find(";", start_pos);
				while (end_pos != string::npos && start_pos < Wipe_List.size()) {
					wipe_path = Wipe_List.substr(start_pos, end_pos - start_pos);
					LOGINFO("wipe_path '%s'\n", wipe_path.c_str());
					if (wipe_path == "/and-sec") {
						if (!PartitionManager.Wipe_Android_Secure()) {
							LOGERR("Unable to wipe android secure\n");
							ret_val = false;
							break;
						} else {
							skip = true;
						}
					} else if (wipe_path == "DALVIK") {
						if (!PartitionManager.Wipe_Dalvik_Cache()) {
							LOGERR("Failed to wipe dalvik\n");
							ret_val = false;
							break;
						} else {
							skip = true;
						}
					} else if (wipe_path == "INTERNAL") {
						if (!PartitionManager.Wipe_Media_From_Data()) {
							ret_val = false;
							break;
						} else {
							skip = true;
						}
					}
					if (!skip) {
						if (!PartitionManager.Wipe_By_Path(wipe_path)) {
							LOGERR("Unable to wipe '%s'\n", wipe_path.c_str());
							ret_val = false;
							break;
						} else if (wipe_path == DataManager::GetSettingsStoragePath()) {
							arg = wipe_path;
						}
					} else {
						skip = false;
					}
					start_pos = end_pos + 1;
					end_pos = Wipe_List.find(";", start_pos);
				}
			}
		} else
			ret_val = PartitionManager.Wipe_By_Path(arg);
#ifndef TW_OEM_BUILD
		if (arg == DataManager::GetSettingsStoragePath()) {
			// If we wiped the settings storage path, recreate the TWRP folder and dump the settings
			string Storage_Path = DataManager::GetSettingsStoragePath();

			if (PartitionManager.Mount_By_Path(Storage_Path, true)) {
				LOGINFO("Making TWRP folder and saving settings.\n");
				Storage_Path += "/TWRP";
				mkdir(Storage_Path.c_str(), 0777);
				DataManager::Flush();
			} else {
				LOGERR("Unable to recreate TWRP folder and save settings.\n");
			}
		}
#endif
	}
	PartitionManager.Update_System_Details();
	if (ret_val)
		ret_val = 0; // 0 is success
	else
		ret_val = 1; // 1 is failure
	operation_end(ret_val);
	return 0;
}

int GUIAction::refreshsizes(std::string arg)
{
	operation_start("Refreshing Sizes");
	if (simulate) {
		simulate_progress_bar();
	} else
		PartitionManager.Update_System_Details();
	operation_end(0);
	return 0;
}

int GUIAction::nandroid(std::string arg)
{
	if (simulate) {
		PartitionManager.stop_backup.set_value(0);
		DataManager::SetValue("tw_partition", "Simulation");
		simulate_progress_bar();
		operation_end(0);
	} else {
		operation_start("Nandroid");
		int ret = 0;

		if (arg == "backup") {
			string Backup_Name;
			DataManager::GetValue(TW_BACKUP_NAME, Backup_Name);
			if (Backup_Name == "(Auto Generate)" || Backup_Name == "(Current Date)" || Backup_Name == "0" || Backup_Name == "(" || PartitionManager.Check_Backup_Name(true) == 0) {
				ret = PartitionManager.Run_Backup();
			}
			else {
				operation_end(1);
				return -1;
			}
			DataManager::SetValue(TW_BACKUP_NAME, "(Auto Generate)");
		} else if (arg == "restore") {
			string Restore_Name;
			DataManager::GetValue("tw_restore", Restore_Name);
			ret = PartitionManager.Run_Restore(Restore_Name);
		} else {
			operation_end(1);
			return -1;
		}
		DataManager::SetValue("tw_encrypt_backup", 0);
		if (!PartitionManager.stop_backup.get_value()) {
			if (ret == false)
				ret = 1; // 1 for failure
			else
				ret = 0; // 0 for success
			DataManager::SetValue("tw_cancel_backup", 0);
		}
		else {
			DataManager::SetValue("tw_cancel_backup", 1);
			gui_print("Backup Canceled.\n");
			ret = 0;
		}
		operation_end(ret);
		return ret;
	}
	return 0;
}

int GUIAction::cancelbackup(std::string arg) {
	if (simulate) {
		PartitionManager.stop_backup.set_value(1);
	}
	else {
		int op_status = PartitionManager.Cancel_Backup();
		if (op_status != 0)
			op_status = 1; // failure
	}

	return 0;
}

int GUIAction::fixpermissions(std::string arg)
{
	int op_status = 0;

	operation_start("Fix Permissions");
	LOGINFO("fix permissions started!\n");
	if (simulate) {
		simulate_progress_bar();
	} else {
		op_status = PartitionManager.Fix_Permissions();
		if (op_status != 0)
			op_status = 1; // failure
	}
	operation_end(op_status);
	return 0;
}

int GUIAction::dd(std::string arg)
{
	operation_start("imaging");

	if (simulate) {
		simulate_progress_bar();
	} else {
		string cmd = "dd " + arg;
		TWFunc::Exec_Cmd(cmd);
	}
	operation_end(0);
	return 0;
}

int GUIAction::partitionsd(std::string arg)
{
	operation_start("Partition SD Card");
	int ret_val = 0;

	if (simulate) {
		simulate_progress_bar();
	} else {
		int allow_partition;
		DataManager::GetValue(TW_ALLOW_PARTITION_SDCARD, allow_partition);
		if (allow_partition == 0) {
			gui_print("This device does not have a real SD Card!\nAborting!\n");
		} else {
			if (!PartitionManager.Partition_SDCard())
				ret_val = 1; // failed
		}
	}
	operation_end(ret_val);
	return 0;

}

int GUIAction::installhtcdumlock(std::string arg)
{
	operation_start("Install HTC Dumlock");
	if (simulate) {
		simulate_progress_bar();
	} else
		TWFunc::install_htc_dumlock();

	operation_end(0);
	return 0;
}

int GUIAction::htcdumlockrestoreboot(std::string arg)
{
	operation_start("HTC Dumlock Restore Boot");
	if (simulate) {
		simulate_progress_bar();
	} else
		TWFunc::htc_dumlock_restore_original_boot();

	operation_end(0);
	return 0;
}

int GUIAction::htcdumlockreflashrecovery(std::string arg)
{
	operation_start("HTC Dumlock Reflash Recovery");
	if (simulate) {
		simulate_progress_bar();
	} else
		TWFunc::htc_dumlock_reflash_recovery_to_boot();

	operation_end(0);
	return 0;
}

int GUIAction::cmd(std::string arg)
{
	int op_status = 0;

	operation_start("Command");
	LOGINFO("Running command: '%s'\n", arg.c_str());
	if (simulate) {
		simulate_progress_bar();
	} else {
		op_status = TWFunc::Exec_Cmd(arg);
		if (op_status != 0)
			op_status = 1;
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::terminalcommand(std::string arg)
{
	int op_status = 0;
	string cmdpath, command;

	DataManager::GetValue("tw_terminal_location", cmdpath);
	operation_start("CommandOutput");
	gui_print("%s # %s\n", cmdpath.c_str(), arg.c_str());
	if (simulate) {
		simulate_progress_bar();
		operation_end(op_status);
	} else if (arg == "exit") {
		LOGINFO("Exiting terminal\n");
		operation_end(op_status);
		page("main");
	} else {
		command = "cd \"" + cmdpath + "\" && " + arg + " 2>&1";;
		LOGINFO("Actual command is: '%s'\n", command.c_str());
		DataManager::SetValue("tw_terminal_state", 1);
		DataManager::SetValue("tw_background_thread_running", 1);
		FILE* fp;
		char line[512];

		fp = popen(command.c_str(), "r");
		if (fp == NULL) {
			LOGERR("Error opening command to run.\n");
		} else {
			int fd = fileno(fp), has_data = 0, check = 0, keep_going = -1, bytes_read = 0;
			struct timeval timeout;
			fd_set fdset;

			while(keep_going)
			{
				FD_ZERO(&fdset);
				FD_SET(fd, &fdset);
				timeout.tv_sec = 0;
				timeout.tv_usec = 400000;
				has_data = select(fd+1, &fdset, NULL, NULL, &timeout);
				if (has_data == 0) {
					// Timeout reached
					DataManager::GetValue("tw_terminal_state", check);
					if (check == 0) {
						keep_going = 0;
					}
				} else if (has_data < 0) {
					// End of execution
					keep_going = 0;
				} else {
					// Try to read output
					memset(line, 0, sizeof(line));
					if(fgets(line, sizeof(line), fp) != NULL)
						gui_print("%s", line); // Display output
					else
						keep_going = 0; // Done executing
				}
			}
			fclose(fp);
		}
		DataManager::SetValue("tw_operation_status", 0);
		DataManager::SetValue("tw_operation_state", 1);
		DataManager::SetValue("tw_terminal_state", 0);
		DataManager::SetValue("tw_background_thread_running", 0);
		DataManager::SetValue(TW_ACTION_BUSY, 0);
	}
	return 0;
}

int GUIAction::killterminal(std::string arg)
{
	int op_status = 0;

	LOGINFO("Sending kill command...\n");
	operation_start("KillCommand");
	DataManager::SetValue("tw_operation_status", 0);
	DataManager::SetValue("tw_operation_state", 1);
	DataManager::SetValue("tw_terminal_state", 0);
	DataManager::SetValue("tw_background_thread_running", 0);
	DataManager::SetValue(TW_ACTION_BUSY, 0);
	return 0;
}

int GUIAction::reinjecttwrp(std::string arg)
{
	int op_status = 0;
	operation_start("ReinjectTWRP");
	gui_print("Injecting TWRP into boot image...\n");
	if (simulate) {
		simulate_progress_bar();
	} else {
		TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
		gui_print("TWRP injection complete.\n");
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::checkbackupname(std::string arg)
{
	int op_status = 0;

	operation_start("CheckBackupName");
	if (simulate) {
		simulate_progress_bar();
	} else {
		op_status = PartitionManager.Check_Backup_Name(true);
		if (op_status != 0)
			op_status = 1;
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::decrypt(std::string arg)
{
	int op_status = 0;

	operation_start("Decrypt");
	if (simulate) {
		simulate_progress_bar();
	} else {
		string Password;
		DataManager::GetValue("tw_crypto_password", Password);
		op_status = PartitionManager.Decrypt_Device(Password);
		if (op_status != 0)
			op_status = 1;
		else {

			DataManager::SetValue(TW_IS_ENCRYPTED, 0);

			int has_datamedia;

			// Check for a custom theme and load it if exists
			DataManager::GetValue(TW_HAS_DATA_MEDIA, has_datamedia);
			if (has_datamedia != 0) {
				if (tw_get_default_metadata(DataManager::GetSettingsStoragePath().c_str()) != 0) {
					LOGINFO("Failed to get default contexts and file mode for storage files.\n");
				} else {
					LOGINFO("Got default contexts and file mode for storage files.\n");
				}
			}
		}
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::adbsideload(std::string arg)
{
	operation_start("Sideload");
	if (simulate) {
		simulate_progress_bar();
		operation_end(0);
	} else {
		gui_print("Starting ADB sideload feature...\n");
		bool mtp_was_enabled = TWFunc::Toggle_MTP(false);

		// wait for the adb connection
		int ret = apply_from_adb("/", &sideload_child_pid);
		DataManager::SetValue("tw_has_cancel", 0); // Remove cancel button from gui now that the zip install is going to start

		if (ret != 0) {
			if (ret == -2)
				gui_print("You need adb 1.0.32 or newer to sideload to this device.\n");
			ret = 1; // failure
		} else {
			int wipe_cache = 0;
			int wipe_dalvik = 0;
			DataManager::GetValue("tw_wipe_dalvik", wipe_dalvik);

			if (TWinstall_zip(FUSE_SIDELOAD_HOST_PATHNAME, &wipe_cache) == 0) {
				if (wipe_cache || DataManager::GetIntValue("tw_wipe_cache"))
					PartitionManager.Wipe_By_Path("/cache");
				if (wipe_dalvik)
					PartitionManager.Wipe_Dalvik_Cache();
			} else {
				ret = 1; // failure
			}
		}
		if (sideload_child_pid) {
			LOGINFO("Signaling child sideload process to exit.\n");
			struct stat st;
			// Calling stat() on this magic filename signals the minadbd
			// subprocess to shut down.
			stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
			int status;
			LOGINFO("Waiting for child sideload process to exit.\n");
			waitpid(sideload_child_pid, &status, 0);
		}

		TWFunc::Toggle_MTP(mtp_was_enabled);
		reinject_after_flash();
		operation_end(ret);
	}
	return 0;
}

int GUIAction::adbsideloadcancel(std::string arg)
{
	struct stat st;
	DataManager::SetValue("tw_has_cancel", 0); // Remove cancel button from gui
	gui_print("Cancelling ADB sideload...\n");
	LOGINFO("Signaling child sideload process to exit.\n");
	// Calling stat() on this magic filename signals the minadbd
	// subprocess to shut down.
	stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &st);
	if (!sideload_child_pid) {
		LOGERR("Unable to get child ID\n");
		return 0;
	}
	::sleep(1);
	LOGINFO("Killing child sideload process.\n");
	kill(sideload_child_pid, SIGTERM);
	int status;
	LOGINFO("Waiting for child sideload process to exit.\n");
	waitpid(sideload_child_pid, &status, 0);
	sideload_child_pid = 0;
	DataManager::SetValue("tw_page_done", "1"); // For OpenRecoveryScript support
	return 0;
}

int GUIAction::openrecoveryscript(std::string arg)
{
	operation_start("OpenRecoveryScript");
	if (simulate) {
		simulate_progress_bar();
		operation_end(0);
	} else {
		// Check for the SCRIPT_FILE_TMP first as these are AOSP recovery commands
		// that we converted to ORS commands during boot in recovery.cpp.
		// Run those first.
		int reboot = 0;
		if (TWFunc::Path_Exists(SCRIPT_FILE_TMP)) {
			gui_print("Processing AOSP recovery commands...\n");
			if (OpenRecoveryScript::run_script_file() == 0) {
				reboot = 1;
			}
		}
		// Check for the ORS file in /cache and attempt to run those commands.
		if (OpenRecoveryScript::check_for_script_file()) {
			gui_print("Processing OpenRecoveryScript file...\n");
			if (OpenRecoveryScript::run_script_file() == 0) {
				reboot = 1;
			}
		}
		if (reboot) {
			// Disable stock recovery reflashing
			TWFunc::Disable_Stock_Recovery_Replace();
			usleep(2000000); // Sleep for 2 seconds before rebooting
			TWFunc::tw_reboot(rb_system);
		} else {
			DataManager::SetValue("tw_page_done", 1);
		}
		operation_end(1);
		return 0;
	}
	return 0;
}

int GUIAction::installsu(std::string arg)
{
	int op_status = 0;

	operation_start("Install SuperSU");
	if (simulate) {
		simulate_progress_bar();
	} else {
		if (!TWFunc::Install_SuperSU())
			op_status = 1;
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::fixsu(std::string arg)
{
	int op_status = 0;

	operation_start("Fixing Superuser Permissions");
	if (simulate) {
		simulate_progress_bar();
	} else {
		LOGERR("Fixing su permissions was deprecated from TWRP.\n");
		LOGERR("4.3+ ROMs with SELinux will always lose su perms.\n");
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::decrypt_backup(std::string arg)
{
	int op_status = 0;

	operation_start("Try Restore Decrypt");
	if (simulate) {
		simulate_progress_bar();
	} else {
		string Restore_Path, Filename, Password;
		DataManager::GetValue("tw_restore", Restore_Path);
		Restore_Path += "/";
		DataManager::GetValue("tw_restore_password", Password);
		TWFunc::SetPerformanceMode(true);
		if (TWFunc::Try_Decrypting_Backup(Restore_Path, Password))
			op_status = 0; // success
		else
			op_status = 1; // fail
		TWFunc::SetPerformanceMode(false);
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::repair(std::string arg)
{
	int op_status = 0;

	operation_start("Repair Partition");
	if (simulate) {
		simulate_progress_bar();
	} else {
		string part_path;
		DataManager::GetValue("tw_partition_mount_point", part_path);
		if (PartitionManager.Repair_By_Path(part_path, true)) {
			op_status = 0; // success
		} else {
			LOGERR("Error repairing file system.\n");
			op_status = 1; // fail
		}
	}

	operation_end(op_status);
	return 0;
}

int GUIAction::changefilesystem(std::string arg)
{
	int op_status = 0;

	operation_start("Change File System");
	if (simulate) {
		simulate_progress_bar();
	} else {
		string part_path, file_system;
		DataManager::GetValue("tw_partition_mount_point", part_path);
		DataManager::GetValue("tw_action_new_file_system", file_system);
		if (PartitionManager.Wipe_By_Path(part_path, file_system)) {
			op_status = 0; // success
		} else {
			LOGERR("Error changing file system.\n");
			op_status = 1; // fail
		}
	}
	PartitionManager.Update_System_Details();
	operation_end(op_status);
	return 0;
}

int GUIAction::startmtp(std::string arg)
{
	int op_status = 0;

	operation_start("Start MTP");
	if (PartitionManager.Enable_MTP())
		op_status = 0; // success
	else
		op_status = 1; // fail

	operation_end(op_status);
	return 0;
}

int GUIAction::stopmtp(std::string arg)
{
	int op_status = 0;

	operation_start("Stop MTP");
	if (PartitionManager.Disable_MTP())
		op_status = 0; // success
	else
		op_status = 1; // fail

	operation_end(op_status);
	return 0;
}

int GUIAction::flashimage(std::string arg)
{
	int op_status = 0;

	operation_start("Flash Image");
	string path, filename, full_filename;
	DataManager::GetValue("tw_zip_location", path);
	DataManager::GetValue("tw_file", filename);
	full_filename = path + "/" + filename;
	if (PartitionManager.Flash_Image(full_filename))
		op_status = 0; // success
	else
		op_status = 1; // fail

	operation_end(op_status);
	return 0;
}

int GUIAction::getKeyByName(std::string key)
{
	if (key == "home")			return KEY_HOME;
	else if (key == "menu")		return KEY_MENU;
	else if (key == "back")	 	return KEY_BACK;
	else if (key == "search")	return KEY_SEARCH;
	else if (key == "voldown")	return KEY_VOLUMEDOWN;
	else if (key == "volup")	return KEY_VOLUMEUP;
	else if (key == "power") {
		int ret_val;
		DataManager::GetValue(TW_POWER_BUTTON, ret_val);
		if (!ret_val)
			return KEY_POWER;
		else
			return ret_val;
	}

	return atol(key.c_str());
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Standard styling for menus created by goog.ui.SubMenuRenderer.
 *
 * @author attila@google.com (Attila Bodis)
 */

/* State: resting. */
/* @noflip */
.goog-submenu-arrow {
  color: #000;
  left: auto;
  padding-right: 6px;
  position: absolute;
  right: 0;
  text-align: right;
}

/* BiDi override. */
/* @noflip */
.goog-menuitem-rtl .goog-submenu-arrow {
  text-align: left;
  left: 0;
  right: auto;
  padding-left: 6px;
}

/* State: disabled. */
.goog-menuitem-disabled .goog-submenu-arrow {
  color: #ccc;
}


text:
package org.olat.lms.scorm.server.sequence;

/**
 * RELOAD TOOLS Copyright (c) 2003 Oleg Liber, Bill Olivier, Phillip Beauvoir, Paul Sharples 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. Project Management Contact: Oleg Liber Bolton
 * Institute of Higher Education Deane Road Bolton BL3 5AB UK e-mail: o.liber@bolton.ac.uk Technical Contact: Phillip Beauvoir e-mail: p.beauvoir@bolton.ac.uk Paul
 * Sharples e-mail: p.sharples@bolton.ac.uk Web: http://www.reload.ac.uk
 */

import org.olat.lms.scorm.ISettingsHandler;
import org.olat.lms.scorm.server.servermodels.ScoDocument;

import uk.ac.reload.moonunit.contentpackaging.SCORM12_Core;

/**
 * A class used to house a single item from a scorm package. It should only contain items that actually reference something. Here we store data about this particular item
 * - its launch, its title, its ID, etc Also this class associates a ScoDocument with this item, but only if its a sco, not for assets. A ScoDocument looks after the
 * persisting of the CMI datamodel back to xml, and also reading it back into the javascript server model.
 *
 * @author Paul Sharples
 */
public class ItemSequence {

    // Here we store some information about this item
    private boolean _hasPrerequisites;
    private String _prerequisites;
    private String _scoitemID;
    private String _title;
    private String _launchUrl;
    private int _sequence;
    private String _scormType;
    // If this item is a sco, then we will associate it with a ScoDocument
    private ScoDocument _scoDataModel;
    private final ISettingsHandler settings;

    /**
     * Constructor
     */
    public ItemSequence(final ISettingsHandler settings) {
        this.settings = settings;
    }

    /**
     * Accessor method - set the title
     *
     * @param title
     */
    public void setTitle(final String title) {
        _title = title;
    }

    /**
     * Accessor method - get the title
     *
     * @return title String
     */
    public String getTitle() {
        return _title;
    }

    /**
     * Accessor method set the launch
     *
     * @param id
     */
    public void setLaunchUrl(final String id) {
        // _launchUrl = "../" + id;
        _launchUrl = id;
    }

    /**
     * Accessor method - get the launch
     *
     * @return String launch uri
     */
    public String getLaunchUrl() {
        return _launchUrl;
    }

    /**
     * Accessor - set the sequence number
     *
     * @param seq
     */
    public void setSequence(final int seq) {
        _sequence = seq;
    }

    /***
     * Accessor - get the sequence number
     *
     * @return int
     */

    public int getSequence() {
        return _sequence;
    }

    /**
     * Accessor method - to return the full cmi datamodel as a 2-d string array
     *
     * @return String[][]
     */
    public String[][] getScoModel() {
        return _scoDataModel.getScoModel();
    }

    /**
     * Method to allow us to update the cmi datamodel (persist it back to disk)
     *
     * @param entries
     *            - the name/value pairs
     */
    public void updateClientModel(final String[][] entries) {
        _scoDataModel.doLmsCommit(entries);
    }

    /**
     * Method to set the sco type for this class and if its an sco, then load in the xml cmi model for it.
     *
     * @param scoType
     *            string which is the ID of the item
     */
    public void setScoType(final String scoType) {
        _scormType = scoType;
    }

    /**
     * Method to associate and load in the cmi model for this sco (if it is one)
     */
    public void loadInModel() {
        // if this is a sco then we need to access the
        // cmi data model we created when importing the package
        if (isItemSco()) {
            if (_scoitemID != null) {
                final ScoDocument anSco = new ScoDocument(settings);
                anSco.loadDocument(_scoitemID);
                _scoDataModel = anSco;
            }
        }
    }

    /**
     * Method to ascertain if an item is a SCO or not
     *
     * @return true/false
     */
    public boolean isItemSco() {
        return (_scormType.equals(SCORM12_Core.SCO));
    }

    /**
     * Accessor method - to set this items ID
     *
     * @param id
     */
    public void setItemId(final String id) {
        _scoitemID = id;
    }

    /**
     * Accessor method to allow us to get this item ID
     *
     * @return String
     */
    public String getItemId() {
        return _scoitemID;
    }

    /**
     * Accessor method to allow us to return any prerequisites on this item
     *
     * @return String
     */
    public String getPrerequisites() {
        return _prerequisites;
    }

    /**
     * Method to allow us to set any prerequisites for this item. If there is a string of chars found in the prerequisistes slot, then we parse it (using the static
     * method in PrerequisiteManager), to ensure that the string is a valid prerequisite string and not just rubbish. If the string does not make sense, then it is
     * junked!
     *
     * @param aprereq
     */
    public void setPrerequisites(final String aprereq) {
        if (!aprereq.equals("")) {
            // get rid of any spaces
            final String pre = aprereq.replaceAll(" ", "");
            // check the prerequisites for legality
            if (PrerequisiteManager.isValid(pre)) {
                _prerequisites = pre;
                _hasPrerequisites = true;
            }
            // if they are not legal, then junk them...
            else {
                _hasPrerequisites = false;
            }
        } else {
            _hasPrerequisites = false;
        }
    }

    /**
     * Accessor method to find aout if there are any prerequisistes attached to this item.
     *
     * @return - boolean
     */
    public boolean hasPrerequisites() {
        return _hasPrerequisites;
    }

}


text:
package com.zhy.sample.viewinjector;

import android.view.View;
import com.zhy.util.ioc.Finder;
import com.zhy.util.ioc.processor.AbstractInjector;

public class MainActivity$$PROXY<T extends MainActivity> implements AbstractInjector<T> {
  @Override public void inject(final Finder finder, final T target, Object source) {
finder.setContentView( source , 2130903040 );
    View view;
    view = finder.findViewById(source , 2131230721 );
    target.mLvDetails = finder.castView( view , 2131230721 , "mLvDetails " );    view = finder.findViewById(source , 2131230720 );
    target.mTvName = finder.castView( view , 2131230720 , "mTvName " );  }

}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>NAnt</name>
    </assembly>
    <members>
        <member name="T:NAnt.Console.ConsoleStub">
            <summary>
            Stub used to created <see cref="T:System.AppDomain"/> and launch real <c>ConsoleDriver</c>
            class in Core assembly.
            </summary>
        </member>
        <member name="M:NAnt.Console.ConsoleStub.Main(System.String[])">
            <summary>
            Entry point for executable
            </summary>
            <param name="args">Command Line arguments</param>
            <returns>The result of the real execution</returns>
        </member>
        <member name="M:NAnt.Console.ConsoleStub.ConstructPrivateBinPath(NAnt.Console.ConsoleStub.Framework,System.String)">
            <summary>
            Constructs the privatebinpath.
            </summary>
            <remarks>
              <para>
              For the common version dir, we do not use the framework version
              as defined in the NAnt configuration file but the CLR version
              since the assemblies in that directory are not specific to a
              certain family and the framwork version might differ between
              families (eg. mono 1.0 == .NET 1.1).
              </para>
            </remarks>
            <param name="runtimeFramework">The runtime framework.</param>
            <param name="baseDir">The base directory of the domain.</param>
            <returns>
            The privatebinpath.
            </returns>
        </member>
        <member name="M:NAnt.Console.ConsoleStub.GetRelativePath(System.String,System.String)">
            <summary>
            Given an absolute directory and an absolute file name, returns a
            relative file name.
            </summary>
            <param name="basePath">An absolute directory.</param>
            <param name="absolutePath">An absolute file name.</param>
            <returns>
            A relative file name for the given absolute file name.
            </returns>
        </member>
        <member name="T:NAnt.Console.ConsoleStub.HelperArguments">
            <summary>
            Helper class for invoking the application entry point in NAnt.Core
            and passing the command-line arguments.
            </summary>
        </member>
        <member name="M:NAnt.Console.ConsoleStub.HelperArguments.#ctor(System.String[],System.String)">
            <summary>
            Initializes a new instance of the <see cref="T:NAnt.Console.ConsoleStub.HelperArguments"/>
            class with the specified command-line arguments.
            </summary>
            <param name="args">The commandline arguments passed to NAnt.exe.</param>
            <param name="probePaths">Directories relative to the base directory of the AppDomain to probe for missing assembly references.</param>
        </member>
        <member name="M:NAnt.Console.ConsoleStub.HelperArguments.CallConsoleRunner">
            <summary>
            Invokes the application entry point in NAnt.Core.
            </summary>
        </member>
        <member name="P:NAnt.Console.ConsoleStub.HelperArguments.ExitCode">
            <summary>
            Gets the status that the build process returned when it exited.
            </summary>
            <value>
            The code that the build process specified when it terminated.
            </value>
        </member>
    </members>
</doc>


text:
const MEDIA_EVENT_TYPES = [
  'canplay',
  'durationchange',
  'ended',
  'error',
  'timeupdate',
  'pause',
  'playing',
];

/**
 * The basic video player
 */
export default class BasicVideoPlayer {
  onMediaEvent: ?(any) => void;
  videoElement: HTMLVideoElement;
  _muted: boolean;
  _volume: number;

  /**
   * Subclasses may use this property to define the video format
   * the video player supports. e.g. If a video player defined
   * `supportedFormats = ['mp4']`, when playing a .webm format video,
   * VRVideoComponent will fall back to use other video player.
   */
  static supportedFormats: ?Array<string> = null;

  constructor() {
    this.videoElement = document.createElement('video');
    this.videoElement.style.display = 'none';
    this.videoElement.setAttribute("x5-video-player-type", "h5")
    this.videoElement.setAttribute("x5-video-player-fullscreen", "true");
    if (document.body) {
      document.body.appendChild(this.videoElement);
    }

    this._volume = 1.0;
    this._muted = false;

    this.onMediaEvent = undefined;
    (this: any)._onMediaEvent = this._onMediaEvent.bind(this);
  }

  initializeVideo(src: string, metaData: any) {
    this.videoElement.src = src;
    this.videoElement.crossOrigin = 'anonymous';
    this._bindMediaEvents();
    this.videoElement.load();
  }

  hasEnoughData(): boolean {
    return (
      !!this.videoElement && this.videoElement.readyState === this.videoElement.HAVE_ENOUGH_DATA
    );
  }

  _bindMediaEvents() {
    MEDIA_EVENT_TYPES.forEach(eventType => {
      this.videoElement.addEventListener(eventType, this._onMediaEvent);
    });
  }

  _unbindMediaEvents() {
    MEDIA_EVENT_TYPES.forEach(eventType => {
      this.videoElement.removeEventListener(eventType, this._onMediaEvent);
    });
  }

  _onMediaEvent(event: any) {
    if (typeof this.onMediaEvent === 'function') {
      this.onMediaEvent(event);
    }
  }

  setVolume(volume: number) {
    this.videoElement.volume = volume;
  }

  setMuted(muted: boolean) {
    this.videoElement.muted = muted;
  }

  play() {
    this.videoElement.play();
  }

  pause() {
    this.videoElement.pause();
  }

  seekTo(position: number) {
    this.videoElement.currentTime = position;
  }

  dispose() {
    this.pause();
    if (document.body) {
      document.body.removeChild(this.videoElement);
    }
    this.videoElement.src = '';
    this._unbindMediaEvents();
    this.onMediaEvent = undefined;
  }
}


text:
class GroupsController < ApplicationController
  include GroupHelper

  before_action :authenticate_user!, except: [ :show ]
  before_action :find_group, except: [:index, :new, :create, :feature]
  before_action :is_group_admin, only: [:update, :destroy]
  before_action :is_admin, only: [:feature]

  def index
    @groups = current_user.is_admin? ? Group.order_by(name: :desc).page(params[:page]) : current_user.groups.page(params[:page])
  end

  def new
    @group = Group.new
  end

  def show
    render layout: 'info' unless current_user
  end

  def create
    @group = current_user.groups.build(group_params)
    @group.owner = current_user

    if @group.save
      redirect_to group_path(@group)
    else
      render :new
    end
  end

  def edit
  end

  def feature
    @group = Group.where(id: params[:id]).first
    @group.update(is_featured: !@group.is_featured)
    respond_to do |format|
      format.js { render 'groups/feature' }
    end
  end

  def update
    if @group.update_attributes(group_params)
      redirect_to group_path(@group)
    else
      render :edit
    end
  end

  def destroy
    @group.destroy

    redirect_to groups_path
  end

  private

  def group_params
    params.fetch(:group).permit(:name, :description, :is_featured)
  end

  # methods from the GroupHelper module are public and need to be private
  private :find_group, :is_group_admin, :is_admin

end


text:
This is a simple theme for the [Apache Roller](http://roller.apache.org) blogging software based on a HTML 5 template based on *Unique Template* by [WebThemez.com](http://webthemez.com).

## Usage
Put this folder into Roller's template directory _themes_ or if you have changed the directory via *roller-custom.properties* put it there:
```
...
themes.dir=/opt/roller
```

## Maven usage
Maven is added to this project to ease up development process.

```
mvn clean compile
```

Copies the content of the project directory to a Vagrant machine directory containing the Apache Roller templates.

```
mvn clean package
```

Copies the content to the directory of Vagrant machine (see target above) and creates a package containing the whole theme.

```
mvn clean install
```

Creates the package and installs it by SSH to an external server. Additional _config.properties_ is needed to define the values for _ssh.user_, _ssh.pwd_ and _ssh.host_. The Glassfish server gets automatically restarted.

Additional properties in pom.xml:
* _theme.destination_: destination directory for themes on remote machine for automated deploying.
* _machine.destination_: destination directory for themes on Vagrant machine.

## Missing features
Currently the template is not complete to compete with the templates delivered with Apache Roller or from roller-extras. This list tells what is missing:

*	archives.vm: Calendar browser and links to latest entries
*	search.vm: Search results page
*	tags_index.vm: Tag index page
*	Missing screenshot as preview on template selection

Check out [CHANGELOG](CHANGELOG.md) for the latest changes and fixes.


text:
#ifndef TENSORFLOW_PYTHON_FRAMEWORK_PY_CONTEXT_MANAGER_H_
#define TENSORFLOW_PYTHON_FRAMEWORK_PY_CONTEXT_MANAGER_H_

#include <Python.h>

#include <string>

#include "tensorflow/python/lib/core/safe_pyobject_ptr.h"

namespace tensorflow {

// Class that wraps a Python context manager, and calls the `__enter__` and
// `__exit__` methods at appropriate times:
//
// * When `PyContextManager::Enter(cm)` is called, the context manager `cm`
//   is stored, and `cm.__enter__` is called.  The result can be retrieved
//   with `PyContextManager::var()`.
// * When the `PyContextManager` is destroyed, then `cm.__exit__` is called
//   (with information about any active exception).
// * `PyContextManager::Enter(cm)` may be called at most once. If
//   `PyContextManager::Enter()` is never called, then the destructor is a
//   no-op (i.e., `__exit__` is not called).
//
// PyContextManager places two restrictons on the wrapped context managers:
//
// 1. The context manager may not suppress exceptions -- i.e., `__exit__`
//    may not return a True value.  If it does, then a new exception will be
//    set, indicating that this is unuspported.
// 2. The context manager may not raise an exception from `__exit__` if the
//    an exception is not active when it is called.  If it does, then an error
//    message will be logged, indicating that this is unsupported, and the
//    exception will be suppressed.
//
// These restrictions are both intended to ensure that the state of
// PyErr_Occurred is unchanged by PyContextManager's destructor.  This is
// important, because changing the state of PyErr_Occurred in the destructor
// would mean that we are returning a nullptr with no exception set, or
// returning a non-null value with an exception set (both of which are invalid).
class PyContextManager {
 public:
  // Calls `py_context_manager.__enter__()`, and stores the result in `var`.
  // Return true if `__enter__` succeeds, or false if `__enter__` raises an
  // exception.  (Also returns false if `py_context_manager` is nullptr.)
  //
  // Steals a reference to `py_context_manager`.  (This reference is deleted
  // when the destructor is called.)
  bool Enter(PyObject* py_context_manager);

  // Calls `py_context_manager.__exit__()`.
  ~PyContextManager();

  // Returns the variable returned by `context_manager.__enter__()`.
  // (This is the `var` bound by `with context_manager as var`.)
  // Returns a borrowed reference.
  PyObject* var() { return var_.get(); }

 protected:
  Safe_PyObjectPtr context_manager_;
  Safe_PyObjectPtr var_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_PYTHON_FRAMEWORK_PY_CONTEXT_MANAGER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Code quality toolsJavaScript</id>
          </State>
          <State>
            <id>JavaScript</id>
          </State>
        </expanded-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectRootManager" version="2" project-jdk-name="RVM: ruby-1.9.3-p484 [global]" project-jdk-type="RUBY_SDK" />
  <component name="VagrantProjectSettings">
    <option name="instanceFolder" value="" />
    <option name="provider" value="" />
  </component>
</project>


text:
Rails.application.routes.draw do
  root 'welcome#index'
  resources :users
  resources :expenses
  resources :purchases
  resources :savings, only: [:new, :create]
  resources :expensesheets, only: [:new, :create, :show, :edit, :update]

  get '/profile/:id' => 'users#show', as: 'profile'
  get '/userpurchases/:id' => 'users#userpurchases', as: 'userpurchases'

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  get 'graph/index'
  get 'graph/net_savings_data', :defaults => { :format =>
    'json' }
  get 'graph/savings_vs_purchase_data', :defaults => { :format =>
    'json' }
  get 'graph/expense_percentages_data', :defaults => { :format =>
    'json' }

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
package coding.lien.charles.locationreportsender.util;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.io.Serializable;

/**
 * Author: lienching
 * Description: This class handle Location stuff and this class use singleton.
 */
public class LocationManager implements LocationListener, Serializable {

    private GoogleApiClient user_client;
    private Location user_location;
    private Activity my_activiity;
    private LocationRequest locationRequest;
    private static LocationManager instance;
    public static boolean success;

    private LocationManager(Activity activity, GoogleApiClient client ) {
        this.user_client = client;
        this.my_activiity = activity;
        try {
            this.user_location = LocationServices.FusedLocationApi.getLastLocation(client);
        } // try
        catch(SecurityException e) {
            Log.e("LocationManager", e.toString());
        } // catch
    } // LocationManager( Activity, GoogleApiClient )

    public static void initLocationManager( Activity activity, GoogleApiClient client ) {
        if ( instance != null ) return;
        instance = new LocationManager(activity,client);
    } // initLocationManager( Activity, GoogleApiClient )

    public static LocationManager getInstance() {
        if ( instance != null )
            return instance;
        return null;
    } // getInstance()

    protected void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(7000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    } // createLocationRequest()

    // Not used yet...
    public void SetInterval( String sec ) {
        locationRequest.setInterval( Long.parseLong(sec) * 1000 );
    } // SetInterval( String )

    public void StartUpdate() {
        if (locationRequest != null) {
            startLocationUpdates();
        } // if
        else {
            Log.e("LocationManager", "locationRequest is null");
        } // else
    } // StartUpdate()

    protected void startLocationUpdates() {
        try {
            if ( !user_client.isConnected() ) {
                user_client.connect();
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    user_client, locationRequest, this);
            Log.d("LocationManager", "Start Location Update");
        } // try
        catch(SecurityException e) {
            Log.e("LocationManager", e.toString());
        } // catch
    } // startLocationUpdates

    public void stopLocationUpdates() {
        try {
            if ( !user_client.isConnected() ) {
                user_client.connect();
            }
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    user_client, this);
            Log.d("LocationManager", "Stop Location Update");
        } // try
        catch(SecurityException e) {
            Log.e("LocationManager", e.toString());
        } // catch
    } // stopLocationUpdates()

    public boolean CheckLocationStatus(Context context) {
        // Code from "http://stackoverflow.com/a/22980843"
        int locationMode = 0;
        String locationProviders;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

            } // try
            catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            } // catch

            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } // if
        else{
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        } // else

    } // CheckLocationStatus(Context)

    public Location getUserLocation() {
        try {
            this.user_location = LocationServices.FusedLocationApi.getLastLocation(user_client);
        }
        catch( SecurityException e ) {
            Log.e("LocationManager", e.toString());
        }
        return this.user_location;
    } // getUserLocation()

    @Override
    public void onLocationChanged(Location location) {
        Log.i("LocationManager", "Location Changed: lat:" + location.getLatitude() + " , long:" + location.getLongitude());
        this.user_location = location;
    } // onLocationChanged(Location)

} // class LocationManager


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>ClassFinder xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

1
18
19  package org.apache.hadoop.hbase;
20
21  import java.io.File;
22  import java.io.FileFilter;
23  import java.io.FileInputStream;
24  import java.io.IOException;
25  import java.lang.reflect.Method;
26  import java.lang.reflect.Modifier;
27  import java.net.URL;
28  import java.util.ArrayList;
29  import java.util.Enumeration;
30  import java.util.HashSet;
31  import java.util.List;
32  import java.util.Set;
33  import java.util.jar.*;
34  import java.util.regex.Matcher;
35  import java.util.regex.Pattern;
36
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39
40  /**
41   * A class that finds a set of classes that are locally accessible
42   * (from .class or .jar files), and satisfy the conditions that are
43   * imposed by name and class filters provided by the user.
44   */
45  public class ClassFinder {
46    private static final Log LOG = LogFactory.getLog(ClassFinder.class);
47    private static String CLASS_EXT = ".class";
48
49    private FileNameFilter fileNameFilter;
50    private ClassFilter classFilter;
51    private FileFilter fileFilter;
52
53    public static interface FileNameFilter {
54      public boolean isCandidateFile(String fileName, String absFilePath);
55    };
56
57    public static interface ClassFilter {
58      public boolean isCandidateClass(Class<?> c);
59    };
60
61    public ClassFinder(FileNameFilter fileNameFilter, ClassFilter classFilter) {
62      this.classFilter = classFilter;
63      this.fileNameFilter = fileNameFilter;
64      this.fileFilter = new FileFilterWithName(fileNameFilter);
65    }
66
67    /**
68     * Finds the classes in current package (of ClassFinder) and nested packages.
69     * @param proceedOnExceptions whether to ignore exceptions encountered for
70     *        individual jars/files/classes, and proceed looking for others.
71     */
72    public Set<Class<?>> findClasses(boolean proceedOnExceptions)
73      throws ClassNotFoundException, IOException, LinkageError {
74      return findClasses(this.getClass().getPackage().getName(), proceedOnExceptions);
75    }
76
77    /**
78     * Finds the classes in a package and nested packages.
79     * @param packageName package names
80     * @param proceedOnExceptions whether to ignore exceptions encountered for
81     *        individual jars/files/classes, and proceed looking for others.
82     */
83    public Set<Class<?>> findClasses(String packageName, boolean proceedOnExceptions)
84      throws ClassNotFoundException, IOException, LinkageError {
85      final String path = packageName.replace('.', '/');
86      final Pattern jarResourceRe = Pattern.compile("^file:(.+\\.jar)!/" + path + "$");
87
88      Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(path);
89      List<File> dirs = new ArrayList<File>();
90      List<String> jars = new ArrayList<String>();
91
92      while (resources.hasMoreElements()) {
93        URL resource = resources.nextElement();
94        String resourcePath = resource.getFile();
95        Matcher matcher = jarResourceRe.matcher(resourcePath);
96        if (matcher.find()) {
97          jars.add(matcher.group(1));
98        } else {
99          dirs.add(new File(resource.getFile()));
100       }
101     }
102
103     Set<Class<?>> classes = new HashSet<Class<?>>();
104     for (File directory : dirs) {
105       classes.addAll(findClassesFromFiles(directory, packageName, proceedOnExceptions));
106     }
107     for (String jarFileName : jars) {
108       classes.addAll(findClassesFromJar(jarFileName, packageName, proceedOnExceptions));
109     }
110     return classes;
111   }
112
113   private Set<Class<?>> findClassesFromJar(String jarFileName,
114       String packageName, boolean proceedOnExceptions)
115     throws IOException, ClassNotFoundException, LinkageError {
116     JarInputStream jarFile = null;
117     try {
118       jarFile = new JarInputStream(new FileInputStream(jarFileName));
119     } catch (IOException ioEx) {
120       if (!proceedOnExceptions) {
121         throw ioEx;
122       }
123       LOG.warn("Failed to look for classes in " + jarFileName + ": " + ioEx);
124     }
125
126     Set<Class<?>> classes = new HashSet<Class<?>>();
127     JarEntry entry = null;
128     while (true) {
129       try {
130         entry = jarFile.getNextJarEntry();
131       } catch (IOException ioEx) {
132         if (!proceedOnExceptions) {
133           throw ioEx;
134         }
135         LOG.warn("Failed to get next entry from " + jarFileName + ": " + ioEx);
136         break;
137       }
138       if (entry == null) {
139         break; // loop termination condition
140       }
141
142       String className = entry.getName();
143       if (!className.endsWith(CLASS_EXT)) {
144         continue;
145       }
146       int ix = className.lastIndexOf('/');
147       String fileName = (ix >= 0) ? className.substring(ix + 1) : className;
148       if (!this.fileNameFilter.isCandidateFile(fileName, className)) {
149         continue;
150       }
151       className = className
152           .substring(0, className.length() - CLASS_EXT.length()).replace('/', '.');
153       if (!className.startsWith(packageName)) {
154         continue;
155       }
156       Class<?> c = makeClass(className, proceedOnExceptions);
157       if (c != null) {
158         if (!classes.add(c)) {
159           LOG.warn("Ignoring duplicate class " + className);
160         }
161       }
162     }
163     return classes;
164   }
165
166   private Set<Class<?>> findClassesFromFiles(File baseDirectory, String packageName,
167       boolean proceedOnExceptions) throws ClassNotFoundException, LinkageError {
168     Set<Class<?>> classes = new HashSet<Class<?>>();
169     if (!baseDirectory.exists()) {
170       LOG.warn("Failed to find " + baseDirectory.getAbsolutePath());
171       return classes;
172     }
173
174     File[] files = baseDirectory.listFiles(this.fileFilter);
175     if (files == null) {
176       LOG.warn("Failed to get files from " + baseDirectory.getAbsolutePath());
177       return classes;
178     }
179
180     for (File file : files) {
181       final String fileName = file.getName();
182       if (file.isDirectory()) {
183         classes.addAll(findClassesFromFiles(file, packageName + "." + fileName,
184             proceedOnExceptions));
185       } else {
186         String className = packageName + '.'
187             + fileName.substring(0, fileName.length() - CLASS_EXT.length());
188         Class<?> c = makeClass(className, proceedOnExceptions);
189         if (c != null) {
190           if (!classes.add(c)) {
191             LOG.warn("Ignoring duplicate class " + className);
192           }
193         }
194       }
195     }
196     return classes;
197   }
198
199   private Class<?> makeClass(String className, boolean proceedOnExceptions)
200     throws ClassNotFoundException, LinkageError {
201     try {
202       Class<?> c = Class.forName(className, false, this.getClass().getClassLoader());
203       return classFilter.isCandidateClass(c) ? c : null;
204     } catch (ClassNotFoundException classNotFoundEx) {
205       if (!proceedOnExceptions) {
206         throw classNotFoundEx;
207       }
208       LOG.info("Failed to instantiate or check " + className + ": " + classNotFoundEx);
209     } catch (LinkageError linkageEx) {
210       if (!proceedOnExceptions) {
211         throw linkageEx;
212       }
213       LOG.info("Failed to instantiate or check " + className + ": " + linkageEx);
214     }
215     return null;
216   }
217
218   private class FileFilterWithName implements FileFilter {
219     private FileNameFilter nameFilter;
220
221     public FileFilterWithName(FileNameFilter nameFilter) {
222       this.nameFilter = nameFilter;
223     }
224
225     @Override
226     public boolean accept(File file) {
227       return file.isDirectory()
228           || (file.getName().endsWith(CLASS_EXT)
229               && nameFilter.isCandidateFile(file.getName(), file.getAbsolutePath()));
230     }
231   };
232 };

This page was automatically generated by Maven


text:
```
$ mvn package
```

## Run
```
$ java -jar target/pinpoint-vertx-4-plugin-testweb-$VERSION-fat.jar
```
You can then access here: http://localhost:18080/


text:
package org.apache.spark.mllib.linalg

import com.github.fommil.netlib.LAPACK.{getInstance => lapack}
import org.netlib.util.intW

/**
 * Compute Cholesky decomposition.
 */
private[spark] object CholeskyDecomposition {

  /**
   * Solves a symmetric positive definite linear system via Cholesky factorization.
   * The input arguments are modified in-place to store the factorization and the solution.
   * @param A the upper triangular part of A
   * @param bx right-hand side
   * @return the solution array
   */
  def solve(A: Array[Double], bx: Array[Double]): Array[Double] = {
    val k = bx.size
    val info = new intW(0)
    lapack.dppsv("U", k, 1, A, bx, k, info)
    val code = info.`val`
    assert(code == 0, s"lapack.dppsv returned $code.")
    bx
  }

  /**
   * Computes the inverse of a real symmetric positive definite matrix A
   * using the Cholesky factorization A = U**T*U.
   * The input arguments are modified in-place to store the inverse matrix.
   * @param UAi the upper triangular factor U from the Cholesky factorization A = U**T*U
   * @param k the dimension of A
   * @return the upper triangle of the (symmetric) inverse of A
   */
  def inverse(UAi: Array[Double], k: Int): Array[Double] = {
    val info = new intW(0)
    lapack.dpptri("U", k, UAi, info)
    val code = info.`val`
    assert(code == 0, s"lapack.dpptri returned $code.")
    UAi
  }
}


text:
using System;
using Android.Content;
using Com.Android.Vending.Billing;
using Android.Util;

namespace InAppService
{
	public class InAppBillingServiceConnection: Java.Lang.Object, IServiceConnection
	{
		public InAppBillingServiceConnection (Context context, Action<bool> setupFinished)
		{
			_context = context;
			_setupFinished = setupFinished;
		}

		public IInAppBillingService Service {
			get;
			private set;
		}

		#region IServiceConnection implementation

		public void OnServiceConnected (ComponentName name, Android.OS.IBinder service)
		{
			LogDebug ("Billing service connected.");
			Service = IInAppBillingServiceStub.AsInterface (service);

			string packageName = _context.PackageName;

			try {
				LogDebug ("Checking for in-app billing V3 support");

				int response = Service.IsBillingSupported (Constants.APIVersion, packageName, ItemType.InApp);
				if (response != BillingResult.OK) {
					SetupFinished(false);
				}

				LogDebug("In-app billing version 3 supported for " + packageName);

				// check for v3 subscriptions support
				response = Service.IsBillingSupported(Constants.APIVersion, packageName, ItemType.Subscription);
				if (response == BillingResult.OK) {
					LogDebug("Subscriptions AVAILABLE.");
					SetupFinished(true);
					return;
				}
				else {
					LogDebug("Subscriptions NOT AVAILABLE. Response: " + response);
				}

			} catch (Exception ex) {
				LogDebug (ex.ToString());
				SetupFinished (false);
			}

			SetupFinished (false);
		}

		public void OnServiceDisconnected (ComponentName name)
		{
			Service = null;
		}

		void SetupFinished(bool isServiceCreated)
		{
			if (_setupFinished != null) {
				_setupFinished (isServiceCreated);
			}
		}

		#endregion

		void LogDebug (String msg)
		{
			Log.Debug (Tag, msg);
		}

		void LogError (String msg)
		{
			Log.Error (Tag, "In-app billing error: " + msg);
		}

		void LogWarn (String msg)
		{
			Log.Warn (Tag, "In-app billing warning: " + msg);
		}

		Action<bool> _setupFinished;
		Context _context;

		const string Tag = "Iab Helper";

	}
}


text:
package algs.model.searchtree;

/**
 * Records the depth of the transition between board states.
 *

 * Used by DepthFirstSearch when deciding whether to advance a board state.
 *
 * @author George Heineman
 * @version 1.0, 6/15/08
 * @since 1.0
 */
public class DepthTransition extends Transition {

	/** Depth away from the initial board state. */
	public final int depth;

	/**
	 * Record the move and previous state of this transition.
	 *

	 * Since this is a depth transition, also record the depth.
	 *
	 * @param move   Move which caused the transition
	 * @param prev   The previous board state
	 * @param depth  The distance from the initial board state
	 */
	public DepthTransition(IMove move, INode prev, int depth) {
		super(move, prev);

		this.depth = depth;
	}

}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("sponsors", "0005_auto_20201015_0908"),
    ]

    operations = [
        migrations.RenameModel(
            old_name="SponsorshipLevel",
            new_name="SponsorshipPackage",
        ),
        migrations.RemoveField(
            model_name="sponsorshipbenefit",
            name="levels",
        ),
        migrations.RemoveField(
            model_name="sponsorshipbenefit",
            name="minimum_level",
        ),
        migrations.AddField(
            model_name="sponsorshipbenefit",
            name="new",
            field=models.BooleanField(
                default=False,
                help_text='If selected, display a "New This Year" badge along side the benefit.',
                verbose_name="New Benefit",
            ),
        ),
        migrations.AddField(
            model_name="sponsorshipbenefit",
            name="package_only",
            field=models.BooleanField(
                default=False,
                help_text="If a benefit is only available via a sponsorship package, select this option.",
                verbose_name="Package Only Benefit",
            ),
        ),
        migrations.AddField(
            model_name="sponsorshipbenefit",
            name="packages",
            field=models.ManyToManyField(
                help_text="What sponsorship packages this benefit is included in.",
                related_name="benefits",
                to="sponsors.SponsorshipPackage",
                verbose_name="Sponsorship Packages",
            ),
        ),
        migrations.AddField(
            model_name="sponsorshipbenefit",
            name="soft_capacity",
            field=models.BooleanField(
                default=False,
                help_text="If a benefit's capacity is flexible, select this option.",
                verbose_name="Soft Capacity",
            ),
        ),
        migrations.AlterField(
            model_name="sponsorshipbenefit",
            name="internal_value",
            field=models.PositiveIntegerField(
                blank=True,
                help_text="Value used internally to calculate sponsorship value when applicants construct their own sponsorship packages.",
                null=True,
                verbose_name="Internal Value",
            ),
        ),
    ]


text: This is a npm tutorial from npm to teach making modules for npm.


text:
import { injector } from "../yok";
import { ICommand, ICommandParameter } from "../definitions/commands";
import { IDoctorService, IProjectHelper } from "../declarations";
import { PlatformTypes } from "../../constants";

export class DoctorCommand implements ICommand {
	constructor(
		private $doctorService: IDoctorService,
		private $projectHelper: IProjectHelper
	) {}

	public allowedParameters: ICommandParameter[] = [];

	public execute(args: string[]): Promise<void> {
		return this.$doctorService.printWarnings({
			trackResult: false,
			projectDir: this.$projectHelper.projectDir,
			forceCheck: true,
		});
	}
}
injector.registerCommand("doctor|*all", DoctorCommand);

export class DoctorIosCommand implements ICommand {
	constructor(
		private $doctorService: IDoctorService,
		private $projectHelper: IProjectHelper
	) {}

	public allowedParameters: ICommandParameter[] = [];

	public execute(args: string[]): Promise<void> {
		return this.$doctorService.printWarnings({
			trackResult: false,
			projectDir: this.$projectHelper.projectDir,
			forceCheck: true,
			platform: PlatformTypes.ios,
		});
	}
}

injector.registerCommand("doctor|ios", DoctorIosCommand);

export class DoctorAndroidCommand implements ICommand {
	constructor(
		private $doctorService: IDoctorService,
		private $projectHelper: IProjectHelper
	) {}

	public allowedParameters: ICommandParameter[] = [];

	public execute(args: string[]): Promise<void> {
		return this.$doctorService.printWarnings({
			trackResult: false,
			projectDir: this.$projectHelper.projectDir,
			forceCheck: true,
			platform: PlatformTypes.android,
		});
	}
}

injector.registerCommand("doctor|android", DoctorAndroidCommand);


text:
package com.deleidos.rtws.webapp.register.form;

public interface Form {

}


text:
<ion-view style="" title="Zezi">
    <ion-nav-buttons side="left">
        <button class="button-icon fa fa-search customHeaderIcon customHeaderIconSmall extraMarginRight" ng-click="showFilterBar()"></button>
    </ion-nav-buttons>
    <button class="button button-post" ng-click="createPosting()">

    </button>
    <ion-content class="has-header" padding="true">
    <ion-refresher pulling-text="Pull to refresh" refreshing-text="Loading..." refreshing-icon="ion-loading-c" pulling-icon="ion-ios7-arrow-thin-down" on-refresh="doRefresh()">
    </ion-refresher>

{{ public.name }}

{{ public.date | date : "h:mm a" }} . {{ public.location }}

{{ public.note }}

{{ public.likes }}

{{ public.comments }}

{{ public.views }}

    </ion-content>
</ion-view>


text:
'use strict';
angular.module('components')
    .factory('RestFullResponse', ['Restangular', function (Restangular) {
        return Restangular.withConfig(function (RestangularConfigurer) {
            RestangularConfigurer.setFullResponse(true);
        });
    }]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <laws />
    <latestAction>
      <actionDate>2017-03-27</actionDate>
      <text>Referred to the House Committee on House Administration.</text>
      <links />
    </latestAction>
    <version>1.0.0</version>
    <policyArea>
      <name>Government Operations and Politics</name>
    </policyArea>
    <summaries>
      <billSummaries />
    </summaries>
    <congress>115</congress>
    <originChamber>House</originChamber>
    <calendarNumbers />
    <updateDate>2017-08-28T21:45:30Z</updateDate>
    <committeeReports />
    <billType>HR</billType>
    <committees>
      <billCommittees>
        <item>
          <activities>
            <item>
              <date>2017-03-27T16:02:25Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <subcommittees />
          <systemCode>hsha00</systemCode>
          <chamber>House</chamber>
          <name>House Administration Committee</name>
          <type>Standing</type>
        </item>
      </billCommittees>
    </committees>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. O'ROURKE:H.R. 1743.Congress has the power to enact this legislation pursuantto the following:Section 4 of Article I of the Constitution:The times, places and manner of holding elections forSenators and Representatives, shall be prescribed in eachstate by the legislature thereof; but the Congress may at anytime by law make or alter such regulations, except as to theplaces of choosing Senators.[Page H2464]
]]></constitutionalAuthorityStatementText>
    <billNumber>1743</billNumber>
    <titles>
      <item>
        <parentTitleType />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberCode />
        <title>No PAC Act</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Short Titles as Introduced</titleType>
        <chamberCode />
        <title>No PAC Act</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Official Title as Introduced</titleType>
        <chamberCode />
        <title>To amend the Federal Election Campaign Act of 1971 to prohibit a candidate for election to the office or Representative in Congress or Senator from accepting contributions from any political committee other than an authorized committee of the candidate and from establishing a leadership PAC.</title>
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Display Title</titleType>
        <chamberCode />
        <title>No PAC Act</title>
        <chamberName />
      </item>
    </titles>
    <notes />
    <introducedDate>2017-03-27</introducedDate>
    <cboCostEstimates />
    <relatedBills />
    <cosponsors>
      <item>
        <lastName>Khanna</lastName>
        <fullName>Rep. Khanna, Ro [D-CA-17]</fullName>
        <middleName />
        <identifiers>
          <gpoId />
          <lisID>2308</lisID>
          <bioguideId>K000389</bioguideId>
        </identifiers>
        <sponsorshipDate>2017-03-27</sponsorshipDate>
        <state>CA</state>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <firstName>Ro</firstName>
        <bioguideId>K000389</bioguideId>
        <district>17</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
      </item>
    </cosponsors>
    <createDate>2017-03-28T05:32:32Z</createDate>
    <recordedVotes />
    <actions>
      <actionTypeCounts>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
        <introducedInHouse>1</introducedInHouse>
      </actionTypeCounts>
      <item>
        <actionCode>H11100</actionCode>
        <actionDate>2017-03-27</actionDate>
        <committee>
          <name>House Administration Committee</name>
          <systemCode>hsha00</systemCode>
        </committee>
        <text>Referred to the House Committee on House Administration.</text>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <links />
        <type>IntroReferral</type>
      </item>
      <item>
        <actionCode>Intro-H</actionCode>
        <actionDate>2017-03-27</actionDate>
        <committee />
        <text>Introduced in House</text>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <links />
        <type>IntroReferral</type>
      </item>
      <item>
        <actionCode>1000</actionCode>
        <actionDate>2017-03-27</actionDate>
        <committee />
        <text>Introduced in House</text>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <links />
        <type>IntroReferral</type>
      </item>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
    </actions>
    <amendments />
    <title>No PAC Act</title>
    <sponsors>
      <item>
        <fullName>Rep. O'Rourke, Beto [D-TX-16]</fullName>
        <district>16</district>
        <lastName>O'Rourke</lastName>
        <byRequestType />
        <party>D</party>
        <state>TX</state>
        <middleName />
        <bioguideId>O000170</bioguideId>
        <firstName>Beto</firstName>
        <identifiers>
          <bioguideId>O000170</bioguideId>
          <lisID>2162</lisID>
          <gpoId />
        </identifiers>
      </item>
    </sponsors>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Congressional elections</name>
          </item>
          <item>
            <name>Elections, voting, political campaign regulation</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Government Operations and Politics</name>
        </policyArea>
      </billSubjects>
    </subjects>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
from django.contrib.auth.models import User
from django.db import models

from spa.models import BaseModel, UserProfile
from spa.models.mix import Mix

class Comment(BaseModel):
    class Meta:
        app_label = 'spa'

    user = models.ForeignKey(User, editable=False, null=True, blank=True)
    mix = models.ForeignKey(Mix, editable=False, null=True, blank=True, related_name='comments')
    comment = models.CharField(max_length=1024)
    date_created = models.DateTimeField(auto_now_add=True)
    time_index = models.IntegerField(default=0)
    likes = models.ManyToManyField(UserProfile, related_name='liked_comments', blank=True, null=True)

    def get_absolute_url(self):
        return '/comment/%i' % self.id

    def create_activity(self):
        pass

    @property
    def avatar_image(self):
        if self.user is None:
            return UserProfile.get_default_avatar_image()
        else:
            return self.user.get_profile().get_avatar_image()