text:
package org.unitime.timetable.gwt.client.rooms;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.unitime.timetable.gwt.client.Client;
import org.unitime.timetable.gwt.client.ToolBox;
import org.unitime.timetable.gwt.client.aria.AriaButton;
import org.unitime.timetable.gwt.client.events.AcademicSessionSelectionBox;
import org.unitime.timetable.gwt.client.page.UniTimeNotifications;
import org.unitime.timetable.gwt.client.page.UniTimePageHeader;
import org.unitime.timetable.gwt.client.page.UniTimePageLabel;
import org.unitime.timetable.gwt.client.rooms.RoomsPage.HistoryToken;
import org.unitime.timetable.gwt.client.rooms.RoomsTable.DeptMode;
import org.unitime.timetable.gwt.client.widgets.LoadingWidget;
import org.unitime.timetable.gwt.client.widgets.SimpleForm;
import org.unitime.timetable.gwt.client.widgets.UniTimeHeaderPanel;
import org.unitime.timetable.gwt.client.widgets.FilterBox.Chip;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable.MouseClickListener;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable.TableEvent;
import org.unitime.timetable.gwt.command.client.GwtRpcResponseList;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.resources.GwtResources;
import org.unitime.timetable.gwt.shared.AcademicSessionProvider;
import org.unitime.timetable.gwt.shared.AcademicSessionProvider.AcademicSessionChangeEvent;
import org.unitime.timetable.gwt.shared.AcademicSessionProvider.AcademicSessionChangeHandler;
import org.unitime.timetable.gwt.shared.EventInterface.EncodeQueryRpcRequest;
import org.unitime.timetable.gwt.shared.EventInterface.EncodeQueryRpcResponse;
import org.unitime.timetable.gwt.shared.EventInterface.FilterRpcRequest;
import org.unitime.timetable.gwt.shared.EventInterface.FilterRpcResponse;
import org.unitime.timetable.gwt.shared.RoomInterface.DepartmentInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.ExamTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FeatureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomFeaturesColumn;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPropertiesInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPropertiesRequest;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomsPageMode;
import org.unitime.timetable.gwt.shared.RoomInterface.SearchRoomFeaturesRequest;

import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Tomas Muller
 */
public class RoomFeaturesPage extends Composite {
	protected static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);
	protected static final GwtResources RESOURCES =  GWT.create(GwtResources.class);
	protected static GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);

	private AcademicSessionProvider iSession = null;
	private RoomFilterBox iFilter = null;
	private AriaButton iSearch = null;
	private AriaButton iNew = null;
	private AriaButton iMore = null;

	private SimpleForm iFeaturesPanel = null;
	private SimplePanel iRootPanel;

	private SimplePanel iPanel = null;
	private HorizontalPanel iFilterPanel = null;
	private RoomPropertiesInterface iProperties = null;
	private UniTimeHeaderPanel iGlobalFeaturesHeader = null;
	private RoomFeaturesTable iGlobalFeaturesTable = null;
	private int iGlobalFeaturesRow = -1;
	private UniTimeHeaderPanel iDepartmentalFeaturesHeader = null;
	private RoomFeaturesTable iDepartmentalFeaturesTable = null;
	private int iDepartmentalFeaturesRow = -1;
	private RoomsPageMode iMode = RoomsPageMode.COURSES;
	private UniTimeHeaderPanel iHeaderPanel = null;
	private HistoryToken iHistoryToken = null;

	private RoomFeatureEdit iRoomFeatureEdit = null;

	public RoomFeaturesPage() {
		if (Location.getParameter("mode") != null)
			iMode = RoomsPageMode.valueOf(Location.getParameter("mode").toUpperCase());
		iHistoryToken = new HistoryToken(iMode);

		iPanel = new SimplePanel();

		iFeaturesPanel = new SimpleForm();
		iFeaturesPanel.setWidth("100%");

		ClickHandler clickSearch = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeUrl();
				search();
			}
		};

		ClickHandler clickMore = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				final PopupPanel popup = new PopupPanel(true);
				MenuBar menu = new MenuBar(true);

				MenuBar sortItems = new MenuBar(true);
				for (final RoomFeaturesColumn column: RoomFeaturesColumn.values()) {
					if (RoomFeaturesComparator.isApplicable(column)) {
						if ((iGlobalFeaturesTable.getRowCount() <= 1 || iGlobalFeaturesTable.getNbrCells(column) == 0) &&
							(iDepartmentalFeaturesTable.getRowCount() <= 1 || iDepartmentalFeaturesTable.getNbrCells(column) == 0)) continue;
						String name = iGlobalFeaturesTable.getColumnName(column, 0).replace("<br>", " ");
						MenuItem item = new MenuItem(name, true, new Command() {
							@Override
							public void execute() {
								popup.hide();
								int sortBy = RoomCookie.getInstance().getRoomFeaturesSortBy();
								if (sortBy == (1 + column.ordinal()) || sortBy == (-1 - column.ordinal())) {
									sortBy = -sortBy;
								} else {
									sortBy = 1 + column.ordinal();
								}
								RoomCookie.getInstance().setSortRoomFeaturesBy(sortBy);
								iGlobalFeaturesTable.setSortBy(sortBy);
								iDepartmentalFeaturesTable.setSortBy(sortBy);
							}
						});
						Roles.getMenuitemRole().setAriaLabelProperty(item.getElement(), UniTimeHeaderPanel.stripAccessKey(MESSAGES.opSortBy(name)));
						sortItems.addItem(item);
					}
				}
				MenuItem sortMenu = new MenuItem(MESSAGES.opSort(), sortItems);
				sortMenu.getElement().getStyle().setCursor(Cursor.POINTER);
				menu.addItem(sortMenu);

				MenuBar deptItems = new MenuBar(true);
				for (final DeptMode d: DeptMode.values()) {
					String name = (RoomCookie.getInstance().getDeptMode() == d.ordinal() ? MESSAGES.opUncheck(d.getName()) : MESSAGES.opCheck(d.getName()));
					MenuItem item = new MenuItem(name, true, new Command() {
						@Override
						public void execute() {
							popup.hide();
							RoomCookie.getInstance().setDeptMode(d.ordinal());
							iGlobalFeaturesTable.refreshTable();
							iDepartmentalFeaturesTable.refreshTable();
						}
					});
					Roles.getMenuitemRole().setAriaLabelProperty(item.getElement(), d.getName());
					deptItems.addItem(item);
				}
				MenuItem deptMenu = new MenuItem(MESSAGES.opDepartmentFormat(), deptItems);
				deptMenu.getElement().getStyle().setCursor(Cursor.POINTER);
				menu.addItem(deptMenu);

				if (iProperties.isCanExportRoomFeatures()) {
					menu.addSeparator();

					MenuItem exportPdf = new MenuItem(MESSAGES.opExportPDF(), true, new Command() {
						@Override
						public void execute() {
							popup.hide();
							export("roomfeatures.pdf");
						}
					});
					Roles.getMenuitemRole().setAriaLabelProperty(exportPdf.getElement(), MESSAGES.opExportPDF());
					menu.addItem(exportPdf);

					MenuItem exportCsv = new MenuItem(MESSAGES.opExportCSV(), true, new Command() {
						@Override
						public void execute() {
							popup.hide();
							export("roomfeatures.csv");
						}
					});
					Roles.getMenuitemRole().setAriaLabelProperty(exportCsv.getElement(), MESSAGES.opExportCSV());
					menu.addItem(exportCsv);
				}

				popup.add(menu);
				popup.showRelativeTo((UIObject)event.getSource());
				menu.focus();
			}
		};

		ClickHandler clickNew = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (iRoomFeatureEdit == null) return;
				Chip dept = iFilter.getChip("department");
				iRoomFeatureEdit.setFeature(null, dept == null ? null : dept.getValue());
				LoadingWidget.execute(iFilter.getElementsRequest(), new AsyncCallback<FilterRpcResponse>() {
					@Override
					public void onFailure(Throwable caught) {
						iFilter.setErrorHint(MESSAGES.failedToLoadRooms(caught.getMessage()));
						UniTimeNotifications.error(MESSAGES.failedToLoadRooms(caught.getMessage()), caught);
					}
					@Override
					public void onSuccess(FilterRpcResponse result) {
						iFilter.clearHint();
						if (result == null || result.getResults() == null || result.getResults().isEmpty()) {
							iFilter.setErrorHint(MESSAGES.errorNoRoomsMatchingFilter());
						} else {
							iRoomFeatureEdit.setRooms(result.getResults());
							iRoomFeatureEdit.show();
						}
					}
				}, MESSAGES.waitLoadingRooms());
			}
		};

		iRoomFeatureEdit = new RoomFeatureEdit(iMode) {
			@Override
			protected void onShow() {
				RoomHint.hideHint();
				iRootPanel.setWidget(iRoomFeatureEdit);
			}

			@Override
			protected void onHide(boolean refresh) {
				iRootPanel.setWidget(iFeaturesPanel);
				UniTimePageLabel.getInstance().setPageName(MESSAGES.pageRoomFeatures());
				if (refresh && (iFeaturesPanel.getRowFormatter().isVisible(iGlobalFeaturesRow) || iFeaturesPanel.getRowFormatter().isVisible(iDepartmentalFeaturesRow))) search();
			}
		};

		if (iMode.hasSessionSelection()) {
			iHeaderPanel = new UniTimeHeaderPanel(MESSAGES.sectFilter());
			iFeaturesPanel.addHeaderRow(iHeaderPanel);

			iSession = new AcademicSessionSelectionBox(iHistoryToken.getParameter("term")) {
				@Override
				protected void onInitializationSuccess(List<AcademicSession> sessions) {
					UniTimePageHeader.getInstance().getRight().setVisible(false);
					UniTimePageHeader.getInstance().getRight().setPreventDefault(true);
					setup(getAcademicSessionId());
				}

				@Override
				protected void onInitializationFailure(Throwable caught) {
					UniTimeNotifications.error(MESSAGES.failedLoadSessions(caught.getMessage()), caught);
				}
			};
			iSession.addAcademicSessionChangeHandler(new AcademicSessionChangeHandler() {
				@Override
				public void onAcademicSessionChange(AcademicSessionChangeEvent event) {
					setup(event.getNewAcademicSessionId());
				}
			});;
			iFeaturesPanel.addRow(MESSAGES.propAcademicSession(), (Widget)iSession);

			iFilter = new RoomFilterBox(iSession);
			iFeaturesPanel.addRow(MESSAGES.propRoomFilter(), iFilter);

			iHeaderPanel.addButton("search", MESSAGES.buttonSearch(), clickSearch);
			iHeaderPanel.addButton("more", MESSAGES.buttonMoreOperations(), clickMore);
			iHeaderPanel.addButton("new", MESSAGES.buttonAddNewRoom(), clickNew);
			iHeaderPanel.setEnabled("more", false);
			iHeaderPanel.setEnabled("new", false);
		} else {
			iFilterPanel = new HorizontalPanel();
			iFilterPanel.setSpacing(3);

			Label filterLabel = new Label(MESSAGES.propFilter());
			iFilterPanel.add(filterLabel);
			iFilterPanel.setCellVerticalAlignment(filterLabel, HasVerticalAlignment.ALIGN_MIDDLE);

			iSession = new Session();
			iFilter = new RoomFilterBox(iSession);
			iFilterPanel.add(iFilter);

			iSearch = new AriaButton(MESSAGES.buttonSearch());
			iSearch.addStyleName("unitime-NoPrint");
			iSearch.addClickHandler(clickSearch);
			iFilterPanel.add(iSearch);

			iMore = new AriaButton(MESSAGES.buttonMoreOperations());
			iMore.setEnabled(false);
			iMore.addStyleName("unitime-NoPrint");
			iMore.addClickHandler(clickMore);
			iFilterPanel.add(iMore);

			iNew = new AriaButton(MESSAGES.buttonAddNewRoomFeature());
			iNew.setEnabled(false);
			iNew.addStyleName("unitime-NoPrint");
			iNew.addClickHandler(clickNew);
			iFilterPanel.add(iNew);

			int filterRow = iFeaturesPanel.addRow(iFilterPanel);
			iFeaturesPanel.getCellFormatter().setHorizontalAlignment(filterRow, 0, HasHorizontalAlignment.ALIGN_CENTER);

			setup(null);
		}

		iGlobalFeaturesHeader = new UniTimeHeaderPanel(MESSAGES.headerGlobalRoomFeatures());
		iGlobalFeaturesRow = iFeaturesPanel.addHeaderRow(iGlobalFeaturesHeader);
		iGlobalFeaturesTable = new RoomFeaturesTable(true) {
			protected void doSort(RoomFeaturesColumn column) {
				super.doSort(column);
				iDepartmentalFeaturesTable.setSortBy(RoomCookie.getInstance().getRoomFeaturesSortBy());
			}
		};
		iFeaturesPanel.addRow(iGlobalFeaturesTable);
		iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow, false);
		iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow + 1, false);

		iDepartmentalFeaturesHeader = new UniTimeHeaderPanel(MESSAGES.headerDepartmentalRoomFeatures());
		iDepartmentalFeaturesRow = iFeaturesPanel.addHeaderRow(iDepartmentalFeaturesHeader);
		iDepartmentalFeaturesTable = new RoomFeaturesTable(false) {
			protected void doSort(RoomFeaturesColumn column) {
				super.doSort(column);
				iGlobalFeaturesTable.setSortBy(RoomCookie.getInstance().getRoomFeaturesSortBy());
			}
		};
		iFeaturesPanel.addRow(iDepartmentalFeaturesTable);
		iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow, false);
		iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow + 1, false);

		iRootPanel = new SimplePanel(iFeaturesPanel);
		iPanel.setWidget(iRootPanel);

		iGlobalFeaturesTable.addMouseClickListener(new MouseClickListener<FeatureInterface>() {
			@Override
			public void onMouseClick(final TableEvent<FeatureInterface> event) {
				FeatureInterface Feature = event.getData();
				if (Feature == null) return;
				if (Feature.canEdit() || Feature.canDelete()) {
					Chip dept = iFilter.getChip("department");
					iRoomFeatureEdit.setFeature(Feature, dept == null ? null : dept.getValue());
					LoadingWidget.execute(iFilter.getElementsRequest(), new AsyncCallback<FilterRpcResponse>() {
						@Override
						public void onFailure(Throwable caught) {
							iFilter.setErrorHint(MESSAGES.failedToLoadRooms(caught.getMessage()));
							UniTimeNotifications.error(MESSAGES.failedToLoadRooms(caught.getMessage()), caught);
						}
						@Override
						public void onSuccess(FilterRpcResponse result) {
							iFilter.clearHint();
							if (result == null || result.getResults() == null || result.getResults().isEmpty()) {
								iFilter.setErrorHint(MESSAGES.errorNoRoomsMatchingFilter());
							} else {
								iRoomFeatureEdit.setRooms(result.getResults());
								iRoomFeatureEdit.show();
							}
						}
					}, MESSAGES.waitLoadingRooms());
				}
			}
		});

		iDepartmentalFeaturesTable.addMouseClickListener(new MouseClickListener<FeatureInterface>() {
			@Override
			public void onMouseClick(final TableEvent<FeatureInterface> event) {
				FeatureInterface Feature = event.getData();
				if (Feature == null) return;
				if (Feature.canEdit() || Feature.canDelete()) {
					Chip dept = iFilter.getChip("department");
					iRoomFeatureEdit.setFeature(Feature, dept == null ? null : dept.getValue());
					LoadingWidget.execute(iFilter.getElementsRequest(), new AsyncCallback<FilterRpcResponse>() {
						@Override
						public void onFailure(Throwable caught) {
							iFilter.setErrorHint(MESSAGES.failedToLoadRooms(caught.getMessage()));
							UniTimeNotifications.error(MESSAGES.failedToLoadRooms(caught.getMessage()), caught);
						}
						@Override
						public void onSuccess(FilterRpcResponse result) {
							iFilter.clearHint();
							if (result == null || result.getResults() == null || result.getResults().isEmpty()) {
								iFilter.setErrorHint(MESSAGES.errorNoRoomsMatchingFilter());
							} else {
								iRoomFeatureEdit.setRooms(result.getResults());
								iRoomFeatureEdit.show();
							}
						}
					}, MESSAGES.waitLoadingRooms());
				}
			}
		});

		initWidget(iPanel);

		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				if (!iInitialized) return;
				iHistoryToken.reset(event.getValue());
				updateFilter(iFeaturesPanel.getRowFormatter().isVisible(iGlobalFeaturesRow) || iFeaturesPanel.getRowFormatter().isVisible(iDepartmentalFeaturesRow));
			}
		});
	}

	private boolean iInitialized = false;
	protected void setup(final Long sessionId) {
		LoadingWidget.getInstance().show(MESSAGES.waitLoadingPage());
		RPC.execute(new RoomPropertiesRequest(sessionId), new AsyncCallback<RoomPropertiesInterface>() {
			@Override
			public void onFailure(Throwable caught) {
				LoadingWidget.getInstance().hide();
				iFilter.setErrorHint(MESSAGES.failedToInitialize(caught.getMessage()));
				UniTimeNotifications.error(MESSAGES.failedToInitialize(caught.getMessage()), caught);
			}

			@Override
			public void onSuccess(RoomPropertiesInterface result) {
				LoadingWidget.getInstance().hide();
				iProperties = result;
				iRoomFeatureEdit.setProperties(iProperties);

				if (iSession instanceof Session)
					((Session)iSession).fireChange();

				boolean search = iDepartmentalFeaturesTable.getRowCount() > 1 || iGlobalFeaturesTable.getRowCount() > 1;

				if (iNew != null) iNew.setEnabled(iProperties.isCanAddDepartmentalRoomFeature() || iProperties.isCanAddGlobalRoomFeature());
				if (iHeaderPanel != null) iHeaderPanel.setEnabled("new", iProperties.isCanAddDepartmentalRoomFeature() || iProperties.isCanAddGlobalRoomFeature());

				if (sessionId != null && iSession instanceof AcademicSessionSelectionBox) {
					iHistoryToken.setParameter("term", ((AcademicSessionSelectionBox)iSession).getAcademicSessionAbbreviation());
					iHistoryToken.mark();
				}
				updateFilter(search);
				iInitialized = true;
			}
		});
	}

	protected void updateFilter(boolean search) {
		iFilter.setValue(iHistoryToken.getParameter("q"), true);
		if (iSession instanceof AcademicSessionSelectionBox && iHistoryToken.isChanged("term", ((AcademicSessionSelectionBox)iSession).getAcademicSessionAbbreviation()) && iHistoryToken.getParameter("term") != null)
			((AcademicSessionSelectionBox)iSession).selectSession(iHistoryToken.getParameter("term"), null);
		if (search)
			search();
	}

	protected void changeUrl() {
		iHistoryToken.reset(null);
		if (iSession instanceof AcademicSessionSelectionBox)
			iHistoryToken.setParameter("term", ((AcademicSessionSelectionBox)iSession).getAcademicSessionAbbreviation());
		iHistoryToken.setParameter("q", iFilter.getValue());
		iHistoryToken.mark();
		Client.fireGwtPageChanged(new Client.GwtPageChangeEvent());
	}

	protected void search() {
		if (iMore != null) iMore.setEnabled(false);
		if (iHeaderPanel != null) iHeaderPanel.setEnabled("more", false);
		iGlobalFeaturesTable.clearTable(1);
		iDepartmentalFeaturesTable.clearTable(1);
		iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow, false);
		iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow + 1, false);
		iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow, false);
		iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow + 1, false);
		SearchRoomFeaturesRequest request = new SearchRoomFeaturesRequest(iProperties.getAcademicSessionId());
		request.setFilter(iFilter.getElementsRequest());
		LoadingWidget.execute(request, new AsyncCallback<GwtRpcResponseList<FeatureInterface>>() {
			@Override
			public void onFailure(Throwable caught) {
				iFilter.setErrorHint(MESSAGES.failedToLoadRoomFeatures(caught.getMessage()));
				UniTimeNotifications.error(MESSAGES.failedToLoadRoomFeatures(caught.getMessage()), caught);
			}
			@Override
			public void onSuccess(GwtRpcResponseList<FeatureInterface> result) {
				iFilter.clearHint();
				if (result == null || result.isEmpty()) {
					iFilter.setErrorHint(MESSAGES.errorNoRoomFeatures());
				} else {
					Chip dept = iFilter.getChip("department");
					boolean skipDepartmental = false;
					DepartmentInterface department = null;
					if (dept != null) {
						for (ExamTypeInterface type: iProperties.getExamTypes())
							if (type.getReference().equals(dept.getValue())) {
								skipDepartmental = true;
								break;
							}
						for (DepartmentInterface d: iProperties.getDepartments())
							if (dept.getValue().equals(d.getDeptCode())) {
								department = d; break;
							}
					}
					for (FeatureInterface Feature: result) {
						if (Feature.isDepartmental()) {
							if (skipDepartmental) continue;
							if (department != null && !department.equals(Feature.getDepartment())) continue;
							if (dept == null && !Feature.hasRooms()) continue;
							iDepartmentalFeaturesTable.addFeature(Feature);
						} else {
							iGlobalFeaturesTable.addFeature(Feature);
						}
					}
					iDepartmentalFeaturesTable.sort();
					iGlobalFeaturesTable.sort();
				}
				if (iMore != null) iMore.setEnabled(iDepartmentalFeaturesTable.getRowCount() > 1 || iGlobalFeaturesTable.getRowCount() > 1);
				if (iHeaderPanel != null) iHeaderPanel.setEnabled("more", iDepartmentalFeaturesTable.getRowCount() > 1 || iGlobalFeaturesTable.getRowCount() > 1);
				iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow, iGlobalFeaturesTable.getRowCount() > 1);
				iFeaturesPanel.getRowFormatter().setVisible(iGlobalFeaturesRow + 1, iGlobalFeaturesTable.getRowCount() > 1);
				iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow, iDepartmentalFeaturesTable.getRowCount() > 1);
				iFeaturesPanel.getRowFormatter().setVisible(iDepartmentalFeaturesRow + 1, iDepartmentalFeaturesTable.getRowCount() > 1);
			}
		}, MESSAGES.waitLoadingRoomFeatures());
	}

	protected void export(String format) {
		RPC.execute(EncodeQueryRpcRequest.encode(query(format)), new AsyncCallback<EncodeQueryRpcResponse>() {
			@Override
			public void onFailure(Throwable caught) {
			}
			@Override
			public void onSuccess(EncodeQueryRpcResponse result) {
				ToolBox.open(GWT.getHostPageBaseURL() + "export?q=" + result.getQuery());
			}
		});
	}

	protected String query(String format) {
		RoomCookie cookie = RoomCookie.getInstance();
		String query = "output=" + format + "&sort=" + cookie.getRoomsSortBy() + (cookie.hasMode() ? "&mode=" + cookie.getMode() : "") + "&dm=" + cookie.getDeptMode();
		if (iProperties.getAcademicSessionId() != null)
			query += "&sid=" + iProperties.getAcademicSessionId();

		FilterRpcRequest rooms = iFilter.getElementsRequest();
		if (rooms.hasOptions()) {
			for (Map.Entry<String, Set<String>> option: rooms.getOptions().entrySet()) {
				for (String value: option.getValue()) {
					query += "&r:" + option.getKey() + "=" + URL.encodeQueryString(value);
				}
			}
		}

		if (rooms.getText() != null && !rooms.getText().isEmpty())
			query += "&r:text=" + URL.encodeQueryString(rooms.getText());

		return query;
	}

	private class Session implements AcademicSessionProvider {
		private List<AcademicSessionChangeHandler> iHandlers = new ArrayList<AcademicSessionProvider.AcademicSessionChangeHandler>();

		private Session() {
		}

		@Override
		public void selectSession(Long sessionId, AsyncCallback<Boolean> callback) {
			callback.onSuccess(false);
		}

		@Override
		public String getAcademicSessionName() {
			return iProperties == null ? null : iProperties.getAcademicSessionName();
		}

		@Override
		public Long getAcademicSessionId() {
			return iProperties == null ? null : iProperties.getAcademicSessionId();
		}

		@Override
		public void addAcademicSessionChangeHandler(AcademicSessionChangeHandler handler) {
			iHandlers.add(handler);
		}

		@Override
		public AcademicSessionInfo getAcademicSessionInfo() {
			return null;
		}

		protected void fireChange() {
			AcademicSessionProvider.AcademicSessionChangeEvent event = new AcademicSessionProvider.AcademicSessionChangeEvent() {
				@Override
				public Long getNewAcademicSessionId() {
					return iProperties == null ? null : iProperties.getAcademicSessionId();
				}
				@Override
				public Long getOldAcademicSessionId() {
					return null;
				}
				@Override
				public boolean isChanged() {
					return true;
				}
			};
			for (AcademicSessionChangeHandler h: iHandlers)
				h.onAcademicSessionChange(event);
		}
	}
}


text:
/**
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

For 1-byte character, the first bit is a 0, followed by its unicode code.
For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
This is how the UTF-8 encoding would work:

   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Given an array of integers representing the data, return whether it is a valid utf-8 encoding.

Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

Example 1:

data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Example 2:

data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
 * @param {number[]} data
 * @return {boolean}
 */
var validUtf8 = function(data) {
	var state = 0;
	for (var i in data) {
		var t = check(data[i]);
		if (t === -2) {
			return false;
		}
		if (state === 0 ||state > 0 && t === -1) {
			state += t;
		} else {
			return false;
		}
	}
	return state === 0;
};

function check(num) {
	if (num > 255) {
		return -2;
	}
	if (num >>> 7 === 0b0) {
		return 0;
	}
	if (num >>> 5 === 0b110) {
		return 1;
	}
	if (num >>> 4 === 0b1110) {
		return 2;
	}
	if (num >>> 3 === 0b11110) {
		return 3;
	}
	if (num >>> 6 === 0b10) {
		return -1;
	}
	return -2;
}

console.log(validUtf8([235, 140, 4]))
// console.log(validUtf8([197, 130, 1]))

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const filesystem = require('fs');
const os = require('os');
const path = require('path');
const sinon = require('sinon');
const editor = require('..');
const memFs = require('mem-fs');

describe('#copy()', () => {
  let store;
  let fs;

  beforeEach(() => {
    store = memFs.create();
    fs = editor.create(store);
  });

  it('copy file', () => {
    const filepath = path.join(__dirname, 'fixtures/file-a.txt');
    const initialContents = fs.read(filepath);
    const newPath = '/new/path/file.txt';
    fs.copy(filepath, newPath);
    expect(fs.read(newPath)).toBe(initialContents);
    expect(fs.store.get(newPath).state).toBe('modified');
  });

  it('can copy directory not commited to disk', () => {
    fs.write('/test/foo/file-a.txt', 'a');
    fs.write('/test/foo/file-b.txt', 'b');

    fs.copy('/test/foo/**', '/test/bar/');

    expect(fs.read('/test/bar/file-a.txt')).toBe('a');
    expect(fs.read('/test/bar/file-b.txt')).toBe('b');
  });

  it('throws when trying to copy from a non-existing file', () => {
    const filepath = path.join(__dirname, 'fixtures/does-not-exits');
    const newPath = '/new/path/file.txt';
    expect(fs.copy.bind(fs, filepath, newPath)).toThrow();
  });

  it('copy file and process contents', () => {
    const filepath = path.join(__dirname, 'fixtures/file-a.txt');
    const initialContents = fs.read(filepath);
    const contents = 'some processed contents';
    const newPath = '/new/path/file.txt';
    fs.copy(filepath, newPath, {
      process(contentsArg) {
        expect(contentsArg).toBeInstanceOf(Buffer);
        expect(contentsArg.toString()).toEqual(initialContents);
        return contents;
      }
    });
    expect(fs.read(newPath)).toBe(contents);
  });

  it('copy by directory', () => {
    fs.copy(path.join(__dirname, '/fixtures'), '/output');
    expect(fs.read('/output/file-a.txt')).toBe('foo\n');
    expect(fs.read('/output/nested/file.txt')).toBe('nested\n');
  });

  it('copy by globbing', () => {
    fs.copy(path.join(__dirname, '/fixtures/**'), '/output');
    expect(fs.read('/output/file-a.txt')).toBe('foo\n');
    expect(fs.read('/output/nested/file.txt')).toBe('nested\n');
  });

  it('copy by globbing multiple patterns', () => {
    fs.copy([path.join(__dirname, '/fixtures/**'), '!**/*tpl*'], '/output');
    expect(fs.read('/output/file-a.txt')).toBe('foo\n');
    expect(fs.read('/output/nested/file.txt')).toBe('nested\n');
    expect(fs.read.bind(fs, '/output/file-tpl.txt')).toThrow();
  });

  it('copy files by globbing and process contents', () => {
    const process = sinon.stub().returnsArg(0);
    fs.copy(path.join(__dirname, '/fixtures/**'), '/output', {process});
    sinon.assert.callCount(process, 7); // 5 total files under 'fixtures', not counting folders
    expect(fs.read('/output/file-a.txt')).toBe('foo\n');
    expect(fs.read('/output/nested/file.txt')).toBe('nested\n');
  });

  it('accepts directory name with "."', () => {
    fs.copy(path.join(__dirname, '/fixtures/**'), '/out.put');
    expect(fs.read('/out.put/file-a.txt')).toBe('foo\n');
    expect(fs.read('/out.put/nested/file.txt')).toBe('nested\n');
  });

  it('requires destination directory when globbing', () => {
    expect(
      fs.copy.bind(
        fs,
        path.join(__dirname, '/fixtures/**'),
        path.join(__dirname, '/fixtures/file-a.txt')
      )
    ).toThrow();
  });

  it('preserve permissions', done => {
    const filename = path.join(os.tmpdir(), 'perm.txt');
    const copyname = path.join(os.tmpdir(), 'copy-perm.txt');
    filesystem.writeFileSync(filename, 'foo', {mode: parseInt(733, 8)});

    fs.copy(filename, copyname);

    fs.commit(() => {
      const oldStat = filesystem.statSync(filename);
      const newStat = filesystem.statSync(copyname);
      expect(newStat.mode).toBe(oldStat.mode);
      done();
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="b74d8e82-03dc-4500-b4ee-9645edf07cd7" name="Default" comment="" />
    <ignored path="HTML5BoilerplaceAsghar.iws" />
    <ignored path=".idea/workspace.xml" />
    <file path="/config.ru" changelist="b74d8e82-03dc-4500-b4ee-9645edf07cd7" time="1366893734836" ignored="false" />
    <file path="$PROJECT_DIR$/../printed-book-examples/modular-backbone-asghar/config.ru" changelist="b74d8e82-03dc-4500-b4ee-9645edf07cd7" time="1366795350668" ignored="false" />
    <file path="$PROJECT_DIR$/../printed-book-examples/modular-backbone/config.ru" changelist="b74d8e82-03dc-4500-b4ee-9645edf07cd7" time="1366795761103" ignored="false" />
    <file path="/Dummy.txt" changelist="b74d8e82-03dc-4500-b4ee-9645edf07cd7" time="1366892311211" ignored="false" />
    <file path="$PROJECT_DIR$/../todobackbone/config.ru" changelist="b74d8e82-03dc-4500-b4ee-9645edf07cd7" time="1366893734836" ignored="false" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="HTML5BoilerplaceAsghar" />
  </component>
  <component name="FileEditorManager">
    <leaf />
  </component>
  <component name="FindManager">
    <FindUsagesManager>
      <setting name="OPEN_NEW_TAB" value="false" />
    </FindUsagesManager>
  </component>
  <component name="IdeDocumentHistory">
    <option name="changedFiles">
      <list>
        <option value="$PROJECT_DIR$/config.ru" />
      </list>
    </option>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="-8" />
    <option name="y" value="-8" />
    <option name="width" value="1378" />
    <option name="height" value="744" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectReloadState">
    <option name="STATE" value="0" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents ProjectPane="true" />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="HTML5BoilerplaceAsghar" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="options.splitter.main.proportions" value="0.3" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="options.lastSelected" value="project.propVCSSupport.Mappings" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$/../todobackbone" />
    <property name="FullScreen" value="false" />
    <property name="options.splitter.details.proportions" value="0.2" />
    <property name="options.searchVisible" value="true" />
  </component>
  <component name="RecentsManager">
    <key name="CopyFile.RECENT_KEYS">
      <recent name="F:\html5\HTML5BoilerplaceAsghar" />
      <recent name="F:\html5\HTML5BoilerplaceAsghar\js" />
    </key>
  </component>
  <component name="RunManager">
    <configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit">
      <option name="VMOptions" />
      <option name="arguments" />
      <option name="filePath" />
      <option name="scope" value="ALL" />
      <option name="testName" />
      <method />
    </configuration>
    <list size="0" />
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="b74d8e82-03dc-4500-b4ee-9645edf07cd7" name="Default" comment="" />
      <created>1366794495294</created>
      <updated>1366794495294</updated>
    </task>
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="-8" y="-8" width="1378" height="744" extended-state="0" />
    <editor active="false" />
    <layout>
      <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24943988" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
    <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
    <option name="CHECK_NEW_TODO" value="true" />
    <option name="myTodoPanelSettings">
      <value>
        <are-packages-shown value="false" />
        <are-modules-shown value="false" />
        <flatten-packages value="false" />
        <is-autoscroll-to-source value="false" />
      </value>
    </option>
    <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
    <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
    <option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
    <option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="false" />
    <option name="CHANGED_ON_SERVER_INTERVAL" value="60" />
    <option name="SHOW_ONLY_CHANGED_IN_SELECTION_DIFF" value="true" />
    <option name="CHECK_COMMIT_MESSAGE_SPELLING" value="true" />
    <option name="DEFAULT_PATCH_EXTENSION" value="patch" />
    <option name="SHORT_DIFF_HORISONTALLY" value="true" />
    <option name="SHORT_DIFF_EXTRA_LINES" value="2" />
    <option name="SOFT_WRAPS_IN_SHORT_DIFF" value="true" />
    <option name="INCLUDE_TEXT_INTO_PATCH" value="false" />
    <option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
    <option name="SHOW_FILE_HISTORY_DETAILS" value="true" />
    <option name="SHOW_VCS_ERROR_NOTIFICATIONS" value="true" />
    <option name="SHOW_DIRTY_RECURSIVELY" value="false" />
    <option name="LIMIT_HISTORY" value="true" />
    <option name="MAXIMUM_HISTORY_ROWS" value="1000" />
    <option name="UPDATE_FILTER_SCOPE_NAME" />
    <option name="USE_COMMIT_MESSAGE_MARGIN" value="false" />
    <option name="COMMIT_MESSAGE_MARGIN_SIZE" value="72" />
    <option name="WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN" value="false" />
    <option name="FORCE_NON_EMPTY_COMMENT" value="false" />
    <option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="false" />
    <option name="LAST_COMMIT_MESSAGE" />
    <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="false" />
    <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
    <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
    <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
    <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
    <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
    <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
    <option name="ACTIVE_VCS_NAME" />
    <option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
    <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
    <option name="UPDATE_FILTER_BY_SCOPE" value="false" />
    <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
    <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/CONTRIBUTING.md">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/config.ru">
      <provider selected="true" editor-type-id="text-editor">
        <state line="3" column="59" selection-start="98" selection-end="98" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/Gemfile">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/Gemfile.lock">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/deploy">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
  </component>
</project>


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Cvv.WebUtility.Expression
{
    class NullPrimitive : LiteralNode
    {
        public NullPrimitive(Token relatedToken)
            : base(relatedToken)
        {

        }

        public override object Execute(IContext context, Stream writer)
        {
            return null;
        }
    }
}


text:
package org.esupportail.cas.adaptors.esupotp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

import org.esupportail.cas.config.EsupOtpConfigurationProperties;
import org.json.JSONException;
import org.json.JSONObject;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AllArgsConstructor
public class EsupOtpService {

	EsupOtpConfigurationProperties esupOtpConfigurationProperties;

	public JSONObject verifyOtp(String uid, String otp) throws IOException {
		String url = esupOtpConfigurationProperties.getUrlApi() + "/protected/users/" + uid + "/" + otp + "/" + esupOtpConfigurationProperties.getApiPassword();
		URL obj = new URL(url);
		HttpURLConnection con = null;
		con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		log.info("Mfa-esupotp request send to [{}]", (String) url);
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		log.info("Connection success to [{}]", (String) url);

		return new JSONObject(response.toString());
	}

	public List<Map<String, String>> getTransports(List<EsupOtpMethod> methods) {
		List<Map<String, String>> transports = new ArrayList<>();
		//Map<Integer, Map> transports = new HashMap<>();
		Map <String, String> transport;

		for (EsupOtpMethod method : methods) {
			if (method.getActive() && method.getTransports().size() > 0) {
				for(String transportName : method.getTransports() ){
					transport = new HashMap<>();
					transport.put("method", method.getName());
					transport.put("transport", transportName);
					transports.add(transport);
				}
			}
		}
		log.info("Size [{}] [{}]",  + transports.size(), transports.toString());

		return transports;
	}

	public JSONObject getUserInfos(String uid) throws IOException, NoSuchAlgorithmException {
		String url = esupOtpConfigurationProperties.getUrlApi() + "/users/" + uid + "/" + getUserHash(uid);
		URL obj = new URL(url);
		HttpURLConnection con = null;
		con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("GET");
		log.info("mfa-esupotp request send to [{}]", url.toString());
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		log.debug("getUserInfos({}) : {}", uid, response.toString());

		return new JSONObject(response.toString());
	}

	public String getUserHash(String uid) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5Md = MessageDigest.getInstance("MD5");
		String md5 = (new HexBinaryAdapter()).marshal(md5Md.digest(esupOtpConfigurationProperties.getUsersSecret().getBytes()));
		md5 = md5.toLowerCase();
		String salt = md5 + getSalt(uid);
		MessageDigest sha256Md = MessageDigest.getInstance("SHA-256");
		String userHash = (new HexBinaryAdapter()).marshal(sha256Md.digest(salt.getBytes()));
		userHash = userHash.toLowerCase();
		return userHash;
	}

	public String getSalt(String uid) {
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		String salt = uid + day + hour;
		return salt;
	}

    public Boolean bypass(List<EsupOtpMethod> methods) throws JSONException, IOException {
        Boolean bypass = true;
        for (EsupOtpMethod method : methods) {
            if (method.getActive()) {
                bypass = false;
            }
        }
        return bypass;
    }

}


text:
package com.amazonaws.services.sagemaker.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum VariantStatus {

    Creating("Creating"),
    Updating("Updating"),
    Deleting("Deleting"),
    ActivatingTraffic("ActivatingTraffic"),
    Baking("Baking");

    private String value;

    private VariantStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return VariantStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static VariantStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (VariantStatus enumEntry : VariantStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
<?php
/**
 * Language - simple language handler.
 *
 * @author Bartek Kuśmierczuk - contact@qsma.pl - http://qsma.pl
 * @version 3.0
 */

namespace Core;

use Core\Error;

/**
 * Language class to load the requested language file.
 */
class Language
{
    /**
     * Variable holds array with language.
     *
     * @var array
     */
    private $array;

    /**
     * Load language function.
     *
     * @param string $name
     * @param string $code
     */
    public function load($name, $code = LANGUAGE_CODE)
    {
        /** lang file */
        $file = APPDIR."language/$code/$name.php";

        /** check if is readable */
        if (is_readable($file)) {
            /** require file */
            $this->array[$code] = include $file;
        } else {
            /** display error */
            echo Error::display("Could not load language file '$code/$name.php'");
            die;
        }
    }

    /**
     * Get element from language array by key.
     *
     * @param  string $value
     *
     * @return string
     */
    public function get($value, $code = LANGUAGE_CODE)
    {
        if (!empty($this->array[$code][$value])) {
            return $this->array[$code][$value];
        } elseif(!empty($this->array[LANGUAGE_CODE][$value])) {
            return $this->array[LANGUAGE_CODE][$value];
        } else {
            return $value;
        }
    }

    /**
     * Get lang for views.
     *
     * @param  string $value this is "word" value from language file
     * @param  string $name  name of file with language
     * @param  string $code  optional, language code
     *
     * @return string
     */
    public static function show($value, $name, $code = LANGUAGE_CODE)
    {
        /** lang file */
        $file = APPDIR."language/$code/$name.php";

        /** check if is readable */
        if (is_readable($file)) {
            /** require file */
            $array = include($file);
        } else {
            /** display error */
            echo Error::display("Could not load language file '$code/$name.php'");
            die;
        }

        if (!empty($array[$value])) {
            return $array[$value];
        } else {
            return $value;
        }
    }
}


text:
![Bowery](http://bowery-blog.s3.amazonaws.com/logo-256.png "Bowery")

Sample Node.js / Express app for use with Bowery Desktop version 3.

This is basic starter app, and can be extended easily with other Node.js packages or used as a base for custom code.


text:
package contnet

type ActionArgumentType uint8

const (
	action_argument_type_unknown ActionArgumentType = iota
	action_argument_type_integer
	action_argument_type_string
	action_argument_type_float
)

var ActionArgumentTypes = struct {
	Unknown ActionArgumentType
	Integer ActionArgumentType
	String  ActionArgumentType
	Float   ActionArgumentType
}{
	Unknown: action_argument_type_unknown,
	Integer: action_argument_type_integer,
	String:  action_argument_type_string,
	Float:   action_argument_type_float,
}

type ActionArgument struct {
	Name  string             `json:"name"`
	Type  ActionArgumentType `json:"type"`
	Value interface{}        `json:"value"`
}
type ActionArgumentFactory struct{}

func (factory ActionArgumentFactory) New(name string, argType ActionArgumentType, value interface{}) *ActionArgument {
	return &ActionArgument{
		Name:  name,
		Type:  argType,
		Value: value,
	}
}

func (arg *ActionArgument) GetValueInteger() int {
	if arg.Type == ActionArgumentTypes.Integer {
		return int(arg.Value.(int))
	} else {
		return 0
	}
}

func (arg *ActionArgument) Clone() *ActionArgument {
	return &ActionArgument{
		Name:  arg.Name,
		Type:  arg.Type,
		Value: arg.Value,
	}
}

type ActionArguments []*ActionArgument

func (args ActionArguments) Clone() ActionArguments {
	out := ActionArguments{}

	for i := 0; i < len(args); i++ {
		out = append(out, args[i].Clone())
	}

	return out
}

func (args ActionArguments) GetArgumentByName(name string) *ActionArgument {
	for i := 0; i < len(args); i++ {
		if args[i].Name == name {
			return args[i].Clone()
		}
	}
	return nil
}


text:
namespace Moonfish.Guerilla
{
    public interface IReadQueueable
    {
        void QueueReads(QueueableBinaryReader binaryReader);
    }
}


text:
package axis2.apache.org.xsd;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="webappFileNames" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "webappFileNames"
})
@XmlRootElement(name = "deleteAllWebApps")
public class DeleteAllWebApps {

    @XmlElement(nillable = true)
    protected List<String> webappFileNames;

    /**
     * Gets the value of the webappFileNames property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the webappFileNames property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getWebappFileNames().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link String }
     *
     *
     */
    public List<String> getWebappFileNames() {
        if (webappFileNames == null) {
            webappFileNames = new ArrayList<String>();
        }
        return this.webappFileNames;
    }

}


text:
title: Project Management (& GitHub) for C4P Participants
layout: page
concept: Best practices for collaborating through GitHub during the development workshop.
---

By: Simon Goring

*GitHub is a collaborative environment for sharing projects among participants.  It is designed for programmers and is based on git, a program to manage version control in program development.*

*While GitHub is often used for active development of computer programs, it can be used for a range of other uses, including data management, text development/paper writing, or, really, whatever you want.*

* TOC
{:toc}

## How to Get An Account

If you already have an account then you're set here.  Otherwise, setting up a GitHub account is fairly straightforward.  Go to [http://github.com]() and set up an account.  In general it's best to have a shorter account name.  Any project you set up in GitHub will have a URL that includes your account name, so the shorter (and more identifiable) the better.  I'd rather go to:

[https://github.com/abcd/123]() [not a real repository]

than

[https://github.com/somereallylongusernamethatsannoyingtotype/123]() [also not real]

Once you've got your username, then you need to join our Development Organization.

### Best Practices

While setting up a basic account is pretty easy, there are a few things you can do to really improve your account and to get more out of GitHub as a platform.  All of the following can be accessed from the "Edit Profile" button visible from your profile page.

1. **Edit your profile**: Adding a picture or avatar to your profile is helpful to other people.  When you start contributing to a project the avatar becomes associated with each change you make or issue you raise.  GitHub provides a default avatar, but using something that's personalized will help other people and give you higher visability.
Change your email settings: You may want to add an extra email address, make your email address private or change the things GitHub sends you.
2. **Add notifications**: When editing your profile click the "Notifications" link in the sidebar.  This enables you to receive (or not receive)  emails when things happen in repositories that you have contributed to. Adding notifications keeps you from getting "out of the loop" on a project when you're working on something else.
Enable the Two Factor Authentication: Through the "Security" link, this helps secure your account in the same way you might for gmail or other accounts, by sending a unique PIN to a mobile device.  This helps ensure your account is more difficult to hack.  Especially if you're using GitHub as a data/project backup you should enable this.

## How to Join a Team

At some point you will be joining one or more teams during this Development meeting.  We have created a GitHub Organization for the development meeting:

[https://github.com/cyber4paleo]()

It's possible for you to develop directly from your own account using a repository, but building as part of the organization lets you share credit, and, in the case that you are developing something using sensitive data, we have the ability to create Private repositories, although our strong preference is to use public repositories within the organization.

Once you've established your account send one of the Organization Administrators an email (currently: goring@wisc.edu) and we'll add you to the organization.  Once you are a member of the organization you will be able to see and create new repositories and make changes to them.  The current settings do not allow you to add new members.

## Creating a GitHub Workflow

The most important point here is to be conscious of the choices you make.  Not making a choice, and putting things off for later is a choice in itself and can affect your team and its future success.

### How to Create a Repository

Once you've become a member of an organization & met with your team, take the time to set up a repository.  Setting up a repository is fairly simple.  Navigate to the Organization's page (here: https://github.com/cyber4paleo) and click "New Repository".  From here you will be asked to provide a repository name, choose whether the repository is to be public or private, decide whether you want a README and add a license and/or gitignore.

### Best Practices

1. The repository name should be simple but descriptive.  The Description should add to this (and should be filled out).
2. The repository should be Public unless there is a specific reason it needs to be Private.
3. You should generate a README file by default.
4. You should add a .gitignore for the programming language you expect to use most in the project.
5. You should generate a license.  MIT is the most permissive and is my (SJG's) default.

Our Project Repository is:

Our description is:

Is your repository public or private?  Why?

Which `.gitignore` did you choose (if any)?

Which license did you choose?  Why?

## Get the Repository Onto Your Computer
Once you've created the repository you'll want to get it onto your computer.  To do this you can use the GitHub Desktop application [here] or use git from the command line [here] or a number of other applications.  You will be "cloning" the repository using whichever tool you choose.  GitHub provides an explanation of how to clone a repository from ither the command line or GitHub Desktop here [link].

## Write a Good README File

A good README file is important. There is even a school of thought called "README Driven Development".  Often times README files are nothing but the repository name, but the README is the first introduction most people will have to your repository, and so it's important to use it to showcase the project.  In README Driven Development the philosophy rests on the fact that READMEs are limited to a single "page", and so development stays focused on key design principles and tasks.

A good README provides a road map to the project, introduces & credits team members, provides examples of the project in action (for common uses), and provides links to outside resources.  If you develop a clean & clear README file you can use it yourself as a roadmap to project development.

The README on GitHub is written using Markdown.  There is good documentation on Markdown from GitHub [here and in more detail here], but what you really need to know is that it's basically a plain text file that you can edit with a basic text editor.  Some suggestions include Sublime Text, Notepad, vim, emacs or Notepad++.

### Best Practices

I like to think that the neotoma package for R has a pretty good README [link].  It could be improved, but it hits some of the key points:

1. Think about what you want to do first. Then write. It's okay to have a placeholder with something short, but a good README will reflect some thought by the team.
2. Credit your team members
3. Provide installation instructions (may be less important at first)
4. Link to help/issues/bug reporting
5. Provide contribution guidelines (or link to your Code of Conduct [link])

Which team member will be responsible for creating the README:

What are the main headings in your README?

## Organize Your Files

You've thought about the project a bit in developing your README file, now think about what development will look like and how you want to organize your resources.  You want your repository to be clean & organized, for yourself and for people who might want to contribute to your project.  There are lots of good explainers for how to structure a repository or project directory because it's really important for collaborative work.  Seriously.  Really.  I can't emphasize it enough.  Promote someone to be your Project Manager and make one of their duties file management.  It will be helpful.

The biggest problem is a failure to maintain any sort of document hierarchy, and the second is to make single, monolithic directories.

### Best Practices

Best practices may vary by programming language, here are some for Python [link], R [link], and Ruby [link]
Maintain a document that helps organize the project.  We talked earlier about the README, but for more complex analytic workflows something like an RMarkdown document, or IPython notebook might be more useful.  You could also use a Markdown document.  Where does this file go?  In docs?  In the main repository?

Briefly sketch your project directory structure:

## Decide How to Collaborate

Will you all be pushing to the same repository?  Will you be branching and making pull requests?  Will you be forking and making pull requests?  It's best to make these decisions as a team.

GitHub has excellent documentation for collaborating through forks [here, and in more detail here], and this is, in general, my preferred way of collaborating.  This document will lay out some more detailed information about how to actually accomplish the tasks programmatically, but in general there are two models:

### Fork + Pull

Usually the model with bigger projects. GitHub provides a more extensive guide on forking, I will briefly discuss this collaboration model though. An individual makes a copy of the parent repository within their own user account, so they might fork the project:theonion/fartscroll.js to happyuser/fartscroll.js (I'm implying that [http://github.com]() comes before the user/repository format).  There the user could make changes, and, if they felt that the changes were worth incorporating back into the main repository, then they could make a Pull Request.  The main point here is that the user makes changes locally in their own account and then the changes are considered by the owner of the parent repository before incorporation.  This allows an extra degree of project management since the administrator can potentially reject changes, ask for revisions, or decide the order in which changes will be incorporated.

### Shared Repository

Here everyone uses the same repository.  This is often the case with small teams.  You pull the most recent changes to your machine, edit, and then push back to the repository, immediately incorporating your changes to the parent repository.  The reason this doesn't make sense for larger projects is that you might have many users making simultaneous (and potentially conflicting) changes.  If you are managing the project with a small team, with good communication, this might be the easiest way to manage the project (it's not that much harder to do it the other way though!).
A subset of this model is the Branch + Pull.  This is one of the methods that GitHub is actively advocating [here], and is a good model for users to practice.

How will you collaborate?  Why?

## GitHub Basics
GitHub provides an excellent "Hello World" tutorial [here] that is worth working through if you haven't used GitHub or git before.  The following is just a brief overview of a git workflow:

### Terminology
When you work with a repository you will (in general)

1. Pull the version from a repository online to your computer
2. Make local changes
3. Commit the local changes
4. Push your local version back up to GitHub

#### The Pull

When you pull (using git pull from the command line), you are calling out to your GitHub repository and asking for the latest version of the repository.  This ensures you're editing the most recent version of the documents.

#### The Commit

Once you've pulled you can edit, using whatever tool you want to use.  Once you've made some changes you'll want to commit those changes.  This is your way of formalizing the changes you've made.  There is lots of advice on how to write a good commit message [link] and when to commit (early & often).  My general rule is to try to make "atomic" commits.  While you're working, if you have solved a problem, added a feature, or worked on something in particular, and you're done with it, then commit.

Especially if you're working with others, failing to commit regularly gets you into conflict quickly, and prevents people from (1) rolling back your changes in the event of an unintended change (2) incorporating your changes in the event of a conflict and  (3) understanding what you've done in a systematic way.

#### The Pull

It is always good practice to pull before you push, especially if you're working in a repository where multiple users are working simultaneously.  This lets you fix any conflicts on your end before you push them back up to the main branch.

#### The Push

Once your changes are commited & you've ensured that they don't overlap you can push up to the repository.  If you are working on a branch or on a fork of the main repository then this is followed by a Pull Request.


text:
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Collections.Generic;

namespace WindowsGlitchHarvester
{
    public class ProcessHijacker
    {

        //C# Signature for the FindWindow() API
        [DllImport("USER32.DLL")] // Let the computer know where the below function will be imported from (user32.dll)
        public static extern IntPtr FindWindow( // Create a function "template"
            string lpClassName, // The function has two arguments, lpClassName (=Window class name) and lpWindowName (=Window name)
            string lpWindowName // Example of FindWindow() call using the arguments -> FindWindow("WindowClass" <- this is the lpClassName type string, "WindowName" <- this is the lpWindowName type string);
        );

        //C# Signature for the WriteProcessMemory() API
        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(
            IntPtr hProcess,
            IntPtr lpBaseAddress,
            byte[] lpBuffer,
            UIntPtr nSize,
            out IntPtr lpNumberOfBytesWritten
        );

        //C# Signature for the OpenProcess() API
        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            Int32 bInheritHandle,
            UInt32 dwProcessId
        );

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

        //C# Signature for the GetWindowThreadProcessId() API
        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(
            IntPtr hWnd,
            out uint lpdwProcessId
        );

        //C# Signature for the ReadProcessMemory() API
        [DllImport("kernel32.dll", SetLastError = true)]
        static unsafe extern bool ReadProcessMemory(
         IntPtr hProcess,
         IntPtr lpBaseAddress,
         void* lpBuffer,
         int dwSize,
         out IntPtr lpNumberOfBytesRead
        );

        [DllImport("kernel32.dll")]
        public static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);

        [DllImport("kernel32.dll")]
        static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);

        // REQUIRED STRUCTS

        public struct MEMORY_BASIC_INFORMATION
        {
            public int BaseAddress;
            public int AllocationBase;
            public int AllocationProtect;
            public int RegionSize;
            public int State;
            public int Protect;
            public int lType;
        }

        public struct SYSTEM_INFO
        {
            public ushort processorArchitecture;
            ushort reserved;
            public uint pageSize;
            public IntPtr minimumApplicationAddress;
            public IntPtr maximumApplicationAddress;
            public IntPtr activeProcessorMask;
            public uint numberOfProcessors;
            public uint processorType;
            public uint allocationGranularity;
            public ushort processorLevel;
            public ushort processorRevision;
        }

        // REQUIRED CONSTS

        const int PROCESS_QUERY_INFORMATION = 0x0400;
        const int MEM_COMMIT = 0x00001000;
        const int PAGE_READWRITE = 0x04;
        const int PROCESS_WM_READ = 0x0010;
        const int PROCESS_ALL_ACCESS = 0x1F0FFF;
        const int PROCESS_VM_WRITE = 0x0020;
        const int PROCESS_VM_OPERATION = 0x0008;

        // Global variables (containers)
        UInt32 ProcID;
        IntPtr WindowHandle;
        IntPtr ProcessReadHandle;
        IntPtr ProcessWriteHandle;
        IntPtr bytesout; // If using ReadProcessMemory(), dump the successfully read bytes here.

        public ushort processorArchitecture;
        ushort reserved;
        public uint pageSize;
        public IntPtr minimumApplicationAddress;
        public IntPtr maximumApplicationAddress;
        public IntPtr activeProcessorMask;
        public uint numberOfProcessors;
        public uint processorType;
        public uint allocationGranularity;
        public ushort processorLevel;
        public ushort processorRevision;

        public long processSize;

		public bool Hooked;

        //Memory indexing
        long[] allMemoryChunkSizes;
		long[] allMemoryChunkAddresses;
		private string processName;

		// thx these for info
		// http://www.codeproject.com/Articles/716227/Csharp-How-to-Scan-a-Process-Memory
		// http://www.codeproject.com/Articles/670373/Csharp-Read-Write-another-Process-Memory

		public ProcessHijacker(string processName)
		{
			Hooked = HookToProcess(processName);
		}

        public void WriteBytes(byte[] byteArray, long address)
        {
			long _address = GetRealAddressFromVirtual(address);

			for (long i = _address; i < byteArray.Length + _address; i++)
                WriteProcessMemory(ProcessWriteHandle, (IntPtr)(_address + i) /*Target address*/, new byte[] { 0 } /*Byte array call*/, (UIntPtr)1 /*Byte array size*/, out bytesout);
        }

        public void WriteByte(byte byteValue, long address)
        {
			long _address = GetRealAddressFromVirtual(address);

			WriteProcessMemory(ProcessWriteHandle, (IntPtr)_address /*Target address*/, new byte[] { byteValue } /*Byte array call*/, (UIntPtr)1 /*Byte array size*/, out bytesout);
        }

        public long GetRealAddressFromVirtual(long virtualAddress)
        {
            long address = 0;
            long blockVirtualAddress = 0;

            for(int i = 0; i < allMemoryChunkAddresses.Length; i++)
            {

                if (virtualAddress < blockVirtualAddress + allMemoryChunkSizes[i])
                {
                    address = (virtualAddress - blockVirtualAddress) + allMemoryChunkAddresses[i];
                    break;
                }

                blockVirtualAddress += allMemoryChunkSizes[i];

            }

            return address;
        }

        public long? GetProcessSizeAndIndexChunks()
        {
            //returns memory size

            // getting minimum & maximum address

            SYSTEM_INFO sys_info = new SYSTEM_INFO();
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later
            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;

            // this will store any information we get from VirtualQueryEx()
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

            int fullMemSize = 0;

            var _allMemoryChunkSizes = new List<long>();
            var _allMemoryChunkAddresses = new List<long>();

            while (proc_min_address_l < proc_max_address_l)
            {
                // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                VirtualQueryEx(ProcessReadHandle, proc_min_address, out mem_basic_info, 28);

                // if this memory chunk is accessible
                if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                {
					_allMemoryChunkSizes.Add(mem_basic_info.RegionSize);
					_allMemoryChunkAddresses.Add(proc_min_address_l);

                    fullMemSize += mem_basic_info.RegionSize;
                }

                // move to the next memory chunk
                proc_min_address_l += mem_basic_info.RegionSize;
                proc_min_address = new IntPtr(proc_min_address_l);
            }

			if(fullMemSize == 0)
			{
				MessageBox.Show("The process refused being hooked");
				return null;
			}

			allMemoryChunkSizes = _allMemoryChunkSizes.ToArray();
			allMemoryChunkAddresses = _allMemoryChunkAddresses.ToArray();

			return fullMemSize;

        }

		public byte ReadByte(long address)
		{
			int bytesRead = 0;
			byte[] buffer = new byte[1];

			ReadProcessMemory((int)ProcessReadHandle, (int)address, buffer, buffer.Length, ref bytesRead);

			return buffer[0];
		}

		public byte[] ReadBytes(long address, long amount)
		{
			int bytesRead = 0;
			byte[] buffer = new byte[amount];

			ReadProcessMemory((int)ProcessReadHandle, (int)address, buffer, buffer.Length, ref bytesRead);

			return buffer;
		}

		/*
		public byte ReadByte(long address)
		{

			long _address = GetRealAddressFromVirtual(address);

			// getting minimum & maximum address

			SYSTEM_INFO sys_info = new SYSTEM_INFO();
			GetSystemInfo(out sys_info);

			IntPtr proc_min_address = sys_info.minimumApplicationAddress;
			IntPtr proc_max_address = sys_info.maximumApplicationAddress;

			// saving the values as long ints so I won't have to do a lot of casts later
			long proc_min_address_l = _address;
			long proc_max_address_l = _address + 1;

			// notepad better be runnin'
			//Process process = Process.GetProcessesByName("notepad")[0];

			// opening the process with desired access level
			//IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);

			//StreamWriter sw = new StreamWriter("dump.txt");

			// this will store any information we get from VirtualQueryEx()
			MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

			int bytesRead = 0;  // number of bytes read with ReadProcessMemory

			List<byte> outputBytes = new List<byte>();

			while (proc_min_address_l < proc_max_address_l)
			{
				// 28 = sizeof(MEMORY_BASIC_INFORMATION)
				VirtualQueryEx(ProcessReadHandle, proc_min_address, out mem_basic_info, 28);

				// if this memory chunk is accessible
				if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
				{

					byte[] buffer = new byte[mem_basic_info.RegionSize];

					// read everything in the buffer above
					ReadProcessMemory((int)ProcessReadHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);

					// then output this in the file
					//for (int i = 0; i < mem_basic_info.RegionSize; i++)
					//sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]);

					outputBytes.AddRange(buffer);
				}

				// move to the next memory chunk
				proc_min_address_l += mem_basic_info.RegionSize;
				proc_min_address = new IntPtr(proc_min_address_l);
			}

			return outputBytes[0];

		}

		public byte[] ReadBytes(long address, long amount)
		{

			long _address = GetRealAddressFromVirtual(address);

			// getting minimum & maximum address

			SYSTEM_INFO sys_info = new SYSTEM_INFO();
			GetSystemInfo(out sys_info);

			IntPtr proc_min_address = sys_info.minimumApplicationAddress;
			IntPtr proc_max_address = sys_info.maximumApplicationAddress;

			// saving the values as long ints so I won't have to do a lot of casts later
			long proc_min_address_l = _address;
			long proc_max_address_l = _address + amount;

			// notepad better be runnin'
			//Process process = Process.GetProcessesByName("notepad")[0];

			// opening the process with desired access level
			//IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);

			//StreamWriter sw = new StreamWriter("dump.txt");

			// this will store any information we get from VirtualQueryEx()
			MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

			int bytesRead = 0;  // number of bytes read with ReadProcessMemory

			List<byte> outputBytes = new List<byte>();

			while (proc_min_address_l < proc_max_address_l)
			{
				// 28 = sizeof(MEMORY_BASIC_INFORMATION)
				VirtualQueryEx(ProcessReadHandle, proc_min_address, out mem_basic_info, 28);

				// if this memory chunk is accessible
				if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
				{

					byte[] buffer = new byte[mem_basic_info.RegionSize];

					// read everything in the buffer above
					ReadProcessMemory((int)ProcessReadHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);

					// then output this in the file
					//for (int i = 0; i < mem_basic_info.RegionSize; i++)
					//sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]);

					outputBytes.AddRange(buffer);
				}

				// move to the next memory chunk
				proc_min_address_l += mem_basic_info.RegionSize;
				proc_min_address = new IntPtr(proc_min_address_l);
			}

			return outputBytes.ToArray();

		}

	*/

		public byte[] ReadAllData()
        {

            // getting minimum & maximum address

            SYSTEM_INFO sys_info = new SYSTEM_INFO();
            GetSystemInfo(out sys_info);

            IntPtr proc_min_address = sys_info.minimumApplicationAddress;
            IntPtr proc_max_address = sys_info.maximumApplicationAddress;

            // saving the values as long ints so I won't have to do a lot of casts later
            long proc_min_address_l = (long)proc_min_address;
            long proc_max_address_l = (long)proc_max_address;

            // notepad better be runnin'
            //Process process = Process.GetProcessesByName("notepad")[0];

            // opening the process with desired access level
            //IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);

            //StreamWriter sw = new StreamWriter("dump.txt");

            // this will store any information we get from VirtualQueryEx()
            MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION();

			int bytesRead = 0;  // number of bytes read with ReadProcessMemory

            List<byte> outputBytes = new List<byte>();

            while (proc_min_address_l < proc_max_address_l)
            {
                // 28 = sizeof(MEMORY_BASIC_INFORMATION)
                VirtualQueryEx(ProcessReadHandle, proc_min_address, out mem_basic_info, 28);

                // if this memory chunk is accessible
                if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT)
                {

                    byte[] buffer = new byte[mem_basic_info.RegionSize];

                    // read everything in the buffer above
                    ReadProcessMemory((int)ProcessReadHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead);

                    // then output this in the file
                    //for (int i = 0; i < mem_basic_info.RegionSize; i++)
                    //sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]);

                    outputBytes.AddRange(buffer);
                }

                // move to the next memory chunk
                proc_min_address_l += mem_basic_info.RegionSize;
                proc_min_address = new IntPtr(proc_min_address_l);
            }

            return outputBytes.ToArray();

        }

        public bool HookToWindow(string windowClass, string windowTitle)
        {
            //WindowHandle = FindWindow("WindowClass", "WindowTitle"); // Establish a Window Handle (hWnd)
            WindowHandle = FindWindow(windowClass, windowTitle); // Establish a Window Handle (hWnd)

            GetWindowThreadProcessId(WindowHandle, out ProcID); // Get the Process ID (PID) from the targeted window/window class
            ProcessReadHandle = OpenProcess(PROCESS_ALL_ACCESS, 1, ProcID); // Gain access to the process memory with OpenProcess() using Process ID as an entry

			var pSize = GetProcessSizeAndIndexChunks();

			if (pSize == null)
				return false;
			else
			{
				processSize = (long)pSize;
				return true;
			}
        }

        public bool HookToProcess(string _processName = null)
        {
			if(_processName!= null)
				processName = _processName;

			string[] processData = processName.Split(':');

			Process process = Process.GetProcessById(Convert.ToInt32(processData[1]));

            // opening the process with desired access level
            ProcessReadHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id);
            ProcessWriteHandle = OpenProcess(0x1F0FFF, false, process.Id);
			//ProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_ALL_ACCESS, true, process.Id);

			var pSize = GetProcessSizeAndIndexChunks();

			if(pSize == null)
				return false;
			else
			{
				processSize = (long)pSize;
				return true;
			}
        }

		public void refreshProcessSize()
		{
			HookToProcess();
		}
	}
}


text:
author: muyiwagbadegesin
comments: true
date: 2017-01-23 07:35:00+00:00
excerpt:
The property taxation system in Lagos was a manual and inefficient system
  with fragmented charges and multiple taxation. The Land Use Charge law was introduced
  in year 2000 to combine the 3 existing charges into just one charge called the Land
  Use Charge (LUC).

layout: post
link: https://mgblog477.wordpress.com/2017/01/23/2016417land-use-charge/
slug: 2016417land-use-charge
title: Developing a Property Assessment and Taxation System in Lagos
wordpress_id: 23
categories:
- Governance
- Projects
- Technology
tags:
- bola tinubu
- gis
- lagos
- land information system
- taxation
---

# Fragmented and leaky legacy systems

The property taxation system in Lagos was a manual and inefficient system with fragmented charges and multiple taxation. The Land Use Charge law was introduced in year 2000 to combine the 3 existing charges into just one charge called the Land Use Charge (LUC). The LUC law required that each property must be enumerated before bills could be issued to the property owner. Before introduction of LUC, each property was billed haphazardly and unpredictably for Ground Rent and Neighborhood Improvement Charge (collected by the state government) and Tenement Rate (collected by the local governments).  These charges were arbitrary and corrupt revenue administrators would often overcharge a helpless property owner to force them to pay bribes to bring down the exorbitant charge.  As can be seen in the table below, revenue due to the state were perennially low due to these fraudulent practices.

## Expected vs Actual Tenement Rate Collection in 2 Lagos Councils (Y2000)

# Introducing transparency

       [caption id="" align="alignnone" width="715.0"]![Sample property enumeration dataset for a typical property in Lagos](https://mgblog477.files.wordpress.com/2017/01/b9830-developing_property_assessment_taxation_system_lagos.png) Sample property enumeration dataset for a typical property in Lagos[/caption]

The LUC put an end to this by ensuring a transparent assessment process which enabled the property owner to independently verify what they were charged by doing the calculations themselves with the formulas encoded in the law.

The enumeration process required a visitation to the property to interview the owner and measure the size of the land parcel and the total size and condition of the building. These values were then plugged into a formula to calculate the annual LUC.  The enumeration process was aided by vectorized parcel maps developed from up-to-date satellite imagery. The parcel maps depict the individual property boundaries and building footprint.

       [caption id="" align="alignnone" width="412.0"]![A 200 sq.m field sheet showing uniquely  identified plots and buildings.](https://mgblog477.files.wordpress.com/2017/01/65e37-img.png) A 200 sq.m field sheet showing uniquely  identified plots and buildings.[/caption]

# Tools and methods

Property taxation is a well developed and automated in many municipalities worldwide with numerous off the shelf and custom softwares being used. The Lagos LUC system was the first automated system in Nigeria at the time.

1. Satellite imagery

2. ESRI ArcGIS software

3. Parcel maps segmented into field sheets

4. Enumeration forms

5. Measuring tape

6. MS Excel, MS Access Server

7. LUC Demand Notices

8. Courier service, delivery notes

# Beating expectations

The LUC system generated 300million Naira in the first year of my operation of the restructured system. The system was initially run by Reid-Crowther/LRC but failed due to high bills which did not take affordability into consideration. We adjusted the formula and were able to send out demand notices valued at 1 billion in year one with collections of 300 million without enforcement . The system now generates about 10 billion per annum.


text:
import React from "react";
import * as renderer from "react-test-renderer";
import { SearchInput } from "src/search-input/search-input";

jest.mock("src/search-input/clear-button");
jest.mock("src/search-input/hoverable-component");

describe("Search Input tests", () => {
  test("Renders the component as expected", () => {
    const spy = jest.fn();
    const component = renderer.create(
      <SearchInput
        width={200}
        height={50}
        placeholder={"test"}
        whenAvailable={spy}
      />
    );
    expect(component.toJSON()).toMatchSnapshot();
  });

  test("setInputRef correctly assigns ref", () => {
    const component = new SearchInput({
      width: 200,
      height: 50,
      placeholder: "test",
      whenAvailable: jest.fn()
    });
    const inputRefMock = "test";
    component.setInputRef(inputRefMock);
    expect(inputRefMock).toBe("test");
  });

  test("setInputRef correctly assigns ref", () => {
    const component = new SearchInput({
      width: 200,
      height: 50,
      placeholder: "test",
      whenAvailable: jest.fn()
    });
    const spy = {
      focus: jest.fn()
    };
    const inputRefMock = spy;
    component.setInputRef(inputRefMock);
    component.setFocus();
    expect(spy.focus).toHaveBeenCalledTimes(1);
  });

  test("clearText blanks the input value", () => {
    const component = new SearchInput({
      width: 200,
      height: 50,
      placeholder: "test",
      whenAvailable: jest.fn()
    });
    component.setState = jest.fn();
    component.clearText();
    expect(component.setState).toHaveBeenCalled();
  });

  test("onChangeText updates State with 0 length string - hides button", () => {
    const component = new SearchInput({
      width: 200,
      height: 50,
      placeholder: "test",
      whenAvailable: jest.fn()
    });
    const mockEvent = {
      target: {
        value: ""
      }
    };
    component.setState = jest.fn();
    component.onChangeText(mockEvent);
    expect(component.setState).toHaveBeenCalledWith({
      content: "",
      showButton: false
    });
  });

  test("onChangeText updates State with 0 length string - hides button", () => {
    const component = new SearchInput({
      width: 200,
      height: 50,
      placeholder: "test",
      whenAvailable: jest.fn()
    });
    const mockEvent = {
      target: {
        value: "TEST"
      }
    };
    component.setState = jest.fn();
    component.onChangeText(mockEvent);
    expect(component.setState).toHaveBeenCalledWith({
      content: "TEST",
      showButton: true
    });
  });
});


text:
var day = new Date();
var isitSept="No";
if (moment(day).format("MM")==9)
{
isitsept="Yes";
}

var idiot = document.getElementById("idiot");
idiot.innerHTML=isitSept;


text:
<p id="hamm_christopher" data-toggle="tooltip" title="">
    Christopher
    Hamm is a postdoc in the Department of Ecology and
    Evolutionary Biology at the University of Kansas. His research
    focuses on the evolution and ecology of insects (mostly
    butterflies). Chris earned his his PhD from Michigan State
    Universty in 2012 and his dog's name is Larry.


text:
// Basic libs, gulp and way to run shell commands
var gulp  = require('gulp');
var shell = require('gulp-shell');

// Runs our install script
gulp.task('goInstall', shell.task([
  './install.sh'
]));

// watch for go files in any folder in /src
gulp.task('default', ['goInstall'], function() {
    //a list of watchers, so it will watch all of the following files waiting for changes
    gulp.watch('src/**/*.go', ['goInstall']);
});

// Aliases for convenience
gulp.task('dev', ['default']);
gulp.task('watch', ['default']);


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/transport/shared_door.iff"
	result.attribute_template_id = -1
	result.stfName("item_n","transport_door")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
import React, { Component } from 'react';
import Tabs from './Tabs/Tabs';
import OutlineHandler from '../containers/Outline/OutlineHandler';

export default class Home extends Component {
  render() {
    return (
      <div>
        <Tabs />
        <OutlineHandler />
      </div>
    );
  }
}


text:
<polymer-element name="kumis-topics">

  <template>
    <app-globals id="globals"></app-globals>
    <core-ajax
        auto
        method="GET"
        url="{{topicsEndpoint}}"
        contentType="application/json"
        handleAs="json"
        response="{{response}}"></core-ajax>

      <template repeat="{{response}}">

          <button onclick='getKumisBrokerAddress("{{$.globals.zkaddress}}/t/{{}}")'>{{}}</button>

      </template>

  </template>

</polymer-element>


text:
      Name
      Type

      {{cfname}}
      {{cfval.type}}

          <button ng-if="!viewOnlyModal"
                  ng-click="editCharFilter(cfname, cfval)" type="button"
                  class="btn btn-default btn-xs">
             Edit
          </button>
          <button ng-if="!viewOnlyModal"
                  ng-click="deleteCharFilter(cfname)" type="button"
                  class="btn btn-default btn-xs">
             Delete
          </button>

    <tr ng-show="Utils.keys(indexMapping.analysis.char_filters).length < 1">
      None

        <button ng-if="!viewOnlyModal"
                ng-click="newCharFilter()" type="button"
                class="btn btn-sm btn-default pull-right">New Character Filter</button>