text:
package com.hotf.client.presenter;

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

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.hotf.client.ClientFactory;
import com.hotf.client.GameController;
import com.hotf.client.HotfRulesEngine;
import com.hotf.client.ImageUtils;
import com.hotf.client.action.result.AccountResult;
import com.hotf.client.action.result.CharacterResult;
import com.hotf.client.action.result.GameResult;
import com.hotf.client.action.result.GameWeaponResult;
import com.hotf.client.action.result.PlaceResult;
import com.hotf.client.action.result.PostResult;
import com.hotf.client.event.AddToNextPostEvent;
import com.hotf.client.event.AddToNextPostEventHandler;
import com.hotf.client.event.ChangeAccountEvent;
import com.hotf.client.event.ChangeAccountEventHandler;
import com.hotf.client.event.ChangeCharacterEvent;
import com.hotf.client.event.ChangeCharacterEventHandler;
import com.hotf.client.event.ChangeGameEvent;
import com.hotf.client.event.ChangeGameEventHandler;
import com.hotf.client.event.ChangeMarkerEvent;
import com.hotf.client.event.ChangePlaceEvent;
import com.hotf.client.event.ChangePlaceEventHandler;
import com.hotf.client.event.ChangePostEvent;
import com.hotf.client.event.ChangePostEventHandler;
import com.hotf.client.event.LoadOtherCharactersEvent;
import com.hotf.client.event.LoadOtherCharactersEventHandler;
import com.hotf.client.event.LoadPostsEvent;
import com.hotf.client.event.LoadPostsEventHandler;
import com.hotf.client.event.MessageEvent;
import com.hotf.client.event.MessageEvent.Level;
import com.hotf.client.event.PlayEvent;
import com.hotf.client.event.PlayEventHandler;
import com.hotf.client.event.SelectCharacterEvent;
import com.hotf.client.event.SelectCharacterEventHandler;
import com.hotf.client.event.SelectPlaceEvent;
import com.hotf.client.event.SelectPlaceEventHandler;
import com.hotf.client.presenter.CharacterEditActivity.CharacterEditPlace;
import com.hotf.client.presenter.CharacterEditActivity.CharacterEditPlace.CreateOrEdit;
import com.hotf.client.presenter.CharacterViewActivity.CharacterViewPlace;
import com.hotf.client.presenter.GameViewActivity.GameViewPlace;
import com.hotf.client.presenter.PlaceEditActivity.PlaceEditPlace;
import com.hotf.client.presenter.PlaceViewActivity.PlaceViewPlace;
import com.hotf.client.view.PlayView;
import com.hotf.client.view.control.CharacterOracle.CharacterSuggestion;
import com.hotf.client.view.control.LocationOracle.LocationSuggestion;

/**
 * PlayPresenter.
 * The Presenter for PlayView's.
 *
 * @author Jeff Gager
 */
public class PlayActivity extends AbstractActivity implements PlayView.Presenter, LoadPostsEventHandler, LoadOtherCharactersEventHandler, ChangePostEventHandler, ChangeCharacterEventHandler, ChangePlaceEventHandler, PlayEventHandler, SelectCharacterEventHandler, SelectPlaceEventHandler, ChangeAccountEventHandler, ChangeGameEventHandler, AddToNextPostEventHandler {

	private ClientFactory clientFactory;

	/**
	 * Constructor.
	 *
	 * @param clientFactory ClientFactory
	 */
	public PlayActivity(final ClientFactory clientFactory) {

		this.clientFactory = clientFactory;

		clientFactory.getEventBus().addHandler(PlayEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(ChangeAccountEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(ChangeGameEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(ChangeCharacterEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(ChangePlaceEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(ChangePostEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(SelectPlaceEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(SelectCharacterEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(LoadOtherCharactersEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(LoadPostsEvent.TYPE, this);
		clientFactory.getEventBus().addHandler(AddToNextPostEvent.TYPE, this);

		final PlayView postListView = clientFactory.getPostListView();
		postListView.getLocationSelection().addSelectionHandler(new SelectionHandler<Suggestion>() {
			@Override
			public void onSelection(SelectionEvent<Suggestion> event) {
				Suggestion suggestion = event.getSelectedItem();
				if (suggestion instanceof LocationSuggestion) {
					LocationSuggestion locationSuggestion = (LocationSuggestion)suggestion;
					playingCharacter.setLocationId(locationSuggestion.getLocation().getId());
					clientFactory.getGameController().saveCharacter(playingCharacter);
					clientFactory.getEventBus().fireEvent(new SelectPlaceEvent(locationSuggestion.getLocation()));
				}
			}
		});
		postListView.getCharacterSelection().addSelectionHandler(new SelectionHandler<Suggestion>() {
			@Override
			public void onSelection(SelectionEvent<Suggestion> event) {
				Suggestion suggestion = event.getSelectedItem();
				if (suggestion instanceof CharacterSuggestion) {
					CharacterSuggestion characterSuggestion = (CharacterSuggestion)suggestion;
					clientFactory.getEventBus().fireEvent(new SelectCharacterEvent(characterSuggestion.getCharacter()));
					String newlocid = characterSuggestion.getCharacter().getLocationId();
					if (!selectedCharacter.getLocationId().equals(newlocid)) {
						clientFactory.getGameController().loadLocation(newlocid);
					}
				}
			}
		});

		postListView.clearPlaceMarker();

	}

	@Override
	public void weaponChange() {
		postingMessage();
		setAttackTypes();
	}

	@Override
	public void privateFieldChange() {
		postingMessage();
	}

	@Override
	public void importantFieldChange() {
		postingMessage();
	}

	private AcceptsOneWidget container;

	@Override
	public void start(AcceptsOneWidget container, EventBus eventBus) {

		this.container = container;

		PlayView postListView = clientFactory.getPostListView();
		postListView.setPresenter(this);
		postListView.setImportantPostValue(false);
		postListView.setPrivatePostValue(false);

		clientFactory.getGameController().play(clientFactory.getAccount().getPlayingCharacterId());

	}

	@Override
	public void onStop() {
		container = null;
	}

	@Override
	public void onPlay(PlayEvent event) {

		game = event.getGame();
		playingCharacter = event.getCharacter();
		selectedCharacter = event.getCharacter();
		playingLocation = event.getLocation();
		selectedLocation = event.getLocation();

		if (container == null) {
			return;
		}

		PlayView postListView = clientFactory.getPostListView();
		postListView.getLocationSelectionField().setText(playingLocation.getName());
		postListView.getCharacterSelectionField().setText(playingCharacter.getName());
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		sb.appendHtmlConstant("
");
		sb.appendEscaped(playingLocation.getName());
		sb.appendHtmlConstant("
");
		postListView.getMapNameField().setHTML(sb.toSafeHtml());
		postListView.getGMCommandsHidden().setVisible(game.getUpdatePermission() && "GM".equals(selectedCharacter.getCharacterType()));

		initMap();
		initCharacter();
		container.setWidget(postListView);
		postingMessage();

	}

	private void postingMessage() {
		if (container == null || game == null || playingCharacter == null || playingLocation == null) {
			return;
		}
		StringBuffer sb = new StringBuffer();
		PlayView postListView = clientFactory.getPostListView();
		sb.append("Posting as ");
		postListView.getPrivateFieldEnabled().setEnabled(playingLocation.getType() == null);
		sb.append(playingCharacter.getName());
		Boolean isPrivatePost = postListView.getPrivatePostValue();
		if (isPrivatePost != null && isPrivatePost) {
			if (selectedCharacter != null && !selectedCharacter.getId().equals(playingCharacter.getId())) {
				sb.append(" to " + selectedCharacter.getName() + " only");
			} else {
				sb.append(" to the Game Master only");
			}
		}
		if (account != null && playingLocation != null && !account.getHomeLocationId().equals(playingLocation.getId())) {
			if (selectedLocation != null) {
				if (playingCharacter.getCharacterType().equals("GM")) {
					sb.append(" in " + selectedLocation.getName());
				} else {
					sb.append(" in " + playingLocation.getName());
				}
			}
		}
		if (selectedLocation != null && account != null && !selectedLocation.getId().equals(account.getHomeLocationId())) {
			sb.append(" at " + game.getTitle());
		}
		String status = playingCharacter.getStatus();
		sb.append(" Status is " + (status == null || status.length() <= 0 ? "Ok" : status));
		Boolean isImportantPost = postListView.getImportantPostValue();
		if (isImportantPost != null && isImportantPost) {
			sb.append(" (Important)");
		}
		clientFactory.getEventBus().fireEvent(new MessageEvent(Level.PAGE, sb.toString()));
	}

	private boolean importantOnly;

	@Override
	public void getMorePosts() {

		//request more posts
		clientFactory.getGameController().getMorePosts(importantOnly);

	}

	private List<PostResult> posts;

	@Override
	public void onLoadPosts(LoadPostsEvent event) {

		if (container == null) {
			return;
		}

		//important only
		importantOnly = event.isImportant();

		//get view
		PlayView postListView = clientFactory.getPostListView();

		//get the posts and stop if there are no posts to load
		posts = event.getPosts();

		//clear existing posts if this is a refresh event
		if (event.isRefresh()) {
			postListView.setPosts(posts);
		} else {
			postListView.setMorePosts(posts);
		}

		//show or hide next rows panel
		int fetchRows = account != null ? account.getFetchRows(): 20;
		boolean morerows = posts.size() >= fetchRows;
		postListView.getGetMorePostsLink().setVisible(morerows);
		postListView.getNoMorePostsField().setVisible(!morerows);

		updateMarkers(event.isRefresh());

		init();
		posted = false;

	}

	private void updateMarkers(boolean refresh) {
		final PlayView playView = clientFactory.getPostListView();
		if (refresh) {
			playView.clearPostMarkers();
		}
		if (posts == null) {
			return;
		}
		List<String> markers = new ArrayList<String>();
		for (PostResult p : posts) {
			String cid = p.getCharacterId();
			if (p.getMarkerX() + p.getMarkerY() >= 0 &&
				!markers.contains(cid) &&
				p.getLocationId().equals(selectedLocation.getId())) {
				playView.addPostMarker(p.getCharacterName(), p.getMarkerX(), p.getMarkerY());
				markers.add(cid);
			} else if (p.getMarkerX() == -99 && p.getMarkerY() == -99) {
				markers.add(cid);
			}
		}
	}

	@Override
	public void selectCharacter(CharacterResult character) {
		clientFactory.getEventBus().fireEvent(new SelectCharacterEvent(character));
	}

	@Override
	public void clearSelection() {
		clientFactory.getEventBus().fireEvent(new SelectCharacterEvent(playingCharacter));
	}

	@Override
	public void onLoadOtherCharacters(LoadOtherCharactersEvent event) {

		if (container == null) {
			return;
		}

		PlayView playView = clientFactory.getPostListView();
		playView.clearTokens();

		for (CharacterResult c : event.getCharacters()) {
			if (c.getUpdatePermission() || !c.getTokenHidden()) {
				if (!c.getId().equals(game.getGameMasterCharacterId())) {
					playView.addToken(c);
				}
			}
		}
		updateMarkers(true);
		updateTargets();

		HotfRulesEngine re = clientFactory.getRulesEngine();
		playView.setActions(re.getCharacterActions(event.getCharacters()));

	}

	private void updateTargets() {
		GameController gc = clientFactory.getGameController();
		CharacterResult ltc = gc.getCharacterById(playingCharacter.getLeftTargetCharacterId());
		CharacterResult rtc = gc.getCharacterById(playingCharacter.getRightTargetCharacterId());
		PlayView postListView = clientFactory.getPostListView();
		postListView.setLeftTargetCharacterName(ltc != null ? ltc.getName() : "No Target Selected");
		postListView.setRightTargetCharacterName(rtc != null ? rtc.getName() : "No Target Selected");
		postListView.setLeftTargetArea(playingCharacter.getLeftTargetArea());
		postListView.setRightTargetArea(playingCharacter.getRightTargetArea());
	}

	protected int stringToInteger(String s) {
		if (s == null) {
			return 0;
		}
		try {
			return Integer.valueOf(s);
		} catch (NumberFormatException e) {
			return 0;
		}
	}

	private AccountResult account;

	@Override
	public void onChange(ChangeAccountEvent event) {

		if (container == null) {
			return;
		}

		account = event.getAccount();
		if (account == null) {
			return;
		}
		PlayView postListView = clientFactory.getPostListView();
		postListView.getPortraitHidden().setVisible(event.getAccount().getShowPortraits());
		postListView.setShowPortraits(account.getShowPortraits());
		postListView.redoList();
	}

	@Override
	public void onChange(ChangePostEvent event) {
		PlayView postListView = clientFactory.getPostListView();
		postListView.setPost(event.getPost());
	}

	@Override
	public void onChange(ChangeGameEvent event) {

		GameResult gameresult = event.getGame();
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		sb.appendHtmlConstant("
");
		sb.appendEscaped(gameresult.getTitle());
		sb.appendHtmlConstant("
");
		PlayView postListView = clientFactory.getPostListView();
		postListView.getGMCommandsHidden().setVisible(gameresult.getUpdatePermission() && "GM".equals(selectedCharacter.getCharacterType()));

	}

	@Override
	public void editPost(PostResult post) {
		new PostEditorPresenter(game, post, clientFactory);
	}

	@Override
	public void markImportant(PostResult post) {
		clientFactory.getGameController().markImportantPost(post, clientFactory.getAccount().getPlayingCharacterId());
	}

	@Override
	public void onChange(ChangeCharacterEvent event) {

		PlayView postListView = clientFactory.getPostListView();
		//update playing character (if that's the character that changed
		CharacterResult character = event.getCharacter();
		if (playingCharacter != null && playingCharacter.getId() != null && playingCharacter.getId().equals(character.getId())) {
			playingCharacter = event.getCharacter();
			postListView.getCharacterSelectionField().setText(event.getCharacter().getName());
			postingMessage();
			initCharacter();
		}

		//update selected character
		if (selectedCharacter != null && character.getId() != null && character.getId().equals(selectedCharacter.getId())) {
			if (moving != null && moving) {
				clientFactory.getEventBus().fireEvent(new MessageEvent(Level.INFO, "Moved - " + character.getLabel()));
				moving = null;
			}
			if (hiding != null) {
				String hc = hiding ? "Hidden - " : "Revealed - ";
				clientFactory.getEventBus().fireEvent(new MessageEvent(Level.INFO, hc + character.getLabel()));
				hiding = null;
			}
			if (event.getCharacter().getId().equals(selectedCharacter.getId())) {
				selectedCharacter = event.getCharacter();
			}
			postListView.scroll(selectedCharacter.getTokenX().intValue(), selectedCharacter.getTokenY().intValue());
			postingMessage();
			initMap();
		}

		HotfRulesEngine re = clientFactory.getRulesEngine();
		GameController gc = clientFactory.getGameController();
		postListView.setActions(re.getCharacterActions(gc.getOtherCharacters()));

		postListView.addToken(character);

	}

	@Override
	public void onChange(ChangePlaceEvent event) {

		//update playing location (if that's the character that changed
		PlaceResult location = event.getPlace();
		if (playingLocation != null && playingLocation.getId() != null && playingLocation.getId().equals(location.getId())) {
			playingLocation = location;
			initMap();
			postingMessage();
		}
		if (selectedLocation != null && selectedLocation.getId() != null && selectedLocation.getId().equals(location.getId())) {
			selectedLocation = location;
			initMap();
			postingMessage();
			PlayView postListView = clientFactory.getPostListView();
			postListView.getLocationSelectionField().setText(location.getName());
			SafeHtmlBuilder sb = new SafeHtmlBuilder();
			sb.appendHtmlConstant("
");
			sb.appendEscaped(playingLocation.getName());
			sb.appendHtmlConstant("
");
			postListView.getMapNameField().setHTML(sb.toSafeHtml());
		}

	}

	private int markerX = -50;
	private int markerY = -50;

	@Override
	public void mapClick(int x, int y) {

		markerX = x;
		markerY = y;
		PlayView postListView = clientFactory.getPostListView();
		int range = 0;
		if (!"GM".equals(playingCharacter.getCharacterType())) {
			range = ImageUtils.get().distance(
					playingCharacter.getTokenX().intValue(), playingCharacter.getTokenY().intValue(),
					markerX, markerY);
		} else if (!playingCharacter.getId().equals(selectedCharacter.getId())) {
			range = ImageUtils.get().distance(
					selectedCharacter.getTokenX().intValue(), selectedCharacter.getTokenY().intValue(),
					markerX, markerY);
		}
		postListView.setPlaceMarker(markerX, markerY, range);
		clientFactory.getEventBus().fireEvent(new ChangeMarkerEvent(markerX, markerY));

		if (markerX + markerY > 0.0D) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.INFO, "Save Post to place a marker at this point. Click on the marker and Save Post again to remove it."));
			clientFactory.getEventBus().fireEvent(new ChangeMarkerEvent(markerX, markerY));
		}
	}

	public void clearedPlaceMarker() {
		markerX = -50;
		markerY = -50;
	}

	@Override
	public void clearedPostMarker() {
		markerX = -99;
		markerY = -99;
	}

	private CharacterResult playingCharacter;
	private PlaceResult playingLocation;
	private GameResult game;

	private void initMap() {

		PlayView postListView = clientFactory.getPostListView();
		postListView.setMapUrl(ImageUtils.get().getMapOverlayUrl(selectedLocation));
		postListView.getPlaceDescriptionField().setHTML(selectedLocation.getDescription());
		updateMarkers(true);
		if (selectedCharacter != null) {
			postListView.scroll(selectedCharacter.getTokenX().intValue(), selectedCharacter.getTokenY().intValue());
		}
		postListView.getGameNameField().setText(game.getTitle());

	}

	private void initCharacter() {
		PlayView postListView = clientFactory.getPostListView();
		postListView.getPortraitImage().setUrl(ImageUtils.get().getPortraitUrl(playingCharacter));
		List<GameWeaponResult> cw = new ArrayList<GameWeaponResult>();
		int leftidx = 0;
		int rightidx = 0;
		for (GameWeaponResult w : game.getWeapons()) {
			if (playingCharacter.getWeapons().contains(w.getName())) {
				cw.add(w);
				if (playingCharacter.getLeftHand().equals(w.getName())) {
					leftidx = cw.size() - 1;
				}
				if (playingCharacter.getRightHand().equals(w.getName())) {
					rightidx = cw.size() - 1;
				}
			}
		}
		postListView.setWeaponList(cw, leftidx, rightidx);

		setAttackTypes();
		postListView.setRss(playingCharacter.getName(), playingCharacter.getId());
		updateTargets();
	}

	private void setAttackTypes() {
		PlayView postListView = clientFactory.getPostListView();
		List<String> sl = new ArrayList<String>();
		GameWeaponResult w = clientFactory.getGameController().getWeapon(playingCharacter.getLeftHand());
		if (w.getDefence() != null) {
			sl.add("Defend");
		}
		if (w.getMinRange() != null && w.getMaxRange() != null) {
			sl.add("Swing");
			sl.add("Thrust");
		}
		if (w.getShotMinRange() != null && w.getShotMaxRange() != null) {
			sl.add("Shoot");
		}
		postListView.setLeftStrikeList(sl, Math.max(sl.indexOf(playingCharacter.getLeftTargetStrike()), 0));
		if (!sl.contains(playingCharacter.getLeftTargetStrike())) {
			playingCharacter.setLeftTargetStrike(sl.get(0));
		}

		sl.clear();
		w = clientFactory.getGameController().getWeapon(playingCharacter.getRightHand());
		if (w.getDefence() != null) {
			sl.add("Defend");
		}
		if (w.getMinRange() != null && w.getMaxRange() != null) {
			sl.add("Swing");
			sl.add("Thrust");
		}
		if (w.getShotMinRange() != null && w.getShotMaxRange() != null) {
			sl.add("Shoot");
		}
		postListView.setRightStrikeList(sl, Math.max(sl.indexOf(playingCharacter.getRightTargetStrike()), 0));
		if (!sl.contains(playingCharacter.getRightTargetStrike())) {
			playingCharacter.setRightTargetStrike(sl.get(0));
		}

	}

	public void init() {

		final PlayView postListView = clientFactory.getPostListView();
		postListView.setImportantPostValue(false);
		postListView.setPrivatePostValue(false);
		postListView.getPostField().setText(" ");
		markerX = -50;
		markerY = -50;

		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				postListView.getPostFocus().setFocus(true);
			}
		});

	}

	private CharacterResult selectedCharacter;

	@Override
	public void onSelectCharacter(SelectCharacterEvent event) {
		selectedCharacter = event.getCharacter();
		PlayView postListView = clientFactory.getPostListView();
		postListView.scroll(selectedCharacter.getTokenX().intValue(), selectedCharacter.getTokenY().intValue());
		postingMessage();
		postListView.getCharacterSelectionField().setText(selectedCharacter.getName());
	}

	private PlaceResult selectedLocation;

	@Override
	public void onSelectPlace(SelectPlaceEvent event) {
		PlaceResult l = event.getPlace();
		//update selected Location
		if (selectedLocation == null || !selectedLocation.getId().equals(l.getId())) {
			selectedLocation = l;
		}
		initMap();
		postingMessage();
		PlayView postListView = clientFactory.getPostListView();
		postListView.getLocationSelectionField().setText(selectedLocation.getName());
	}

	@Override
	public void openCharacter() {
		if (selectedCharacter.getUpdatePermission()) {
			clientFactory.getPlaceController().goTo(new CharacterEditPlace(CreateOrEdit.EditCharacter, selectedCharacter.getId()));
		} else {
			clientFactory.getPlaceController().goTo(new CharacterViewPlace(selectedCharacter.getId()));
		}
	}

	@Override
	public void openGame() {
		clientFactory.getPlaceController().goTo(new GameViewPlace(game.getId()));
	}

	@Override
	public void refresh() {

		clientFactory.getPlaceController().goTo(new PlayPlace());

		//request latest posts from server
		clientFactory.getGameController().getLatestPosts();

	}

	@Override
	public void important() {

		clientFactory.getPlaceController().goTo(new PlayPlace());

		//request latest important posts from server
		clientFactory.getGameController().getLatestImportantPosts();

	}

	@Override
	public void createMap() {
		clientFactory.getPlaceController().goTo(new PlaceEditPlace(PlaceEditPlace.CreateOrEdit.CreatePlace, game.getId(), false));
	}

	@Override
	public void openMap() {
		clientFactory.getPlaceController().goTo(new PlaceViewPlace(selectedLocation.getId()));
	}

	@Override
	public void editCharacter() {
		if (!selectedCharacter.getUpdatePermission()) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "You cannot edit this character"));
		} else {
			clientFactory.getPlaceController().goTo(new CharacterEditPlace(CreateOrEdit.EditCharacter, selectedCharacter.getId()));
		}
	}

	@Override
	public void createCharacter() {
		if (markerX < 0 || markerY < 0) {
			clientFactory.getPostListView().showMap();
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "You must set the map marker to show where the character will be created"));
		} else {
			clientFactory.getPlaceController().goTo(new CharacterEditPlace(CreateOrEdit.CreateCharacter, selectedLocation.getId()));
		}
	}

	@Override
	public void copyCharacter() {

		if (selectedCharacter == null || selectedCharacter.getId().equals(playingCharacter.getId())) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "Select a character to copy"));
			return;
		}
		if (markerX < 0 || markerY < 0) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "Place your marker where you want to create a copy of the selected character"));
			return;
		}
		clientFactory.getGameController().saveCharacter(selectedCharacter, true);

	}

	private Boolean moving = null;

	@Override
	public void moveCharacter() {

		if (selectedCharacter.getCharacterType().equals("GM")) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "The Game Master does not have a token and cannot be moved"));
			return;
		}

		if (markerX < 0 || markerY < 0) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "You must set the map marker to show where the character will be moved to"));
			return;
		}

		if (playingCharacter.getCharacterType().equals("GM")) {
			selectedCharacter.setTokenX(new Double(markerX));
			selectedCharacter.setTokenY(new Double(markerY));
			selectedCharacter.setLocationId(selectedLocation.getId());
			clientFactory.getGameController().saveCharacter(selectedCharacter);
		} else {
			playingCharacter.setTokenX(new Double(markerX));
			playingCharacter.setTokenY(new Double(markerY));
			clientFactory.getGameController().saveCharacter(playingCharacter);
		}
		moving = true;
		PlayView playView = clientFactory.getPostListView();
		playView.clearPlaceMarker();
	}

	private Boolean hiding = null;

	@Override
	public void hideCharacter() {

		if (selectedCharacter.getId().equals(game.getGameMasterCharacterId())) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "The Game Master does not have a token and cannot be hidden"));
			return;
		}

		selectedCharacter.setTokenHidden(selectedCharacter.getTokenHidden() == null ? false : !selectedCharacter.getTokenHidden());
		clientFactory.getGameController().saveCharacter(selectedCharacter);
		hiding = selectedCharacter.getTokenHidden();

	}

	@Override
	public void playCharacter() {
		clientFactory.getGameController().play(selectedCharacter.getId());
	}

	private boolean posted = false;

	@Override
	public void setLeftHand(String weapon) {
		if (playingCharacter.getId().equals(game.getGameMasterCharacterId())) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "The Game Master does not have a left hand"));
			return;
		}
		playingCharacter.setLeftHand(weapon);
		setAttackTypes();
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(weapon).getTwoHanded()) {
			playingCharacter.setRightHand(weapon);
			playingCharacter.setRightTargetArea(playingCharacter.getLeftTargetArea());
			playingCharacter.setRightTargetCharacterId(playingCharacter.getLeftTargetCharacterId());
			playingCharacter.setRightTargetStrike(playingCharacter.getLeftTargetStrike());
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void setRightHand(String weapon) {
		if (playingCharacter.getId().equals(game.getGameMasterCharacterId())) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "The Game Master does not have a right hand"));
			return;
		}
		playingCharacter.setRightHand(weapon);
		setAttackTypes();
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(weapon).getTwoHanded()) {
			playingCharacter.setLeftHand(weapon);
			playingCharacter.setLeftTargetArea(playingCharacter.getRightTargetArea());
			playingCharacter.setLeftTargetCharacterId(playingCharacter.getRightTargetCharacterId());
			playingCharacter.setLeftTargetStrike(playingCharacter.getRightTargetStrike());
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void leftTargetArea(Integer area) {
		playingCharacter.setLeftTargetArea(area);
		updateTargets();
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(playingCharacter.getLeftHand()).getTwoHanded()) {
			playingCharacter.setRightTargetArea(area);
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void rightTargetArea(Integer area) {
		playingCharacter.setRightTargetArea(area);
		updateTargets();
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(playingCharacter.getRightHand()).getTwoHanded()) {
			playingCharacter.setLeftTargetArea(area);
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void leftTargetStrike(String strike) {
		playingCharacter.setLeftTargetStrike(strike);
		if ("Defend".equals(strike)) {
			playingCharacter.setDefence("L");
		}
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(playingCharacter.getLeftHand()).getTwoHanded()) {
			playingCharacter.setRightTargetStrike(strike);
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void rightTargetStrike(String strike) {
		playingCharacter.setRightTargetStrike(strike);
		if ("Defend".equals(strike)) {
			playingCharacter.setDefence("R");
		}
		GameController gc = clientFactory.getGameController();
		if (gc.getWeapon(playingCharacter.getRightHand()).getTwoHanded()) {
			playingCharacter.setLeftTargetStrike(strike);
		}
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void leftTargetCharacter() {
		String selid = selectedCharacter.getId();
		GameController gc = clientFactory.getGameController();
		if (gc.getCharacterById(selid) == null) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "You can only target characters in the same place as your character"));
			return;
		}
		String val = playingCharacter.getLeftTargetCharacterId();
		if ((val == null || "".equals(val)) && !selid.equals(playingCharacter.getId())) {
			playingCharacter.setLeftTargetCharacterId(selid);
		} else {
			playingCharacter.setLeftTargetCharacterId(null);
		}
		if (gc.getWeapon(playingCharacter.getLeftHand()).getTwoHanded()) {
			playingCharacter.setRightTargetCharacterId(playingCharacter.getLeftTargetCharacterId());
		}
		updateTargets();
		gc.saveCharacter(playingCharacter);
	}

	@Override
	public void rightTargetCharacter() {
		String selid = selectedCharacter.getId();
		GameController gc = clientFactory.getGameController();
		if (gc.getCharacterById(selid) == null) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "You can only target characters in the same place as your character"));
			return;
		}
		String val = playingCharacter.getRightTargetCharacterId();
		if ((val == null || "".equals(val)) && !selid.equals(playingCharacter.getId())) {
			playingCharacter.setRightTargetCharacterId(selid);
		} else {
			playingCharacter.setRightTargetCharacterId(null);
		}
		if (gc.getWeapon(playingCharacter.getRightHand()).getTwoHanded()) {
			playingCharacter.setLeftTargetCharacterId(playingCharacter.getRightTargetCharacterId());
		}
		updateTargets();
		clientFactory.getGameController().saveCharacter(playingCharacter);
	}

	@Override
	public void onAdd(AddToNextPostEvent event) {
		PlayView playView = clientFactory.getPostListView();
		playView.getPostField().setText(event.getText());
	}

	@Override
	public void createPost() {

		if (posted) {
			return;
		}
		final PlayView postListView = clientFactory.getPostListView();
		//make sure there is something to post
		String postText = postListView.getPostField().getHTML();
		if (postText == null || postListView.getPostField().getText().length() <= 1) {
			clientFactory.getEventBus().fireEvent(new MessageEvent(Level.ERROR, "No text entered in post"));
			return;
		}

		//create post
		PostResult post = new PostResult();
		post.setCharacterId(playingCharacter.getId());
		post.setImportant(postListView.getImportantPostValue());

		post.setText(postText);
		post.setLocationId(selectedLocation.getId());

		//set private post indicator value
		String target = null;
		if (postListView.getPrivatePostValue()) {
			if (!playingCharacter.getId().equals(selectedCharacter.getId())) {
				target = selectedCharacter.getId();
			} else {
				target = game.getGameMasterCharacterId();
			}
		}
		post.setTargetedCharacterId(target);

		//set the marker position
		post.setMarkerX(markerX);
		post.setMarkerY(markerY);
		clientFactory.getEventBus().fireEvent(new ChangeMarkerEvent());

		//save post
		clientFactory.getGameController().savePost(post);

		postListView.resetButtons();
		postListView.clearPlaceMarker();
		markerX = -50;
		markerY = -50;
		posted = true;
		postingMessage();

	}

	public static class PlayPlace extends Place {
		public static final String TOKEN = "play";
	}

}


text:
//
//  TKPreferredFontCategory.h
//  IntroToTextKitDemo2013
//
//  Created by xiekw on 1/16/15.
//  Copyright (c) 2015 Apple Inc. All rights reserved.
//

#import <UIKit/UIKit.h>

/*Notice: Please try to observe UIContentSizeCategoryDidChangeNotification notification to update the layout*/

@interface UIFont (TextKitDemo)
+ (UIFont *)tkd_preferredFontWithTextStyle:(NSString *)aTextStyle scale:(CGFloat)aScale;
- (NSString *)tkd_textStyle;
- (UIFont *)tkd_fontWithScale:(CGFloat)fontScale;
@end

@interface UIFontDescriptor (TextKitDemo)
+ (UIFontDescriptor *)tkd_preferredFontDescriptorWithTextStyle:(NSString *)aTextStyle scale:(CGFloat)aScale;
- (NSString *)tkd_textStyle;
- (UIFontDescriptor *)tkd_fontDescriptorWithScale:(CGFloat)aScale;
@end

@interface UITextView (TextKitDemo)
- (NSString *)tkd_textStyle;
- (void)usePreferredFontWithScale:(CGFloat)scale;
- (UIFont *)preferredFontWithScale:(CGFloat)scale;
@end

@interface UILabel (TextKitDemo)
- (NSString *)tkd_textStyle;
- (void)usePreferredFontWithScale:(CGFloat)scale;
- (UIFont *)preferredFontWithScale:(CGFloat)scale;
@end

@interface UITextField (TextKitDemo)
- (NSString *)tkd_textStyle;
- (void)usePreferredFontWithScale:(CGFloat)scale;
- (UIFont *)preferredFontWithScale:(CGFloat)scale;
@end

@interface UIButton (TDKDemo)
- (NSString *)tkd_textStyle;
- (void)usePreferredFontWithScale:(CGFloat)scale;
- (UIFont *)preferredFontWithScale:(CGFloat)scale;
@end

redpajama_set_name: RedPajamaGithub


text:
package net.jpeelaer.ospos;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;

import com.google.common.collect.ComparisonChain;

class LanguageLine implements Comparable<LanguageLine> {

	/**
	 *
	 */
	private final CsvLanguageTool csvLanguageTool;

	private String label, fileName;

	private Set<Translation> translations = new HashSet<Translation>();

	public LanguageLine(CsvLanguageTool csvLanguageTool, Matcher matcher, String fileName) {
		this.csvLanguageTool = csvLanguageTool;
		this.label =matcher.group(1) + "_" +  matcher.group(2) ;
		this.fileName = fileName.split("\\.")[0];
	}

	public void addTranslation(String language, String text) {
		translations.add(new Translation(this.csvLanguageTool, label, language, text));
	}

	public Set<Translation> getTranslations() {
		return translations;
	}

	public String getLabel() {
		return label;
	}

	public String getFileName() {
		return fileName;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + getOuterType().hashCode();
		result = prime * result
				+ ((fileName == null) ? 0 : fileName.hashCode());
		result = prime * result + ((label == null) ? 0 : label.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LanguageLine other = (LanguageLine) obj;
		if (!getOuterType().equals(other.getOuterType()))
			return false;
		if (fileName == null) {
			if (other.fileName != null)
				return false;
		} else if (!fileName.equals(other.fileName))
			return false;
		if (label == null) {
			if (other.label != null)
				return false;
		} else if (!label.equals(other.label))
			return false;
		return true;
	}

	private CsvLanguageTool getOuterType() {
		return this.csvLanguageTool;
	}

	String[] toCsvLine(List<String> languages) {
		List<String> csvLines = new ArrayList<String>();
		csvLines.add(getLabel());
		for(String language : languages) {
			boolean textFound = false;
			for (Translation translation : getTranslations()) {
				if (translation.getLanguage().equals(language)) {
					csvLines.add(translation.getText());
					textFound = true;
				}
			}
			if (!textFound) {
				csvLines.add("");
			}
		}
		return csvLines.toArray(new String[csvLines.size()]);
	}

	public int compareTo(LanguageLine line) {
		return ComparisonChain.start()
			.compare(getFileName(), line.getFileName())
			.compare(getLabel(), line.getLabel()).result();
	}

	public String toString() {
		return "$lang['" + label + "'] = " + translations.iterator().next() + ";";
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1"
         xmlns:naming="http://geronimo.apache.org/xml/ns/naming-1.2"
         xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0"
         xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">

  <sys:environment>
    <sys:moduleId>
      <sys:groupId>${project.groupId}</sys:groupId>
      <sys:artifactId>${project.artifactId}</sys:artifactId>
      <sys:version>${project.version}</sys:version>
      <sys:type>car</sys:type>
    </sys:moduleId>
	<sys:dependencies>
            <sys:dependency>
               <sys:groupId>org.apache.geronimo.framework</sys:groupId>
               <sys:artifactId>rmi-naming</sys:artifactId>
           </sys:dependency>
    </sys:dependencies>
    <sys:hidden-classes/>
    <sys:non-overridable-classes/>
  </sys:environment>

    <context-root>${project.artifactId}</context-root>
	<gbean name="URLBindingA" class="org.apache.geronimo.testsuite.deployment.URLBinding.urlGBeanImpl">
        <attribute name="url">http://geronimo.apache.org</attribute>
    </gbean>
</web-app>


text:
package org.codehaus.griffon.runtime.core;

import griffon.inject.BindTo;

import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;

public class FieldsModuleTestcase {
    public static class Targets {
        @BindTo(Atom.class)
        public Hydrogen hydrogen;

        @BindTo(Atom.class)
        @Named("Helium")
        public Helium litium;
    }

    public static class SingletonTargets {
        @Singleton
        @BindTo(Atom.class)
        public Hydrogen hydrogen;

        @Singleton
        @BindTo(Atom.class)
        @Named("Helium")
        public Helium helium;
    }

    public static class ProviderTypes {
        @BindTo(Atom.class)
        public LitiumProvider litium;

        @BindTo(Atom.class)
        @Named("Berilium")
        public BeriliumProvider berilium;
    }

    public static class SingletonProviderTypes {
        @Singleton
        @BindTo(Atom.class)
        public LitiumProvider litium;

        @Singleton
        @BindTo(Atom.class)
        @Named("Berilium")
        public BeriliumProvider berilium;
    }

    public static class Instances {
        @BindTo(Atom.class)
        public Atom boron = new Boron();

        @BindTo(Atom.class)
        @Named("Carbon")
        public Atom carbon = new Carbon();
    }

    public static class Providers {
        @BindTo(Atom.class)
        public Provider<Nitrogen> nitrogen = new NitrogenProvider();

        @BindTo(Atom.class)
        @Named("Oxygen")
        public Provider<Oxygen> oxygen = new OxygenProvider();
    }

    public static class SingletonProviders {
        @Singleton
        @BindTo(Atom.class)
        public Provider<Nitrogen> nitrogen = new NitrogenProvider();

        @Singleton
        @BindTo(Atom.class)
        @Named("Oxygen")
        public Provider<Oxygen> oxygen = new OxygenProvider();
    }

    public static class Hydrogen implements Atom {
        @Override
        public int getNumElectrons() {
            return 1;
        }
    }

    public static class Helium implements Atom {
        @Override
        public int getNumElectrons() {
            return 2;
        }
    }

    public static class Litium implements Atom {
        @Override
        public int getNumElectrons() {
            return 3;
        }
    }

    public static class Berilium implements Atom {
        @Override
        public int getNumElectrons() {
            return 4;
        }
    }

    public static class Boron implements Atom {
        @Override
        public int getNumElectrons() {
            return 5;
        }
    }

    public static class Carbon implements Atom {
        @Override
        public int getNumElectrons() {
            return 6;
        }
    }

    public static class Nitrogen implements Atom {
        @Override
        public int getNumElectrons() {
            return 7;
        }
    }

    public static class Oxygen implements Atom {
        @Override
        public int getNumElectrons() {
            return 8;
        }
    }

    public static class LitiumProvider implements Provider<Litium> {
        @Override
        public Litium get() {
            return new Litium();
        }
    }

    public static class BeriliumProvider implements Provider<Berilium> {
        @Override
        public Berilium get() {
            return new Berilium();
        }
    }

    public static class NitrogenProvider implements Provider<Nitrogen> {
        @Override
        public Nitrogen get() {
            return new Nitrogen();
        }
    }

    public static class OxygenProvider implements Provider<Oxygen> {
        @Override
        public Oxygen get() {
            return new Oxygen();
        }
    }
}


text:
# Dispatch Workflow

> [Create][github-dispatch-workflow] a workflow dispatch event.

## Usage

```javascript
var dispatch = require( '@stdlib/_tools/github/dispatch-workflow' );
```

#### dispatch( slug, id, options, clbk )

[Creates][github-dispatch-workflow] a workflow dispatch event.

```javascript
var opts = {
    'token': 'tkjorjk34ek3nj4!'
};

dispatch( 'stdlib-js/utils-property-symbols', 'test.yml', opts, clbk );

function clbk( error, data, info ) {
    // Check for rate limit information...
    if ( info ) {
        console.error( 'Limit: %d', info.limit );
        console.error( 'Remaining: %d', info.remaining );
        console.error( 'Reset: %s', (new Date( info.reset*1000 )).toISOString() );
    }
    if ( error ) {
        if ( error instanceof Error ) {
            throw error;
        }
        console.error( error.message );
    } else {
        console.log( JSON.stringify( data ) );
    }
}
```

The function accepts the following `options`:

-   **token**: GitHub [access token][github-token] (_required_).
-   **protocol**: request protocol. Default: `'https'`.
-   **hostname**: endpoint hostname. Default: `'api.github.com'`.
-   **port**: endpoint port. Default: `443` (https) or `80` (http).
-   **useragent**: [user agent][github-user-agent] `string`.
-   **ref**: git reference for the workflow (branch or tag name). Default: `'main'`.
-   **inputs**: input key-value pairs overriding the defaults specified in the workflow file. The maximum number of properties is ten.

To specify a [user agent][github-user-agent], set the `useragent` option.

```javascript
var opts = {
    'token': 'tkjorjk34ek3nj4!',
    'useragent': 'hello-github!'
};

dispatch( 'stdlib-js/utils-property-symbols', 'test.yml', opts, clbk );

function clbk( error, info ) {
    if ( info ) {
        console.error( info );
    }
    if ( error ) {
        if ( error instanceof Error ) {
            throw error;
        }
        console.error( error.message );
    } else {
        console.log( 'Success!' );
    }
}
```

## Notes

-   [Rate limit][github-rate-limit] information includes the following:

    -   **limit**: maximum number of requests a consumer is permitted to make per hour.
    -   **remaining**: number of remaining requests.
    -   **reset**: time at which the current [rate limit][github-rate-limit] window resets in [UTC seconds][unix-time].

## Examples

```javascript
var dispatch = require( '@stdlib/_tools/github/dispatch-workflow' );

var opts = {
    'token': 'tkjorjk34ek3nj4!',
    'useragent': 'my-unique-agent'
};

dispatch( 'stdlib-js/utils-property-symbols', 'test.yml', opts, clbk );

function clbk( error, info ) {
    if ( info ) {
        console.error( info );
    }
    if ( error ) {
        if ( error instanceof Error ) {
            throw error;
        }
        console.error( error.message );
    } else {
        console.log( 'Success!' );
    }
}
```

**Note**: in order to run the example, you will need to obtain an access [token][github-token] and modify the `token` option accordingly.

* * *

## CLI

### Usage

```text
Usage: ghdispatch [options] slug --id id

Options:

  -h,   --help                       Print this message.
  -V,   --version                    Print the package version.
        --protocol proto             Request protocol. Default: https.
        --hostname host              Hostname. Default: api.github.com.
  -p,   --port port                  Port. Default: 443 (https) or 80 (http).
        --token token                GitHub access token.
  --ua, --useragent ua               User agent.
        --id id                      ID or file name of the workflow.
        --ref                        git reference for the workflow.
        --inputs                     Input keys + values (key1=value,key2=...).
```

### Notes

-   In addition to the [`token`][github-token] option, the [token][github-token] may also be specified by a [`GITHUB_TOKEN`][github-token] environment variable. The command-line option **always** takes precedence.
-   Requested resources are written to `stdout`.
-   [Rate limit][github-rate-limit] information is written to `stderr`.

### Examples

Setting the access [token][github-token] using the command-line option:

```bash
$ DEBUG=* ghdispatch 'stdlib-js/utils-property-symbols' --token <token> --id 'test.yml'
```

Setting the access [token][github-token] using an environment variable:

```bash
$ DEBUG=* GITHUB_TOKEN=<token> ghdispatch 'stdlib-js/utils-property-symbols' --id 'test.yml'
```

[unix-time]: https://en.wikipedia.org/wiki/Unix_time

[github-token]: https://github.com/settings/tokens/new

[github-user-agent]: https://developer.github.com/v3/#user-agent-required

[github-rate-limit]: https://developer.github.com/v3/rate_limit/

[github-dispatch-workflow]: https://docs.github.com/en/rest/reference/actions#create-a-workflow-dispatch-event


text:
<?php

namespace TypiCMS\Modules\ProductCategories\Shells\Repositories;

use TypiCMS\Modules\ProductCategories\Repositories\CacheDecorator as BaseClass;

class CacheDecorator extends BaseClass implements ProductCategoryInterface
{

}


text:
package db

import (
	"fmt"

	"github.com/lxc/lxd/lxd/db/query"
	"github.com/pkg/errors"
)

// Operation holds information about a single LXD operation running on a node
// in the cluster.
type Operation struct {
	ID          int64  // Stable database identifier
	UUID        string // User-visible identifier
	NodeAddress string // Address of the node the operation is running on
}

// OperationsUUIDs returns the UUIDs of all operations associated with this
// node.
func (c *ClusterTx) OperationsUUIDs() ([]string, error) {
	stmt := "SELECT uuid FROM operations WHERE node_id=?"
	return query.SelectStrings(c.tx, stmt, c.nodeID)
}

// OperationByUUID returns the operation with the given UUID.
func (c *ClusterTx) OperationByUUID(uuid string) (Operation, error) {
	null := Operation{}
	operations, err := c.operations("uuid=?", uuid)
	if err != nil {
		return null, err
	}
	switch len(operations) {
	case 0:
		return null, NoSuchObjectError
	case 1:
		return operations[0], nil
	default:
		return null, fmt.Errorf("more than one node matches")
	}
}

// OperationAdd adds a new operations to the table.
func (c *ClusterTx) OperationAdd(uuid string) (int64, error) {
	columns := []string{"uuid", "node_id"}
	values := []interface{}{uuid, c.nodeID}
	return query.UpsertObject(c.tx, "operations", columns, values)
}

// OperationRemove removes the operation with the given UUID.
func (c *ClusterTx) OperationRemove(uuid string) error {
	result, err := c.tx.Exec("DELETE FROM operations WHERE uuid=?", uuid)
	if err != nil {
		return err
	}
	n, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("query deleted %d rows instead of 1", n)
	}
	return nil
}

// Operations returns all operations in the cluster, filtered by the given clause.
func (c *ClusterTx) operations(where string, args ...interface{}) ([]Operation, error) {
	operations := []Operation{}
	dest := func(i int) []interface{} {
		operations = append(operations, Operation{})
		return []interface{}{
			&operations[i].ID,
			&operations[i].UUID,
			&operations[i].NodeAddress,
		}
	}
	stmt := `
SELECT operations.id, uuid, nodes.address FROM operations JOIN nodes ON nodes.id = node_id `
	if where != "" {
		stmt += fmt.Sprintf("WHERE %s ", where)
	}
	stmt += "ORDER BY operations.id"
	err := query.SelectObjects(c.tx, dest, stmt, args...)
	if err != nil {
		return nil, errors.Wrap(err, "failed to fecth operations")
	}
	return operations, nil
}


text:
<session>

                        <input class="rating" data-bind="courseRating: {'rating': rating()}, value: rating()"/>

                            Teach

                            About

                            For

                        Course's Name

 0 && $root.user.id() != creatorId()">
                        Rate this course:
                        <input class="rating"
                               data-bind="rating: {'rating': $root.learningCourse.rating()}, value: rating(), event: {change: $root.saveRating.bind($root, $element)}"/>

This page is created to describe about course's detail

                    <div class="row container-fluid" style="margin-bottom: 10px"
                         data-bind="if: $root.user.isLogin() && (!$root.learningCourse.id() || $root.learningCourse.id() < 0)">
                        <button type="button" class="btn btn-success btn-lg"
                                data-bind="click: $root.enroll.bind($root)">

                            Start Learning
                        </button>

                        Created by
                        Somebody

                            Edit Course

                Course Details

                <form class="nav nav-pills navbar-right" data-bind="foreach: router.navigationModel">

                </form>

</session>


text:
package cn.com.newcapec.citycard.system.service;

import java.util.List;

import cn.com.newcapec.common.domain.Node;
import cn.com.newcapec.common.exception.BusinessException;
import cn.com.newcapec.citycard.common.po.TOrgPermission;

/**
 * <pre>
 * 功能描述:模块管理服务接口定义
 *
 * Author : Wangjian
 * Date   : 2008-06-03
 * Time   : 10:11:15
 * Version: 1.0
 * </pre>
 */
public interface IModuleInfoService {

	/**
	 * 查询当前满足查询条件的记录总数
	 *
	 * @param parentId:
	 *            Integer对象
	 * @return 根据给定的parentId返回记录总数
	 */
	public Integer getModuleInfoCountByQuery(Integer parentId)
			throws BusinessException;

	/**
	 * 功能描述:得到模块管理树型目录结点列表
	 *
	 * @return List<Node> 模块管理树型目录结点列表
	 */
	public List<Node> getModuleInfoTreeNodeList() throws BusinessException;

	/**
	 * 功能描述:得到已分配或未分配给指定角色的模块管理树型目录结点列表
	 *
	 * @return List<Node> 已分配或未分配给指定角色的模块管理树型目录结点列表
	 */
	public List<Node> getModuleInfoTreeNodeByRole(Integer roleId) throws BusinessException;

	/**
	 * 功能描述:得到指定ID号功能模块所有包含的子模块列表
	 *
	 * @return List<ModuleInfo> 子模块列表
	 */
	public List<TOrgPermission> getAllChildNodeById(Integer parentId,
			int firstResult, int maxResults) throws BusinessException;

	/**
	 * 保存或修改模块
	 *
	 * @param obj:模块
	 * @return
	 * @throws BusinessException
	 *             业务异常
	 */
	public void saveOrUpdateModuleInfo(TOrgPermission moduleInfo)
			throws BusinessException;

	/**
	 * 根据主键查询记录的详细信息
	 *
	 * @param id:
	 *            ModuleInfo主键
	 * @return ModuleInfo: ModuleInfo对象
	 */
	public TOrgPermission getModuleInfoByPK(int id);

	/**
	 * 删除所选择的模块
	 *
	 */
	public void deleteModuleInfo(List<Integer> id) throws BusinessException;

}


text:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Common.Apis;
using Android.Gms.Common;
using Android.Gms.Plus;
using Android.Gms.Plus.Model.People;

namespace gplus_tutorial
{
    [Activity(Label = "gplus_tutorial", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity, IGoogleApiClientConnectionCallbacks, IGoogleApiClientOnConnectionFailedListener
    {
        private IGoogleApiClient mGoogleApiClient;
        private SignInButton mGoogleSignIn;

        private ConnectionResult mConnectionResult;

        private bool mIntentInProgress;
        private bool mSignInClicked;
        private bool mInfoPopulated;

        private TextView mName;
        private TextView mTagline;
        private TextView mBraggingRights;
        private TextView mGender;
        private TextView mRelationship;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            mGoogleSignIn = FindViewById<SignInButton>(Resource.Id.sign_in_button);

            mName = FindViewById<TextView>(Resource.Id.txtName);
            mTagline = FindViewById<TextView>(Resource.Id.txtTagLine);
            mBraggingRights = FindViewById<TextView>(Resource.Id.txtBraggingRights);
            mGender = FindViewById<TextView>(Resource.Id.txtGender);
            mRelationship = FindViewById<TextView>(Resource.Id.txtRelationship);

            mGoogleSignIn.Click += mGoogleSignIn_Click;

            GoogleApiClientBuilder builder = new GoogleApiClientBuilder(this);
            builder.AddConnectionCallbacks(this);
            builder.AddOnConnectionFailedListener(this);
            builder.AddApi(PlusClass.Api);
            builder.AddScope(PlusClass.ScopePlusProfile);
            builder.AddScope(PlusClass.ScopePlusLogin);

            //Build our IGoogleApiClient
            mGoogleApiClient = builder.Build();
        }

        void mGoogleSignIn_Click(object sender, EventArgs e)
        {
            //Fire sign in
            if (!mGoogleApiClient.IsConnecting)
            {
                mSignInClicked = true;
                ResolveSignInError();
            }
        }

        private void ResolveSignInError()
        {
            if (mGoogleApiClient.IsConnected)
            {
                //No need to resolve errors, already connected
                return;
            }

            if (mConnectionResult.HasResolution)
            {
                try
                {
                    mIntentInProgress = true;
                    StartIntentSenderForResult(mConnectionResult.Resolution.IntentSender, 0, null, 0, 0, 0);
                }

                catch (Android.Content.IntentSender.SendIntentException e)
                {
                    //The intent was cancelled before it was sent. Return to the default
                    //state and attempt to connect to get an updated ConnectionResult
                    mIntentInProgress = false;
                    mGoogleApiClient.Connect();
                }
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
           if (requestCode == 0)
           {
               if (resultCode != Result.Ok)
               {
                   mSignInClicked = false;
               }

               mIntentInProgress = false;

               if (!mGoogleApiClient.IsConnecting)
               {
                   mGoogleApiClient.Connect();
               }
           }
        }

        protected override void OnStart()
        {
            base.OnStart();
            mGoogleApiClient.Connect();
        }

        protected override void OnStop()
        {
            base.OnStop();
            if (mGoogleApiClient.IsConnected)
            {
                mGoogleApiClient.Disconnect();
            }
        }

        public void OnConnected(Bundle connectionHint)
        {
            //Successful log in hooray!!
            mSignInClicked = false;

            if (mInfoPopulated)
            {
                //No need to populate info again
                return;
            }

            if (PlusClass.PeopleApi.GetCurrentPerson(mGoogleApiClient) != null)
            {
                IPerson plusUser = PlusClass.PeopleApi.GetCurrentPerson(mGoogleApiClient);

                if (plusUser.HasDisplayName)
                {
                    mName.Text += plusUser.DisplayName;
                }

                if (plusUser.HasTagline)
                {
                    mTagline.Text += plusUser.Tagline;
                }

                if (plusUser.HasBraggingRights)
                {
                    mBraggingRights.Text += plusUser.HasBraggingRights;
                }

                if (plusUser.HasRelationshipStatus)
                {
                    switch (plusUser.RelationshipStatus)
                    {
                        case 0:
                            mRelationship.Text += "Single";
                            break;

                        case 1:
                            mRelationship.Text += "In a relationship";
                            break;

                        case 2:
                            mRelationship.Text += "Engaged";
                            break;

                        case 3:
                            mRelationship.Text += "Married";
                            break;

                        case 4:
                            mRelationship.Text += "It's complicated";
                            break;

                        case 5:
                            mRelationship.Text += "In an open relationship";
                            break;

                        case 6:
                            mRelationship.Text += "Widowed";
                            break;

                        case 7:
                            mRelationship.Text += "In a domestic partnership";
                            break;

                        case 8:
                            mRelationship.Text += "In a civil union";
                            break;

                        default:
                            mRelationship.Text += "Unknown";
                            break;
                    }
                }

                if (plusUser.HasGender)
                {
                    switch (plusUser.Gender)
                    {
                        case 0:
                            mGender.Text += "Male";
                            break;

                        case 1:
                            mGender.Text += "Female";
                            break;

                        case 2:
                            mGender.Text += "Other";
                            break;

                        default:
                            mGender.Text += "Unknown";
                            break;
                    }
                }

                mInfoPopulated = true;
            }
        }

        public void OnConnectionSuspended(int cause)
        {
            throw new NotImplementedException();
        }

        public void OnConnectionFailed(ConnectionResult result)
        {
           if (!mIntentInProgress)
           {
               //Store the ConnectionResult so that we can use it later when the user clicks 'sign-in;
               mConnectionResult = result;

               if (mSignInClicked)
               {
                   //The user has already clicked 'sign-in' so we attempt to resolve all
                   //errors until the user is signed in, or the cancel
                   ResolveSignInError();
               }
           }
        }
    }
}


text:
package org.tntstudio.utils.math;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Disposable;

public class Line implements Disposable {
	public Vector2 lineStart;
	public Vector2 lineEnd;

	private Vector2 mTMP = new Vector2();

	public static final class LineMode {
		public static final byte SQUARE_LINE = 0;
		public static final byte PARALLEL_LINE = 1;
	}

	public Line () {
		lineStart = new Vector2();
		lineEnd = new Vector2();
	}

	public Line (Line line) {
		set(line);
	}

	public Line (Vector2 startPoint, float angleFactor) {

	}

	public Line (Vector2 startPoint, Line line, byte linemode) {
		if (linemode == LineMode.SQUARE_LINE) {
			Vector2 d = line.getNormalVector();
			Vector2 endPoint = new Vector2(startPoint.x + d.x, startPoint.y + d.y);
			set(startPoint, endPoint);
		} else if (linemode == LineMode.PARALLEL_LINE) {
			Vector2 d = line.getDirectionalVector();
			Vector2 endPoint = new Vector2(startPoint.x + d.x, startPoint.y + d.y);
			set(startPoint, endPoint);
		}
	}

	public Line (float startX, float startY, Vector2 normalVector) {
		lineStart = new Vector2(startX, startY);
		lineEnd = new Vector2(startX + normalVector.y, startY - normalVector.x);
	}

	public Line (Vector2 lineStart, Vector2 lineEnd) {
		this.lineStart = lineStart;
		this.lineEnd = lineEnd;
	}

	public Line (float startX, float startY, float endX, float endY) {
		this.lineStart = new Vector2(startX, startY);
		this.lineEnd = new Vector2(endX, endY);
	}

	/*************************************************************
         *
         *************************************************************/
	public Line set (float x, float y, float x1, float y1) {
		lineStart.set(x, y);
		lineEnd.set(x1, y1);
		return this;
	}

	public Line setEnd (float x, float y) {
		lineEnd.set(x, y);
		return this;
	}

	public Line setStart (float x, float y) {
		lineStart.set(x, y);
		return this;
	}

	private void set (Vector2 startPoint, Vector2 endPoint) {
		lineStart = startPoint;
		lineEnd = endPoint;
	}

	public Line set (Line line) {
		this.lineStart = new Vector2(line.lineStart.x, line.lineStart.y);
		this.lineEnd = new Vector2(line.lineEnd.x, line.lineEnd.y);
		return this;
	}

	public Line cpy () {
		return new Line(this);
	}

	/*************************************************************
         *
         *************************************************************/

	public Vector2 getNormalVector () {
		mTMP.set(lineEnd.x - lineStart.x, lineEnd.y - lineStart.y);
		if (mTMP.y < 0)
			mTMP.set(-mTMP.y, mTMP.x);
		else
			mTMP.set(mTMP.y, -mTMP.x);
		return mTMP;
	}

	public Vector2 getDirectionalVector () {
		return mTMP.set(lineEnd.x - lineStart.x, lineEnd.y - lineStart.y);
	}

	/** Get the angle between this line and 0x line
	 *
	 * @return result is in range [0,360] */
	public float getAngleFactor () {
		if (lineEnd.x == lineStart.x) {
			if (lineEnd.y > lineStart.y) return 90;
			if (lineEnd.y < lineStart.y) return 270;
		}

		if (lineEnd.y == lineStart.y) {
			if (lineStart.x < lineEnd.x) return 360;
			if (lineStart.x > lineEnd.x) return 180;
		}

		if (lineEnd.x > lineStart.x)
			return (float)(180.0f / MathUtils.PI * Math.atan((lineEnd.y - lineStart.y) / (lineEnd.x - lineStart.x)));
		if (lineEnd.x < lineStart.x)
			return (float)(180.0f / MathUtils.PI * Math.atan((lineEnd.y - lineStart.y) / (lineEnd.x - lineStart.x))) - 180;

		return 0;
	}

	public float getConstantOfLine () {
		Vector2 n = getNormalVector();
		float c = -(n.x * lineStart.x + n.y * lineStart.y);
		return c;
	}

	public Vector2 getMidPoint () {
		return mTMP.set((lineStart.x + lineEnd.x) / 2, (lineStart.y + lineEnd.y) / 2);
	}

	/*************************************************************
         *
         *************************************************************/

	public float module () {
		float tmp = (float)Math.sqrt((lineStart.x - lineEnd.x) * (lineStart.x - lineEnd.x) + (lineStart.y - lineEnd.y)
			* (lineStart.y - lineEnd.y));
		return tmp;
	}

	public float module2 () {
		float tmp = (float)((lineStart.x - lineEnd.x) * (lineStart.x - lineEnd.x) + (lineStart.y - lineEnd.y)
			* (lineStart.y - lineEnd.y));
		return tmp;
	}

	/*************************************************************
         *
         *************************************************************/

	public int getXinLine (int y) {
		float delta = ((float)(lineStart.x - lineEnd.x) / (float)(lineStart.y - lineEnd.y));
		return (int)(delta * (y - lineStart.y) + lineStart.x);
	}

	public float getYinLine (float x) {
		float delta = ((float)(lineStart.y - lineEnd.y) / (float)(lineStart.x - lineEnd.x));
		return (int)(delta * (x - lineStart.x) + lineStart.y);
	}

	/** You input point(x0,y0) and i will return: a*x0 + b*y0 + c
	 *
	 * @param point
	 * @return */
	public float getLine (Vector2 point) {
		// Normal vector in 2D (vector pha'p tuyen)
		Vector2 n = getNormalVector();
		float c = -(n.x * lineStart.x + n.y * lineStart.y);

		return (n.x * point.x + n.y * point.y + c);
	}

	/*************************************************************
         *
         *************************************************************/
	public float getSideOnLine (Vector2 point) {
		float side = getLine(point);
		return side;
	}

	public boolean isOnLeftSide (Vector2 point) {
		if (getSideOnLine(point) < 0) return true;
		return false;
	}

	public boolean isOnRightSide (Vector2 point) {
		if (getSideOnLine(point) > 0) return true;
		return false;
	}

	public float calDistancePointToLine (Vector2 point) {
		float delta = Math.abs(getLine(point));

		float module = getNormalVector().len();

		return (delta / module);
	}

	public Vector2 calCrossPoint (Line line) {
		mTMP = getNormalVector();
		float a1 = mTMP.x;
		float b1 = mTMP.y;
		float c1 = getConstantOfLine();

		mTMP = line.getNormalVector();
		float a2 = mTMP.x;
		float b2 = mTMP.y;
		float c2 = line.getConstantOfLine();

		if (a1 * b2 == b1 * a2)
			return null;
		else
			return new Vector2((b1 * c2 - c1 * b2) / (b2 * a1 - b1 * a2), (a2 * c1 - c2 * a1) / (b2 * a1 - b1 * a2));
	}

	@Override
	public void dispose () {
		lineEnd = null;
		lineStart = null;
		mTMP = null;
	}
}


text:
name: Greenlytics
logo: greenlytics.png
website: https://greenlytics.io
location:
    - Stockholm

positions: []
---


text:
<?php

namespace Reachwhere\WebAppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MerchantHasContact
 *
 * @ORM\Table(name="merchant_has_contact")
 * @ORM\Entity
 */
class MerchantHasContact
{
    /**
     * @var string
     *
     * @ORM\Column(name="id", type="string", length=45, nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * @var \Merchant
     *
     * @ORM\ManyToOne(targetEntity="Merchant")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="merchants_id", referencedColumnName="id")
     * })
     */
    private $merchants;

    /**
     * @var \Contact
     *
     * @ORM\ManyToOne(targetEntity="Contact")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="contacts_id", referencedColumnName="id")
     * })
     */
    private $contacts;

    /**
     * @var \MerchantHasContactType
     *
     * @ORM\ManyToOne(targetEntity="MerchantHasContactType")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="merchant_contact_types_id", referencedColumnName="id")
     * })
     */
    private $merchantContactTypes;

    /**
     * Get id
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return MerchantHasContact
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return MerchantHasContact
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set merchants
     *
     * @param \Reachwhere\WebAppBundle\Entity\Merchant $merchants
     * @return MerchantHasContact
     */
    public function setMerchants(\Reachwhere\WebAppBundle\Entity\Merchant $merchants = null)
    {
        $this->merchants = $merchants;

        return $this;
    }

    /**
     * Get merchants
     *
     * @return \Reachwhere\WebAppBundle\Entity\Merchant
     */
    public function getMerchants()
    {
        return $this->merchants;
    }

    /**
     * Set contacts
     *
     * @param \Reachwhere\WebAppBundle\Entity\Contact $contacts
     * @return MerchantHasContact
     */
    public function setContacts(\Reachwhere\WebAppBundle\Entity\Contact $contacts = null)
    {
        $this->contacts = $contacts;

        return $this;
    }

    /**
     * Get contacts
     *
     * @return \Reachwhere\WebAppBundle\Entity\Contact
     */
    public function getContacts()
    {
        return $this->contacts;
    }

    /**
     * Set merchantContactTypes
     *
     * @param \Reachwhere\WebAppBundle\Entity\MerchantHasContactType $merchantContactTypes
     * @return MerchantHasContact
     */
    public function setMerchantContactTypes(\Reachwhere\WebAppBundle\Entity\MerchantHasContactType $merchantContactTypes = null)
    {
        $this->merchantContactTypes = $merchantContactTypes;

        return $this;
    }

    /**
     * Get merchantContactTypes
     *
     * @return \Reachwhere\WebAppBundle\Entity\MerchantHasContactType
     */
    public function getMerchantContactTypes()
    {
        return $this->merchantContactTypes;
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsAndroidNetworkLinkService.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/Services.h"

#include "AndroidBridge.h"

NS_IMPL_ISUPPORTS1(nsAndroidNetworkLinkService,
                   nsINetworkLinkService)

nsAndroidNetworkLinkService::nsAndroidNetworkLinkService()
{
}

nsAndroidNetworkLinkService::~nsAndroidNetworkLinkService()
{
}

NS_IMETHODIMP
nsAndroidNetworkLinkService::GetIsLinkUp(bool *aIsUp)
{
  if (!mozilla::AndroidBridge::Bridge()) {
    // Fail soft here and assume a connection exists
    NS_WARNING("GetIsLinkUp is not supported without a bridge connection");
    *aIsUp = true;
    return NS_OK;
  }

  *aIsUp = mozilla::AndroidBridge::Bridge()->IsNetworkLinkUp();
  return NS_OK;
}

NS_IMETHODIMP
nsAndroidNetworkLinkService::GetLinkStatusKnown(bool *aIsKnown)
{
  NS_ENSURE_TRUE(mozilla::AndroidBridge::Bridge(), NS_ERROR_NOT_IMPLEMENTED);

  *aIsKnown = mozilla::AndroidBridge::Bridge()->IsNetworkLinkKnown();
  return NS_OK;
}

NS_IMETHODIMP
nsAndroidNetworkLinkService::GetLinkType(uint32_t *aLinkType)
{
  NS_ENSURE_ARG_POINTER(aLinkType);

  // XXX This function has not yet been implemented for this platform
  *aLinkType = nsINetworkLinkService::LINK_TYPE_UNKNOWN;
  return NS_OK;
}


text:
var fontyourfaceSampleText = '';
var fontyourfaceSampleMarkup = '';

(function ($) {

  Drupal.behaviors.fontyourfaceAddForm = {

    attach:function(context, settings) {

      var input = $('#edit-css');
      var selector = input.val();

      fontyourfaceSampleText = $('#edit-sample-text').val();
      fontyourfaceSampleMarkup = $('.fontyourface-view').html();

      $('#edit-sample-text').keyup(function() {

        var markup = fontyourfaceSampleMarkup;
        var updatedText = $('#edit-sample-text').val();

        if (updatedText != fontyourfaceSampleText) {

          markup = markup.split(fontyourfaceSampleText).join(updatedText);
          markup = markup.split(fontyourfaceEncodeURI(fontyourfaceSampleText)).join(fontyourfaceEncodeURI(updatedText));

        } // if

        $('.fontyourface-view').html(markup);

      });

      if (selector && selector.length > 0) {

        var select = $('<select id="edit-css-select"><option value="">-- none --</option><option value="h1, h2, h3, h4, h5, h6">all headers (h1, h2, h3, h4, h5, h6)</option><option value="h1">h1</option><option value="h2">h2</option><option value="h3">h3</option><option value="p, div">standard text (p, div)</option><option value="body">everything (body)</option><option value="<none>">-- add selector in theme CSS --</option><option value="-- other --">other</option>')
          .change(fontyourfaceCssSelectChange)
          .insertBefore(input);

        if (select.find('option[value="' + selector + '"]').length > 0) {

          select.find('option[value=' + selector + ']').attr('selected', true);
          input.hide();

        } // if
        else {

          select.find('option[value="-- other --"]').attr('selected', true);
          input.show();

        } // else

      } // if

    } // attach

  } // Drupal.behaviors.fontyourfaceAddForm

  function fontyourfaceCssSelectChange() {

    var selector = $(this).val();

    if (selector == '') {
      $('#edit-css').show();
    } // if
    else {
      $('#edit-css').val(selector);
      $('#edit-css').hide();
    } // else

  } // fontyourfaceCssSelectChange

  function fontyourfaceEncodeURI(text) {

    return encodeURIComponent(text)
      .replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28')
      .replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');

  } // fontyourfaceEncodeURI

})(jQuery);


text:
@interface UITableViewCell (HDTableViewMaker)
@property (nonatomic,weak) UITableView *tableView;

@property (nonatomic, strong) NSIndexPath *indexPath;

- (void)reloadRow:(UITableViewRowAnimation)animation;

@end


text:
package net.huntersharpe.Underground.util;

import net.huntersharpe.Underground.Underground;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Config implements Configurable{

    private static Config config = new Config();

    private Config()
    {

    }

    public static Config getConfig()
    {
        return config;
    }

    private Path configFile = Paths.get(Underground.getUnderground().getConfigDir() + "/config.conf");
    private ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(configFile).build();
    private CommentedConfigurationNode configNode;

    @Override
    public void setup()
    {
        if (!Files.exists(configFile))
        {
            try
            {
                Files.createFile(configFile);
                load();
                save();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            load();
        }
    }

    @Override
    public void load()
    {
        try
        {
            configNode = configLoader.load();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void save()
    {
        try
        {
            configLoader.save(configNode);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public CommentedConfigurationNode get()
    {
        return configNode;
    }
}


text:
A very simple tool to generate random arithmetic equations using Python

#### Python version
2.7

#### Screenshot
![N|Solid](https://github.com/QuinnSong/LoveMath/blob/master/demo/main.png)

#### Features:
- Generate multiple-step equations
- Support two formats:
    1. Horizontal
	2. Vertical
- Define operation range, e.g. 5, 10, 100...etc.
- Generate unknown equations
- Operations can be a combination of the following:
    1. `+` : addition
    2. `-` : subtraction
    3. `*` : multiplication
    4. `/` : division
    5. `()` : brackets
- Custom header and footer
- Export questions/answers to separate text files
- Preview / Print the questions
- Show / Hide answers
- Options of tenths and hundredths decimals
- Options of borrow/carry in addition and subtraction

2017.06.25


text:
class MessagesController < ApplicationController
  #Prevent access to these actions if not logged in.
  before_action :login_required, :only => [:index, :create, :show, :new]

  def create
    message = current_user.messages.build(message_params)
    message.chat_room = ChatRoom.find(params['room_id'])

    if message.save
      logger.info "Saved"
      # Broadcast using WebSockets so other clients are updated in real time.
      ActionCable.server.broadcast "chat_room_#{params['room_id']}_channel",
                                    message: render_message(message),
                                    user_id: "#{current_user.id}",
                                    message_id: message.id,
                                    type: "send_message"
    end
  end

  def destroy
    message = Message.find(params[:id])
    room_id = message.chat_room.id
    logger.info room_id

    if message.user == current_user || current_user.role == 'admin'
      message.destroy

      # Broadcast using WebSockets so other clients are updated in real time.
      ActionCable.server.broadcast "chat_room_#{room_id}_channel",
                                    message: message.id,
                                    type: "delete_message"
    end
  end

  private
    def message_params
      params.require(:message).permit(:body)
    end

    def render_message(message)
      render partial: "messages/message_sender", locals: {message: message}
    end

    def login_required
      unless logged_in?
        flash[:error] = "Please Log In."
        redirect_to login_path
      end
    end
end


text:
<title>Berkeley DB: DB->set_re_delim</title>
<meta name="description" content="Berkeley DB: An embedded database programmatic toolkit.">
<meta name="keywords" content="embedded,database,programmatic,toolkit,btree,hash,hashing,transaction,transactions,locking,logging,access method,access methods,Java,C,C++">

DB->set_re_delim

<tt>

#include <db.h>

int
DB->set_re_delim(DB *db, int delim);

int
DB->get_re_delim(DB *db, int *delimp);

Description: DB->set_re_delim

Set the delimiting byte used to mark the end of a record in the backing
source file for the Recno access method.

This byte is used for variable length records if the re_source
file is specified.  If the re_source file is specified and no
delimiting byte was specified, <newline> characters (that
is, ASCII 0x0a) are interpreted as end-of-record markers.

The DB->set_re_delim method configures a database, not only operations performed
using the specified DB handle.

The DB->set_re_delim method may not be called after the DB->open method is called.
If the database already exists when
DB->open is called, the information specified to DB->set_re_delim will
be ignored.

The DB->set_re_delim method
returns a non-zero error value on failure
and 0 on success.

Parameters

 re_delim

The re_delim parameter is the delimiting byte used to mark the
end of a record.

Errors

The DB->set_re_delim method
may fail and return one of the following non-zero errors:

EINVAL

If the method was called after DB->open was called; or if an
invalid flag value or parameter was specified.

Description: DB->get_re_delim

The DB->get_re_delim method returns the delimiting byte.

The DB->get_re_delim method may be called at any time during the life of the
application.

The DB->get_re_delim method
returns a non-zero error value on failure
and 0 on success.

Parameters

 delimp

The DB->get_re_delim method returns  the
delimiting byte in delimp.

Class
DB

See Also
Databases and Related Methods
</tt>

Copyright (c) 1996,2008 Oracle.  All rights reserved.


text:
/* global done:false */
/* global error:false */
/* global PaymentRequest:false */

/**
 * Initializes the payment request object.
 */
function buildPaymentRequest() {
  if (!window.PaymentRequest) {
    return null;
  }

  var supportedInstruments = [
    {
      supportedMethods: 'basic-card',
    },
  ];

  var details = {
    total: {
      label: 'Total',
      amount: {
        currency: 'USD',
        value: '1.00',
      },
    },
    shippingOptions: [{
      id: 'freeShippingOption',
      label: 'Free shipping',
      amount: {
        currency: 'USD',
        value: '0.00'
      },
      selected: true
    }]
  };

  var options = {requestShipping: true};

  var request = null;

  try {
    request = new PaymentRequest(supportedInstruments, details, options);
  } catch (e) {
    error("Developer mistake: '" + e + "'");
  }

  if (request.canMakePayment) {
    request
      .canMakePayment()
      .then(function(result) {
        info(result ? 'Can make payment' : 'Cannot make payment');
      })
      .catch(function(err) {
        error(err);
      });
  }

  return request;
}

var request = buildPaymentRequest();

/**
 * Launches payment request for credit cards.
 */
function onBuyClicked() {
  // eslint-disable-line no-unused-vars
  if (!window.PaymentRequest || !request) {
    error('PaymentRequest API is not supported.');
    return;
  }

  try {
    request
      .show()
      .then(function(instrumentResponse) {
        validateResponse(instrumentResponse)
          .then(function() {
              instrumentResponse
                .complete('success')
                .then(function() {
                  done(
                    'This is a demo website. No payment will be processed.',
                    instrumentResponse,
                  );
                })
                .catch(function(err) {
                  error(err);
                  request = buildPaymentRequest();
                });
          });
      })
      .catch(function(err) {
        error(err);
        request = buildPaymentRequest();
      });
  } catch (e) {
    error("Developer mistake: '" + e + "'");
    request = buildPaymentRequest();
  }
}

function validateResponse(response) {
  return new Promise(resolver => {
    if (!response.retry) {
      error('PaymentResponse.retry() is not defined. Is chrome://flags/#enable-experimental-web-platform-features enabled?');
      return;
    }

      if (!response.shippingAddress || response.shippingAddress.postalCode != "12345") {
        var postalCodeError = document.querySelector("#postal-code-error").value;
        response.retry({ shippingAddress: { postalCode: postalCodeError }})
          .then(function() {
            resolver(validateResponse(response));
          });
      } else {
        resolver();
      }
  });
}


text:
class ApacheFlink < Formula
  desc "Scalable batch and stream data processing"
  homepage "https://flink.apache.org/"
  url "https://www.apache.org/dyn/closer.lua?path=flink/flink-1.11.2/flink-1.11.2-bin-scala_2.12.tgz"
  mirror "https://archive.apache.org/dist/flink/flink-1.11.2/flink-1.11.2-bin-scala_2.12.tgz"
  version "1.11.2"
  sha256 "d8d22847e9aa8243373024e74f54f79f281541c4ea0b9034f177cdf290e5c0e0"
  license "Apache-2.0"
  head "https://github.com/apache/flink.git"

  livecheck do
    url :stable
  end

  bottle :unneeded

  depends_on java: "1.8"

  def install
    rm_f Dir["bin/*.bat"]
    libexec.install Dir["*"]
    (libexec/"bin").env_script_all_files(libexec/"libexec", Language::Java.java_home_env("1.8"))
    (libexec/"bin").install Dir["#{libexec}/libexec/*.jar"]
    chmod 0755, Dir["#{libexec}/bin/*"]
    bin.write_exec_script "#{libexec}/bin/flink"
  end

  test do
    (testpath/"log").mkpath
    (testpath/"input").write "foo bar foobar"
    expected = <<~EOS
      (foo,1)
      (bar,1)
      (foobar,1)
    EOS
    ENV.prepend "_JAVA_OPTIONS", "-Djava.io.tmpdir=#{testpath}"
    ENV.prepend "FLINK_LOG_DIR", testpath/"log"
    system libexec/"bin/start-cluster.sh"
    system bin/"flink", "run", "-p", "1",
           libexec/"examples/streaming/WordCount.jar", "--input", "input",
           "--output", "result/1"
    system libexec/"bin/stop-cluster.sh"
    assert_predicate testpath/"result/1", :exist?
    assert_equal expected, (testpath/"result/1").read
  end
end


text:
package plugins

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/toolkits/file"

	"github.com/leancloud/satori/agent/g"
	"github.com/leancloud/satori/common/model"
)

func safeClose(c chan struct{}) {
	defer func() { _ = recover() }()
	close(c)
}

func closed(c chan struct{}) bool {
	select {
	case <-c:
		return true
	default:
		return false
	}
}

type Plugin struct {
	FilePath string
	Step     int
	Params   []model.PluginParam

	proc       *exec.Cmd
	stdout     *bufio.Reader
	stdoutPipe io.ReadCloser
	stderr     *bufio.Reader
	stderrPipe io.ReadCloser
	finished   chan struct{}
	killSwitch chan struct{}
}

func (p *Plugin) Run() {
	debug := g.Config().Debug
	if debug {
		log.Printf("Starting plugin scheduler for %s/%d/%s", p.FilePath, p.Step, p.Params)
	}

	p.Kill()

	dur := p.Step
	if dur <= 0 {
		dur = 1
	}

	ticker := time.NewTicker(time.Duration(dur) * time.Second)

	go func() {
		s := make(chan struct{})
		p.killSwitch = s
		for {
			<-ticker.C
			if closed(s) {
				return
			}

			p.RunOnce()
		}
	}()
}

func (p *Plugin) reportFailure(subject string, desc string) {
	hostname, _ := g.Hostname()
	now := time.Now().Unix()
	m := []*model.MetricValue{
		&model.MetricValue{
			Endpoint:  hostname,
			Metric:    ".satori.agent.plugin." + subject,
			Value:     1,
			Step:      1,
			Timestamp: now,
			Tags: map[string]string{
				"file": p.FilePath,
			},
			Desc: desc,
		},
	}
	g.SendToTransfer(m)
}

func (p *Plugin) setupPipes() {
	p.stdoutPipe, _ = p.proc.StdoutPipe()
	p.stdout = bufio.NewReader(p.stdoutPipe)
	p.stderrPipe, _ = p.proc.StderrPipe()
	p.stderr = bufio.NewReader(p.stderrPipe)
	p.finished = make(chan struct{})
}

func (p *Plugin) teardownPipes() {
	if p.stdout != nil {
		_ = p.stdoutPipe.Close()
		p.stdoutPipe = nil
		p.stdout = nil
	}
	if p.stderr != nil {
		_ = p.stderrPipe.Close()
		p.stderrPipe = nil
		p.stderr = nil
	}
}

func (p *Plugin) sendStdout() {
	for {
		if p.stdout == nil {
			return
		}
		s, err := p.stdout.ReadBytes('\n')
		if err != nil {
			p.teardownPipes()
			safeClose(p.finished)
			return
		}
		var metrics []*model.MetricValue
		err = json.Unmarshal(s, &metrics)
		if err != nil {
			log.Printf("[ERROR] json.Unmarshal stdout of %s fail. error:%s stdout: \n%s\n", p.FilePath, err, s)
			p.reportFailure("bad-format", err.Error()+"\n\n"+string(s))
			p.teardownPipes()
			safeClose(p.finished)
			return
		}
		g.SendToTransfer(metrics)
	}
}

func (p *Plugin) sendStderr() {
	if p.stderr != nil {
		s, _ := ioutil.ReadAll(p.stderr)
		if len(s) > 0 {
			p.reportFailure("error", string(s))
		}
	}
}

func (p *Plugin) setupCommand() error {
	cfg := g.Config().Plugin
	fpath := filepath.Join(cfg.CheckoutPath, cfg.Subdir, p.FilePath)
	if !file.IsExist(fpath) {
		return fmt.Errorf("No such plugin: %s", p.FilePath)
	}

	cmd := exec.Command(fpath)
	if p.Params != nil {
		var stdin bytes.Buffer
		s, err := json.Marshal(p.Params)
		if err != nil {
			return fmt.Errorf("Error marshalling params for metric plugin: %s, %s", p.FilePath, err)
		}
		stdin.Write(s)
		cmd.Stdin = &stdin
	}
	p.proc = cmd
	return nil
}

func (p *Plugin) terminateCommand() {
	debug := g.Config().Debug
	if p.proc != nil {
		cmd := p.proc
		p.proc = nil
		p.teardownPipes()
		if err := cmd.Process.Kill(); err != nil && debug {
			log.Printf("Error killing proc: %s\n", err)
		}
		_ = cmd.Wait()
	}
}

func (p *Plugin) makeTimeoutChan() <-chan time.Time {
	if p.Step > 0 {
		// Periodically called plugin
		t := p.Step*1000 - 500
		return time.After(time.Duration(t) * time.Millisecond)
	}

	// Long running plugin
	return make(chan time.Time)
}

func (p *Plugin) RunOnce() {
	debug := g.Config().Debug

	if err := p.setupCommand(); err != nil {
		log.Printf("Can't setup plugin %s command: %s\n", p.FilePath, err)
		p.reportFailure("error", err.Error())
		return
	}
	p.setupPipes()
	if err := p.proc.Start(); err != nil {
		log.Printf("Can't start plugin %s process: %s\n", p.FilePath, err)
		p.reportFailure("error", err.Error())
		return
	}

	if debug {
		log.Println(p.FilePath, "running...")
	}

	go p.sendStdout()
	go p.sendStderr()

	select {
	case <-p.finished:
		break
	case <-p.makeTimeoutChan():
		log.Println("[INFO] Plugin timed out, terminating: ", p.FilePath)
		p.reportFailure("timeout", "")
	case <-p.killSwitch:
		log.Println("[INFO] Plugin was asked to terminate: ", p.FilePath)
	}
	p.terminateCommand()
}

func (p *Plugin) Kill() {
	if p.killSwitch != nil {
		debug := g.Config().Debug
		if debug {
			log.Printf("Stopping plugin scheduler for %s/%d/%s", p.FilePath, p.Step, p.Params)
		}
		close(p.killSwitch)
	}
}

var (
	PluginsLock = new(sync.RWMutex)
	Plugins     = make([]*Plugin, 0)
)

// key: sys/ntp/60_ntp.py
func getDirPlugins(relativePath string, L *[]*Plugin) {
	if relativePath == "" || relativePath == "_metric" {
		return
	}

	cfg := g.Config().Plugin
	dir := filepath.Join(cfg.CheckoutPath, cfg.Subdir, relativePath)

	if !file.IsExist(dir) || file.IsFile(dir) {
		return
	}

	fs, err := ioutil.ReadDir(dir)
	if err != nil {
		log.Println("can not list files under", dir)
		return
	}

	for _, f := range fs {
		if f.IsDir() {
			continue
		}

		filename := f.Name()
		arr := strings.Split(filename, "_")
		if len(arr) < 2 {
			continue
		}

		// filename should be: $step_$xx
		var step int
		step, err = strconv.Atoi(arr[0])
		if err != nil {
			continue
		}

		fpath := filepath.Join(relativePath, filename)
		plugin := &Plugin{
			FilePath: fpath,
			Step:     step,
			Params:   nil,
		}
		*L = append(*L, plugin)
	}
}

func getMetricPlugins(metrics []model.PluginParam, L *[]*Plugin) {
	type Group struct {
		Metric string
		Step   int
	}

	g := make(map[Group][]model.PluginParam)
	for _, p := range metrics {
		var metric string
		step := -1

		if m, ok := p["_metric"]; ok {
			if s, ok := m.(string); ok {
				metric = s
			}
		}

		if c, ok := p["_step"]; ok {
			if s, ok := c.(float64); ok {
				step = int(s)
			}
		}

		if metric == "" || step == -1 {
			continue
		}

		t := Group{metric, step}
		g[t] = append(g[t], p)
	}

	for k, v := range g {
		*L = append(*L, &Plugin{
			FilePath: filepath.Join("_metric", k.Metric),
			Step:     k.Step,
			Params:   v,
		})
	}
}

func RunPlugins(dirs []string, metrics []model.PluginParam) {
	L := make([]*Plugin, 0)

	for _, d := range dirs {
		getDirPlugins(d, &L)
	}

	getMetricPlugins(metrics, &L)

	debug := g.Config().Debug
	if debug {
		log.Printf("Reschedule for %d plugins", len(L))
	}

	PluginsLock.Lock()
	defer PluginsLock.Unlock()

	for _, p := range Plugins {
		p.Kill()
	}

	Plugins = L
	for _, p := range L {
		p.Run()
	}
}


text:
CREATE TABLE IF NOT EXISTS `PartyHistories` (
  `county_code` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `voter_id` bigint(18) unsigned NOT NULL,
  `party_affiliation` varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `export_date` date NOT NULL,
  PRIMARY KEY (`county_code`,`voter_id`,`party_affiliation`,`export_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


text:
@implementation UIView (DWAnimation)

-(DWAnimation *)dw_CreateAnimationWithKey:(NSString *)animationKey animationCreater:(void (^)(DWAnimationMaker *))animationCreater
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey animationCreater:animationCreater];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationKey:(NSString *)animationKey
                                         beginTime:(CGFloat)beginTime
                                          duration:(CGFloat)duration
                                        animations:(__kindof NSArray<CAAnimation *> *)animations
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration animations:animations];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationType:(DWAnimationType)animationType
                                       animationKey:(NSString *)animationKey
                                          beginTime:(CGFloat)beginTime
                                             values:(NSArray *)values
                                      timeIntervals:(NSArray *)timeIntervals
                                         transition:(BOOL)transition
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationType:animationType animationKey:animationKey beginTime:beginTime values:values timeIntervals:timeIntervals transition:transition];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration bezierPath:(UIBezierPath *)bezierPath autoRotate:(BOOL)autoRotate
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration bezierPath:bezierPath autoRotate:autoRotate];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration arcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise autoRotate:(BOOL)autoRotate
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration arcCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:clockwise autoRotate:autoRotate];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationKey:(NSString *)animationKey springingType:(DWAnimationSpringType)springingType beginTime:(CGFloat)beginTime fromValue:(id)fromValue toValue:(id)toValue mass:(CGFloat)mass stiffness:(CGFloat)stiffness damping:(CGFloat)damping initialVelocity:(CGFloat)initialVelocity
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey springingType:springingType beginTime:beginTime fromValue:fromValue toValue:toValue mass:mass stiffness:stiffness damping:damping initialVelocity:initialVelocity];
}

-(DWAnimation *)dw_CreateAnimationWithKeyPath:(NSString *)keyPath animationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration fromValue:(id)fromValue toValue:(id)toValue timingFunctionName:(NSString *)timingFunctionName
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer keyPath:keyPath animationKey:animationKey beginTime:beginTime duration:duration fromValue:fromValue toValue:toValue timingFunctionName:timingFunctionName];
}

-(DWAnimation *)dw_CreateAnimationWithAnimationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration rotateStartAngle:(CGFloat)startAngle rotateEndAngle:(CGFloat)endAngle rotateAxis:(Axis)rotateAxis deep:(CGFloat)deep
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration rotateStartAngle:startAngle rotateEndAngle:endAngle rotateAxis:rotateAxis deep:deep];
}

-(DWAnimation *)dw_CreateAnimationWithLayer:(CALayer *)layer animationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration rotateStartAngle:(CGFloat)startAngle rotateEndAngle:(CGFloat)endAngle simulateChangeAnchor:(CGPoint)anchor
{
    return [[DWAnimation alloc] initAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration rotateStartAngle:startAngle rotateEndAngle:endAngle simulateChangeAnchor:anchor];
}

-(DWAnimation *)dw_CreateResetAnimationWithAnimationKey:(NSString *)animationKey beginTime:(CGFloat)beginTime duration:(CGFloat)duration
{
    return [DWAnimation createResetAnimationWithLayer:self.layer animationKey:animationKey beginTime:beginTime duration:duration];
}

+(void)dw_StartAnimations:(__kindof NSArray<DWAnimation *> *)animations playMode:(DWAnimationPlayMode)playMode
{
    [DWAnimationManager startAnimations:animations playMode:playMode];
}
@end


text:
package org.mccandless.minotaur

import org.scalatest.matchers.{BeMatcher, MatchResult, Matcher}
import org.scalatest.words.ResultOfNotWordForAny

trait TermMatchers {

  /**
    * Matches when the left (actual value) is a [[Term]].
    * @param expectedTerm
    */
  class AlphaEquivalenceMatcher(expectedTerm: Term) extends Matcher[Term] {

    override def apply(left: Term) = {
      MatchResult(
        left.isAlphaEquivalentTo(expectedTerm),
        s"""$left was not alpha-equivalent to $expectedTerm""",
        s"""$left was alpha-equivalent to $expectedTerm"""
      )
    }
  }

  /**
    * Matches when the left (actual value) is a [[DeBruijnTerm]].
    *
    * @param expectedTerm
    */
  class DeBruijnAlphaEquivalenceMatcher(expectedTerm: Term) extends Matcher[DeBruijnTerm] {

    override def apply(left: DeBruijnTerm) = {
      MatchResult(
        left == expectedTerm.toDeBruijn,
        s"""$left was not alpha-equivalent to $expectedTerm""",
        s"""$left was alpha-equivalent to $expectedTerm"""
      )
    }
  }

  // TODO think about some nicer syntax here. =𝛂= ?
  def beAlphaEquivalentTo(expectedTerm: Term) = new AlphaEquivalenceMatcher(expectedTerm)

  implicit class NegatedAlphaEquivalenceMatcher[T <: Term](t: ResultOfNotWordForAny[T]) {
    def beAlphaEquivalentTo(expectedTerm: Term) = {
      this.t be BeMatcher[Term] {
        left => MatchResult(!left.isAlphaEquivalentTo(expectedTerm), "", "")
      }
    }
  }
}

object TermMatchers extends TermMatchers