text:
/*
    Indicator Categories are things like:
        Population or
        Income or
        Property Prices
*/

create table indicator_categories
(
    category citext primary key,
    description text,
    inserted timestamp not null default now(),
    updated timestamp
);

create trigger indicator_categories_set_updated_column
before update
on indicator_categories
for each row
execute procedure set_updated_column();

insert into indicator_categories
(category)
values
('Population'),
('Income');

/* Let's store what type of value an indicator keeps track
   of so we know how to format it (meaning, is it a number
   or a currency, etc)
*/
create table indicator_value_formats
(
    format citext primary key,
    description text,
    inserted timestamp not null default now(),
    updated timestamp
);

create trigger indicator_value_formats_set_updated_column
before update
on indicator_value_formats
for each row
execute procedure set_updated_column();

insert into indicator_value_formats
(format)
values
('number'),
('currency'),
('percent');

/* Indicators or Variables are what we're measuring.
   They're part of a greater category -- so we
   might have something like total-population which is
   part of Population, or median income which is part
   of the income category */
create table indicators
(
    indicator_uuid uuid not null default uuid_generate_v4() primary key,
    title citext unique,

    pretty_label citext,

    description text,

    indicator_value_format citext not null default 'number'
    references indicator_value_formats (format),

    indicator_category citext not null
    references indicator_categories (category),

    inserted timestamp not null default now(),
    updated timestamp
);

create trigger indicators_set_updated_column
before update
on indicators
for each row
execute procedure set_updated_column();

/* Indicators relate to each other --

   might want to rethink this, but for now,
   let's do a table of indicator ratios

   where we set a numerator and denominator
   from our list of indicators */

create table indicator_ratios
(
    indicator_numerator uuid not null
    references indicators (indicator_uuid),

    indicator_denominator uuid not null
    references indicators (indicator_uuid),

    primary key (indicator_numerator, indicator_denominator),

    inserted timestamp not null default now(),
    updated timestamp

);

create trigger indicator_ratios_set_updated_column
before update
on indicator_ratios
for each row
execute procedure set_updated_column();

/* We need to set up some geographies or places.

   Indicators are good as they give us a data point,
   but we also need to link these data points
   to specific places.

   These places should also be mappable
*/

/* Place types are like state, country, etc */
create table location_types
(
    location_type citext not null primary key,

    description text,

    contained_in citext
    references location_types (location_type),

    inserted timestamp not null default now(),
    updated timestamp
);

create trigger location_types_set_updated_column
before update
on location_types
for each row
execute procedure set_updated_column();

insert into location_types
(location_type, contained_in)
values
('county', null),
('city', 'county'),
('neighborhood', 'city'),
('community development corporation', 'city');

/* This is an actual place */
create table locations
(
    location_uuid uuid primary key default uuid_generate_v4(),

    title citext not null,

    description text,

    location_type citext not null
    references location_types(location_type),

    /* Do we want to store the map polygon here? */

    location_shape geometry(MultiPolygon, 4326),

    location_shape_json json,

    display_me boolean not null default true,

    inserted timestamp not null default now(),
    updated timestamp

);

create trigger location_set_updated_column
before update
on locations
for each row
execute procedure set_updated_column();

/* So we don't have to return a geometry to the HTML / frontend
   let's set up a trigger to transform geometry multipolygon
   into a more easily readable json shape object */
create or replace function set_location_shape_json ()
returns trigger
as
$$

begin
    new.location_shape_json:= ST_AsGeoJSON(new.location_shape);
    return new;
end;
$$
language plpgsql;

create trigger locations_setlocation_shape_json
before insert or update
on locations
for each row
execute procedure set_location_shape_json();

/* For each indicator, we can have values that relate to
   a point in time and a specific place. We should
   record  */


text:
// © Alexander Kozlenko. Licensed under the MIT License.

#pragma warning disable CA1720

namespace Anemonis.JsonRpc
{
    /// Represents JSON-RPC message identifier type.
    public enum JsonRpcIdType
    {
        /// Undefined JSON-RPC message identifier.
        None = 0x00,

        /// JSON-RPC message identifier of string type.
        String = 0x01,

        /// JSON-RPC message identifier of integer type.
        Integer = 0x02,

        /// JSON-RPC message identifier of float type.
        Float = 0x03
    }
}

#pragma warning restore CA1720

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="ru" flag="ru" title="Russian">
    <string_add name="_bx_timeline_reactions"><![CDATA[Лента - Реакции]]></string_add>
	<string_add name="_bx_timeline_option_enable_jump_to_switcher"><![CDATA[Показывать переключатель 'Перейти к']]></string_add>
</resources>


text:
/*

package org.apache.taverna.workbench.file.impl;

import static java.awt.GraphicsEnvironment.isHeadless;
import static java.util.Collections.singleton;
import static javax.swing.SwingUtilities.invokeAndWait;
import static javax.swing.SwingUtilities.isEventDispatchThread;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.swing.filechooser.FileFilter;

import org.apache.taverna.lang.observer.MultiCaster;
import org.apache.taverna.lang.observer.Observable;
import org.apache.taverna.lang.observer.Observer;
import org.apache.taverna.workbench.edits.EditManager;
import org.apache.taverna.workbench.edits.EditManager.AbstractDataflowEditEvent;
import org.apache.taverna.workbench.edits.EditManager.EditManagerEvent;
import org.apache.taverna.workbench.file.DataflowInfo;
import org.apache.taverna.workbench.file.DataflowPersistenceHandler;
import org.apache.taverna.workbench.file.FileManager;
import org.apache.taverna.workbench.file.FileType;
import org.apache.taverna.workbench.file.events.ClosedDataflowEvent;
import org.apache.taverna.workbench.file.events.ClosingDataflowEvent;
import org.apache.taverna.workbench.file.events.FileManagerEvent;
import org.apache.taverna.workbench.file.events.OpenedDataflowEvent;
import org.apache.taverna.workbench.file.events.SavedDataflowEvent;
import org.apache.taverna.workbench.file.events.SetCurrentDataflowEvent;
import org.apache.taverna.workbench.file.exceptions.OpenException;
import org.apache.taverna.workbench.file.exceptions.OverwriteException;
import org.apache.taverna.workbench.file.exceptions.SaveException;
import org.apache.taverna.workbench.file.exceptions.UnsavedException;

import org.apache.log4j.Logger;

import org.apache.taverna.scufl2.api.common.Scufl2Tools;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;
import org.apache.taverna.scufl2.api.core.Workflow;
import org.apache.taverna.scufl2.api.profiles.Profile;

/**
 * Implementation of {@link FileManager}
 *
 * @author Stian Soiland-Reyes
 */
public class FileManagerImpl implements FileManager {
	private static Logger logger = Logger.getLogger(FileManagerImpl.class);
	private static int nameIndex = 1;

	/**
	 * The last blank workflowBundle created using #newDataflow() until it has
	 * been changed - when this variable will be set to null again. Used to
	 * automatically close unmodified blank workflowBundles on open.
	 */
	private WorkflowBundle blankWorkflowBundle = null;
	@SuppressWarnings("unused")
	private EditManager editManager;
	private EditManagerObserver editManagerObserver = new EditManagerObserver();
	protected MultiCaster<FileManagerEvent> observers = new MultiCaster<>(this);
	/**
	 * Ordered list of open WorkflowBundle
	 */
	private LinkedHashMap<WorkflowBundle, OpenDataflowInfo> openDataflowInfos = new LinkedHashMap<>();
	private DataflowPersistenceHandlerRegistry dataflowPersistenceHandlerRegistry;
	private Scufl2Tools scufl2Tools = new Scufl2Tools();
	private WorkflowBundle currentWorkflowBundle;

	public DataflowPersistenceHandlerRegistry getPersistanceHandlerRegistry() {
		return dataflowPersistenceHandlerRegistry;
	}

	public FileManagerImpl(EditManager editManager) {
		this.editManager = editManager;
		editManager.addObserver(editManagerObserver);
	}

	/**
	 * Add an observer to be notified of {@link FileManagerEvent}s, such as
	 * {@link OpenedDataflowEvent} and {@link SavedDataflowEvent}.
	 *
	 * {@inheritDoc}
	 */
	@Override
	public void addObserver(Observer<FileManagerEvent> observer) {
		observers.addObserver(observer);
	}

	@Override
	public boolean canSaveWithoutDestination(WorkflowBundle workflowBundle) {
		OpenDataflowInfo dataflowInfo = getOpenDataflowInfo(workflowBundle);
		if (dataflowInfo.getSource() == null)
			return false;
		Set<?> handlers = getPersistanceHandlerRegistry()
				.getSaveHandlersForType(
						dataflowInfo.getFileType(),
						dataflowInfo.getDataflowInfo().getCanonicalSource()
								.getClass());
		return !handlers.isEmpty();
	}

	@Override
	public boolean closeDataflow(WorkflowBundle workflowBundle,
			boolean failOnUnsaved) throws UnsavedException {
		if (workflowBundle == null)
			throw new NullPointerException("Dataflow can't be null");
		ClosingDataflowEvent message = new ClosingDataflowEvent(workflowBundle);
		observers.notify(message);
		if (message.isAbortClose())
			return false;
		if ((failOnUnsaved && getOpenDataflowInfo(workflowBundle).isChanged()))
			throw new UnsavedException(workflowBundle);
		if (workflowBundle.equals(getCurrentDataflow())) {
			// We'll need to change current workflowBundle
			// Find best candidate to the left or right
			List<WorkflowBundle> workflowBundles = getOpenDataflows();
			int openIndex = workflowBundles.indexOf(workflowBundle);
			if (openIndex == -1)
				throw new IllegalArgumentException("Workflow was not opened "
						+ workflowBundle);

			if (openIndex > 0)
				setCurrentDataflow(workflowBundles.get(openIndex - 1));
			else if (openIndex == 0 && workflowBundles.size() > 1)
				setCurrentDataflow(workflowBundles.get(1));
			else
				// If it was the last one, start a new, empty workflowBundle
				newDataflow();
		}
		if (workflowBundle == blankWorkflowBundle)
			blankWorkflowBundle = null;
		openDataflowInfos.remove(workflowBundle);
		observers.notify(new ClosedDataflowEvent(workflowBundle));
		return true;
	}

	@Override
	public WorkflowBundle getCurrentDataflow() {
		return currentWorkflowBundle;
	}

	@Override
	public WorkflowBundle getDataflowBySource(Object source) {
		for (Entry<WorkflowBundle, OpenDataflowInfo> infoEntry : openDataflowInfos
				.entrySet()) {
			OpenDataflowInfo info = infoEntry.getValue();
			if (source.equals(info.getSource()))
				return infoEntry.getKey();
		}
		// Not found
		return null;
	}

	@Override
	public String getDataflowName(WorkflowBundle workflowBundle) {
		Object source = null;
		if (isDataflowOpen(workflowBundle))
			source = getDataflowSource(workflowBundle);
		// Fallback
		String name;
		Workflow workflow = workflowBundle.getMainWorkflow();
		if (workflow != null)
			name = workflow.getName();
		else
			name = workflowBundle.getName();
		if (source == null)
			return name;
		if (source instanceof File)
			return ((File) source).getAbsolutePath();
		else if (source instanceof URL)
			return source.toString();

		// Check if it has implemented a toString() method
		Method toStringMethod = null;
		Method toStringMethodFromObject = null;
		try {
			toStringMethod = source.getClass().getMethod("toString");
			toStringMethodFromObject = Object.class.getMethod("toString");
		} catch (Exception e) {
			throw new IllegalStateException(
					"Source did not implement Object.toString() " + source);
		}
		if (!toStringMethod.equals(toStringMethodFromObject))
			return source.toString();
		return name;
	}

	@Override
	public String getDefaultWorkflowName() {
		return "Workflow" + (nameIndex++);
	}

	@Override
	public Object getDataflowSource(WorkflowBundle workflowBundle) {
		return getOpenDataflowInfo(workflowBundle).getSource();
	}

	@Override
	public FileType getDataflowType(WorkflowBundle workflowBundle) {
		return getOpenDataflowInfo(workflowBundle).getFileType();
	}

	@Override
	public List<Observer<FileManagerEvent>> getObservers() {
		return observers.getObservers();
	}

	/**
	 * Get the {@link OpenDataflowInfo} for the given WorkflowBundle
	 *
	 * @throws NullPointerException
	 *             if the WorkflowBundle was null
	 * @throws IllegalArgumentException
	 *             if the WorkflowBundle was not open.
	 * @param workflowBundle
	 *            WorkflowBundle which information is to be found
	 * @return The {@link OpenDataflowInfo} describing the WorkflowBundle
	 */
	protected synchronized OpenDataflowInfo getOpenDataflowInfo(
			WorkflowBundle workflowBundle) {
		if (workflowBundle == null)
			throw new NullPointerException("Dataflow can't be null");
		OpenDataflowInfo info = openDataflowInfos.get(workflowBundle);
		if (info == null)
			throw new IllegalArgumentException("Workflow was not opened "
					+ workflowBundle);
		return info;
	}

	@Override
	public List<WorkflowBundle> getOpenDataflows() {
		return new ArrayList<>(openDataflowInfos.keySet());
	}

	@Override
	public List<FileFilter> getOpenFileFilters() {
		List<FileFilter> fileFilters = new ArrayList<>();

		Set<FileType> fileTypes = getPersistanceHandlerRegistry()
				.getOpenFileTypes();
		if (!fileTypes.isEmpty())
			fileFilters.add(new MultipleFileTypes(fileTypes,
					"All supported workflows"));
		for (FileType fileType : fileTypes)
			fileFilters.add(new FileTypeFileFilter(fileType));
		return fileFilters;
	}

	@Override
	public List<FileFilter> getOpenFileFilters(Class<?> sourceClass) {
		List<FileFilter> fileFilters = new ArrayList<>();
		for (FileType fileType : getPersistanceHandlerRegistry()
				.getOpenFileTypesFor(sourceClass))
			fileFilters.add(new FileTypeFileFilter(fileType));
		return fileFilters;
	}

	@Override
	public List<FileFilter> getSaveFileFilters() {
		List<FileFilter> fileFilters = new ArrayList<>();
		for (FileType fileType : getPersistanceHandlerRegistry()
				.getSaveFileTypes())
			fileFilters.add(new FileTypeFileFilter(fileType));
		return fileFilters;
	}

	@Override
	public List<FileFilter> getSaveFileFilters(Class<?> destinationClass) {
		List<FileFilter> fileFilters = new ArrayList<>();
		for (FileType fileType : getPersistanceHandlerRegistry()
				.getSaveFileTypesFor(destinationClass))
			fileFilters.add(new FileTypeFileFilter(fileType));
		return fileFilters;
	}

	@Override
	public boolean isDataflowChanged(WorkflowBundle workflowBundle) {
		return getOpenDataflowInfo(workflowBundle).isChanged();
	}

	@Override
	public boolean isDataflowOpen(WorkflowBundle workflowBundle) {
		return openDataflowInfos.containsKey(workflowBundle);
	}

	@Override
	public WorkflowBundle newDataflow() {
		WorkflowBundle workflowBundle = new WorkflowBundle();
		workflowBundle.setMainWorkflow(new Workflow());
		workflowBundle.getMainWorkflow().setName(getDefaultWorkflowName());
		workflowBundle.setMainProfile(new Profile());
		scufl2Tools.setParents(workflowBundle);
		blankWorkflowBundle = null;
		openDataflowInternal(workflowBundle);
		blankWorkflowBundle = workflowBundle;
		observers.notify(new OpenedDataflowEvent(workflowBundle));
		return workflowBundle;
	}

	@Override
	public void openDataflow(WorkflowBundle workflowBundle) {
		openDataflowInternal(workflowBundle);
		observers.notify(new OpenedDataflowEvent(workflowBundle));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public WorkflowBundle openDataflow(FileType fileType, Object source)
			throws OpenException {
		if (isHeadless())
			return performOpenDataflow(fileType, source);

		OpenDataflowRunnable r = new OpenDataflowRunnable(this, fileType,
				source);
		if (isEventDispatchThread()) {
			r.run();
		} else
			try {
				invokeAndWait(r);
			} catch (InterruptedException | InvocationTargetException e) {
				throw new OpenException("Opening was interrupted", e);
			}
		OpenException thrownException = r.getException();
		if (thrownException != null)
			throw thrownException;
		return r.getDataflow();
	}

	public WorkflowBundle performOpenDataflow(FileType fileType, Object source)
			throws OpenException {
		DataflowInfo dataflowInfo;
		WorkflowBundle workflowBundle;
		dataflowInfo = openDataflowSilently(fileType, source);
		workflowBundle = dataflowInfo.getDataflow();
		openDataflowInternal(workflowBundle);
		getOpenDataflowInfo(workflowBundle).setOpenedFrom(dataflowInfo);
		observers.notify(new OpenedDataflowEvent(workflowBundle));
		return workflowBundle;
	}

	@Override
	public DataflowInfo openDataflowSilently(FileType fileType, Object source)
			throws OpenException {
		Set<DataflowPersistenceHandler> handlers;
		Class<? extends Object> sourceClass = source.getClass();

		boolean unknownFileType = (fileType == null);
		if (unknownFileType)
			handlers = getPersistanceHandlerRegistry().getOpenHandlersFor(
					sourceClass);
		else
			handlers = getPersistanceHandlerRegistry().getOpenHandlersFor(
					fileType, sourceClass);
		if (handlers.isEmpty())
			throw new OpenException("Unsupported file type or class "
					+ fileType + " " + sourceClass);

		Throwable lastException = null;
		for (DataflowPersistenceHandler handler : handlers) {
			Collection<FileType> fileTypes;
			if (unknownFileType)
				fileTypes = handler.getOpenFileTypes();
			else
				fileTypes = singleton(fileType);
			for (FileType candidateFileType : fileTypes) {
				if (unknownFileType && (source instanceof File))
					/*
					 * If source is file but fileType was not explicitly set
					 * from the open workflow dialog - check the file extension
					 * and decide which handler to use based on that (so that we
					 * do not loop though all handlers)
					 */
					if (!((File) source).getPath().endsWith(
							candidateFileType.getExtension()))
						continue;

				try {
					DataflowInfo openDataflow = handler.openDataflow(
							candidateFileType, source);
					WorkflowBundle workflowBundle = openDataflow.getDataflow();
					logger.info("Loaded workflow: " + workflowBundle.getName()
							+ " " + workflowBundle.getGlobalBaseURI()
							+ " from " + source + " using " + handler);
					return openDataflow;
				} catch (OpenException ex) {
					logger.warn("Could not open workflow " + source + " using "
							+ handler + " of type " + candidateFileType);
					lastException = ex;
				}
			}
		}
		throw new OpenException("Could not open workflow " + source + "\n",
				lastException);
	}

	/**
	 * Mark the WorkflowBundle as opened, and close the blank WorkflowBundle if
	 * needed.
	 *
	 * @param workflowBundle
	 *            WorkflowBundle that has been opened
	 */
	protected void openDataflowInternal(WorkflowBundle workflowBundle) {
		if (workflowBundle == null)
			throw new NullPointerException("Dataflow can't be null");
		if (isDataflowOpen(workflowBundle))
			throw new IllegalArgumentException("Workflow is already open: "
					+ workflowBundle);

		openDataflowInfos.put(workflowBundle, new OpenDataflowInfo());
		setCurrentDataflow(workflowBundle);
		if (openDataflowInfos.size() == 2 && blankWorkflowBundle != null)
			/*
			 * Behave like a word processor and close the blank WorkflowBundle
			 * when another workflow has been opened
			 */
			try {
				closeDataflow(blankWorkflowBundle, true);
			} catch (UnsavedException e) {
				logger.error("Blank workflow was modified "
						+ "and could not be closed");
			}
	}

	@Override
	public void removeObserver(Observer<FileManagerEvent> observer) {
		observers.removeObserver(observer);
	}

	@Override
	public void saveDataflow(WorkflowBundle workflowBundle,
			boolean failOnOverwrite) throws SaveException {
		if (workflowBundle == null)
			throw new NullPointerException("Dataflow can't be null");
		OpenDataflowInfo lastSave = getOpenDataflowInfo(workflowBundle);
		if (lastSave.getSource() == null)
			throw new SaveException("Can't save without source "
					+ workflowBundle);
		saveDataflow(workflowBundle, lastSave.getFileType(),
				lastSave.getSource(), failOnOverwrite);
	}

	@Override
	public void saveDataflow(WorkflowBundle workflowBundle, FileType fileType,
			Object destination, boolean failOnOverwrite) throws SaveException {
		DataflowInfo savedDataflow = saveDataflowSilently(workflowBundle,
				fileType, destination, failOnOverwrite);
		getOpenDataflowInfo(workflowBundle).setSavedTo(savedDataflow);
		observers.notify(new SavedDataflowEvent(workflowBundle));
	}

	@Override
	public DataflowInfo saveDataflowSilently(WorkflowBundle workflowBundle,
			FileType fileType, Object destination, boolean failOnOverwrite)
			throws SaveException, OverwriteException {
		Set<DataflowPersistenceHandler> handlers;

		Class<? extends Object> destinationClass = destination.getClass();
		if (fileType != null)
			handlers = getPersistanceHandlerRegistry().getSaveHandlersForType(
					fileType, destinationClass);
		else
			handlers = getPersistanceHandlerRegistry().getSaveHandlersFor(
					destinationClass);

		SaveException lastException = null;
		for (DataflowPersistenceHandler handler : handlers) {
			if (failOnOverwrite) {
				OpenDataflowInfo openDataflowInfo = getOpenDataflowInfo(workflowBundle);
				if (handler.wouldOverwriteDataflow(workflowBundle, fileType,
						destination, openDataflowInfo.getDataflowInfo()))
					throw new OverwriteException(destination);
			}
			try {
				DataflowInfo savedDataflow = handler.saveDataflow(
						workflowBundle, fileType, destination);
				savedDataflow.getDataflow();
				logger.info("Saved workflow: " + workflowBundle.getName() + " "
						+ workflowBundle.getGlobalBaseURI() + " to "
						+ savedDataflow.getCanonicalSource() + " using "
						+ handler);
				return savedDataflow;
			} catch (SaveException ex) {
				logger.warn("Could not save to " + destination + " using "
						+ handler);
				lastException = ex;
			}
		}

		if (lastException == null)
			throw new SaveException("Unsupported file type or class "
					+ fileType + " " + destinationClass);
		throw new SaveException("Could not save to " + destination + ":\n"
				+ lastException.getLocalizedMessage(), lastException);
	}

	@Override
	public void setCurrentDataflow(WorkflowBundle workflowBundle) {
		setCurrentDataflow(workflowBundle, false);
	}

	@Override
	public void setCurrentDataflow(WorkflowBundle workflowBundle,
			boolean openIfNeeded) {
		currentWorkflowBundle = workflowBundle;
		if (!isDataflowOpen(workflowBundle)) {
			if (!openIfNeeded)
				throw new IllegalArgumentException("Workflow is not open: "
						+ workflowBundle);
			openDataflow(workflowBundle);
			return;
		}
		observers.notify(new SetCurrentDataflowEvent(workflowBundle));
	}

	@Override
	public void setDataflowChanged(WorkflowBundle workflowBundle,
			boolean isChanged) {
		getOpenDataflowInfo(workflowBundle).setIsChanged(isChanged);
		if (blankWorkflowBundle == workflowBundle)
			blankWorkflowBundle = null;
	}

	@Override
	public Object getCanonical(Object source) throws IllegalArgumentException,
			URISyntaxException, IOException {
		Object canonicalSource = source;

		if (source instanceof URL) {
			URL url = ((URL) source);
			if (url.getProtocol().equalsIgnoreCase("file"))
				canonicalSource = new File(url.toURI());
		}

		if (canonicalSource instanceof File)
			canonicalSource = ((File) canonicalSource).getCanonicalFile();
		return canonicalSource;
	}

	public void setDataflowPersistenceHandlerRegistry(
			DataflowPersistenceHandlerRegistry dataflowPersistenceHandlerRegistry) {
		this.dataflowPersistenceHandlerRegistry = dataflowPersistenceHandlerRegistry;
	}

	/**
	 * Observe the {@link EditManager} for changes to open workflowBundles. A
	 * change of an open workflow would set it as changed using
	 * {@link FileManagerImpl#setDataflowChanged(Dataflow, boolean)}.
	 *
	 * @author Stian Soiland-Reyes
	 *
	 */
	private final class EditManagerObserver implements
			Observer<EditManagerEvent> {
		@Override
		public void notify(Observable<EditManagerEvent> sender,
				EditManagerEvent message) throws Exception {
			if (message instanceof AbstractDataflowEditEvent) {
				AbstractDataflowEditEvent dataflowEdit = (AbstractDataflowEditEvent) message;
				WorkflowBundle workflowBundle = dataflowEdit.getDataFlow();
				/**
				 * TODO: on undo/redo - keep last event or similar to determine
				 * if workflow was saved before. See
				 * FileManagerTest#isChangedWithUndo().
				 */
				setDataflowChanged(workflowBundle, true);
			}
		}
	}
}


text:
package org.robolectric;

import com.example.objects.AnyObject;
import com.example.objects.Dummy;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.robolectric.annotation.processing.shadows.ShadowAnything;
import org.robolectric.annotation.processing.shadows.ShadowDummy;
import org.robolectric.internal.ShadowProvider;
import org.robolectric.shadow.api.Shadow;

@Generated("org.robolectric.annotation.processing.RobolectricProcessor")
@SuppressWarnings({"unchecked","deprecation"})
public class Shadows implements ShadowProvider {
  private static final Map<String, String> SHADOW_MAP = new HashMap<>(2);

  static {
    SHADOW_MAP.put("com.example.objects.AnyObject", "org.robolectric.annotation.processing.shadows.ShadowAnything");
    SHADOW_MAP.put("com.example.objects.Dummy", "org.robolectric.annotation.processing.shadows.ShadowDummy");
  }

  public static ShadowAnything shadowOf(AnyObject actual) {
    return (ShadowAnything) Shadow.extract(actual);
  }

  public static ShadowDummy shadowOf(Dummy actual) {
    return (ShadowDummy) Shadow.extract(actual);
  }

  public void reset() {
    ShadowAnything.anotherResetter();
    ShadowDummy.resetter_method();
  }

  @Override
  public Map<String, String> getShadowMap() {
    return SHADOW_MAP;
  }

  @Override
  public String[] getProvidedPackageNames() {
    return new String[] {"com.example.objects"};
  }
}


text:
import unittest

class mediafile(object):
  """a mediafile (i know this description sucks)"""
  def __init__(self):
    super(mediafile, self).__init__()

  def write(self,filename):
    """write the file to the specified destination"""
    raise NotImplementedError

  def import_File(self,filename):
    """Import an existing file and add all available tracks to the object."""
    raise NotImplementedError

  def add_Chapters(self,chapterlist):
    """Provide a list of Podcast.Chapter Objects."""
    raise NotImplementedError

class mediafileTests(unittest.TestCase):
  def setUp(self):
    pass

if __name__ == '__main__':
  unittest.main()


text:
namespace solar {

	inline std::string build_string(const char* format, fmt::ArgList args) {
		return fmt::format(format, args);
	}

	FMT_VARIADIC(std::string, build_string, const char *)

	template<typename Con>
	std::string build_container_string(const Con& con) {
		std::stringstream ss;
		ss << "[ ";
		bool is_first = true;
		for (const auto& e : con) {
			if (!is_first) {
				ss << " , ";
			}
			is_first = false;
			ss << e;
		}
		ss << " ]";
		return ss.str();
	}

}


text:
module EmailSpec
  class EmailViewer
    extend Deliveries

    def self.save_and_open_all_raw_emails
      filename = tmp_email_filename

      File.open(filename, "w") do |f|
        all_emails.each do |m|
          f.write m.to_s
          f.write "\n" + '='*80 + "\n"
        end
      end

      open_in_text_editor(filename)
    end

    def self.save_and_open_all_html_emails
      all_emails.each_with_index do |m, index|
        if m.multipart? && html_part = m.parts.detect{ |p| p.content_type == 'text/html' }
          filename = tmp_email_filename("-#{index}.html")
          File.open(filename, "w") do |f|
            f.write m.parts[1].body
          end
          open_in_browser(filename)
        end
      end
    end

    def self.save_and_open_all_text_emails
      filename = tmp_email_filename

      File.open(filename, "w") do |f|
        all_emails.each do |m|
          if m.multipart? && text_part = m.parts.detect{ |p| p.content_type == 'text/plain' }
            m.ordered_each{|k,v| f.write "#{k}: #{v}\n" }
            f.write text_part.body
          else
            f.write m.to_s
          end
          f.write "\n" + '='*80 + "\n"
        end
      end

      open_in_text_editor(filename)
    end

    def self.save_and_open_email(mail)
      filename = tmp_email_filename

      File.open(filename, "w") do |f|
        f.write mail.to_s
      end

      open_in_text_editor(filename)
    end

    def self.save_and_open_email_attachments_list(mail)
      filename = tmp_email_filename

      File.open(filename, "w") do |f|
        mail.attachments.each_with_index do |attachment, index|
          info = "#{index + 1}:"
          info += "\n\tfilename: #{attachment.original_filename}"
          info += "\n\tcontent type: #{attachment.content_type}"
          info += "\n\tsize: #{attachment.size}"
          f.write info + "\n"
        end
      end

      open_in_text_editor(filename)
    end

    # TODO: use the launchy gem for this stuff...
    def self.open_in_text_editor(filename)
      Launchy.open(URI.parse("file://#{File.expand_path(filename)}"), :application => :editor)
    end

    def self.open_in_browser(filename)
      Launchy.open(URI.parse("file://#{File.expand_path(filename)}"))
    end

    def self.tmp_email_filename(extension = '.txt')
      "#{Rails.root}/tmp/email-#{Time.now.to_i}#{extension}"
    end
  end
end


text:
/*
 */
package org.apache.taverna.server.master.rest;
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

import static org.apache.taverna.server.master.rest.ContentTypes.ATOM;

import java.net.MalformedURLException;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.cxf.jaxrs.model.wadl.Description;
import org.apache.taverna.server.master.exceptions.FilesystemAccessException;
import org.apache.taverna.server.master.exceptions.NoDirectoryEntryException;
import org.apache.taverna.server.master.exceptions.NoUpdateException;

/**
 * A very stripped down ATOM feed for the interaction service.
 *
 * @author Donal Fellows
 */
public interface InteractionFeedREST {
	/**
	 * Get the feed document for this ATOM feed.
	 *
	 * @return The feed.
	 * @throws FilesystemAccessException
	 *             If we can't read from the feed directory.
	 * @throws NoDirectoryEntryException
	 *             If something changes things under our feet.
	 */
	@GET
	@Path("/")
	@Produces(ATOM)
	@Description("Get the feed document for this ATOM feed.")
	Feed getFeed() throws FilesystemAccessException, NoDirectoryEntryException;

	/**
	 * Adds an entry to this ATOM feed.
	 *
	 * @param entry
	 *            The entry to create.
	 * @return A redirect to the created entry.
	 * @throws MalformedURLException
	 *             If we have problems generating the URI of the entry.
	 * @throws FilesystemAccessException
	 *             If we can't create the feed entry file.
	 * @throws NoDirectoryEntryException
	 *             If things get changed under our feet.
	 * @throws NoUpdateException
	 *             If we don't have permission to change things relating to this
	 *             run.
	 */
	@POST
	@Path("/")
	@Consumes(ATOM)
	@Produces(ATOM)
	@Description("Adds an entry to this ATOM feed.")
	Response addEntry(Entry entry) throws MalformedURLException,
			FilesystemAccessException, NoDirectoryEntryException,
			NoUpdateException;

	/** Handles the OPTIONS request. */
	@OPTIONS
	@Path("/")
	@Description("Describes what HTTP operations are supported on the feed.")
	Response feedOptions();

	/**
	 * Gets the content of an entry in this ATOM feed.
	 *
	 * @param id
	 *            The ID of the entry to fetch.
	 * @return The entry contents.
	 * @throws FilesystemAccessException
	 *             If we have problems reading the entry.
	 * @throws NoDirectoryEntryException
	 *             If we can't find the entry to read.
	 */
	@GET
	@Path("{id}")
	@Produces(ATOM)
	@Description("Get the entry with a particular ID within this ATOM feed.")
	Entry getEntry(@PathParam("id") String id)
			throws FilesystemAccessException, NoDirectoryEntryException;

	/**
	 * Delete an entry from this ATOM feed.
	 *
	 * @param id
	 *            The ID of the entry to delete.
	 * @return A simple message. Not very important!
	 * @throws FilesystemAccessException
	 *             If we have problems deleting the entry.
	 * @throws NoDirectoryEntryException
	 *             If we can't find the entry to delete.
	 * @throws NoUpdateException
	 *             If we don't have permission to alter things relating to this
	 *             run.
	 */
	@DELETE
	@Path("{id}")
	@Produces("text/plain")
	@Description("Deletes an entry from this ATOM feed.")
	String deleteEntry(@PathParam("id") String id)
			throws FilesystemAccessException, NoDirectoryEntryException,
			NoUpdateException;

	/** Handles the OPTIONS request. */
	@OPTIONS
	@Path("{id}")
	@Description("Describes what HTTP operations are supported on an entry.")
	Response entryOptions(@PathParam("{id}") String id);
}


text:
insert into city(country, name, state, map) values ('Australia', 'Brisbane', 'Queensland', '-27.470933, 153.023502')
insert into hotel(city_id, name, address, zip) values (1, 'Conrad Treasury Place', 'William & George Streets', '4001')

-- Melbourne
insert into city(country, name, state, map) values ('Australia', 'Melbourne', 'Victoria', '-37.813187, 144.96298')
insert into hotel(city_id, name, address, zip) values (2, 'The Langham', '1 Southgate Ave, Southbank', '3006')

-- Sydney
insert into city(country, name, state, map) values ('Australia', 'Sydney', 'New South Wales', '-33.868901, 151.207091')
insert into hotel(city_id, name, address, zip) values (3, 'Swissotel', '68 Market Street', '2000')

-- =================================================================================================
-- CANADA

-- Montreal
insert into city(country, name, state, map) values ('Canada', 'Montreal', 'Quebec', '45.508889, -73.554167')
insert into hotel(city_id, name, address, zip) values (4, 'Ritz Carlton', '1228 Sherbrooke St', 'H3G1H6')

-- =================================================================================================
-- ISRAEL

-- Tel Aviv
insert into city(country, name, state, map) values ('Israel', 'Tel Aviv', '', '32.066157, 34.777821')
insert into hotel(city_id, name, address, zip) values (5, 'Hilton Tel Aviv', 'Independence Park', '63405')

-- =================================================================================================
-- JAPAN

-- Tokyo
insert into city(country, name, state, map) values ('Japan', 'Tokyo', '', '35.689488, 139.691706')
insert into hotel(city_id, name, address, zip) values (6, 'InterContinental Tokyo Bay', 'Takeshiba Pier', '105')

-- =================================================================================================
-- SPAIN

-- Barcelona
insert into city(country, name, state, map) values ('Spain', 'Barcelona', 'Catalunya', '41.387917, 2.169919')
insert into hotel(city_id, name, address, zip) values (7, 'Hilton Diagonal Mar', 'Passeig del Taulat 262-264', '08019')

-- =================================================================================================
-- SWITZERLAND

-- Neuchatel
insert into city(country, name, state, map) values ('Switzerland', 'Neuchatel', '', '46.992979, 6.931933')
insert into hotel(city_id, name, address, zip) values (8, 'Hotel Beaulac', ' Esplanade Leopold-Robert 2', '2000')

-- =================================================================================================
-- UNITED KINGDOM

-- Bath
insert into city(country, name, state, map) values ('UK', 'Bath', 'Somerset', '51.381428, -2.357454')
insert into hotel(city_id, name, address, zip) values (9, 'The Bath Priory Hotel', 'Weston Road', 'BA1 2XT')


text:
function INT = minus(INT1,INT2)
% vpi/minus: Subtracts two vpi objects, or one vpi and a constant
% usage: INT = INT1 - INT2;
%
% arguments:
%  INT,INT1,INT2 - vpi objects or scalars
%
%
%  See also: uminus, plus
%
%
%  Author: John D'Errico
%  e-mail: woodchips@rochester.rr.com
%  Release: 1.0
%  Release date: 1/19/09

% negate the second term, then add
INT = INT1 + uminus(INT2);


text:
(function() {
  "use strict";

  var linkGlobal = (typeof global  === 'undefined') ? this : global;
  var linkModule = (typeof exports === 'undefined') ? this : exports;

  var Slickback =
    linkModule.Slickback || linkGlobal.Slickback || require('../slickback'),
    use = Slickback.use;

  var imported = use(linkGlobal, [
      { symbol: '_', module: 'underscore' }
    ]),
    _ = imported._;

  var exportNamespace = Slickback;

  function choiceFormatter(row,cell,value,col,data) {
    var chosen = data.get(col.field); // why string?
    var choice = _.find(col.choices,function(choice) {
      // NOTE: using type coercion so element value="2" == column value: 2
      return (choice == chosen || (choice && (choice.value == chosen)));
    });
    return choice ? (choice.label || choice) :
      (typeof col.includeBlank === 'string' ? col.includeBlank : '');
  }

  exportNamespace.ChoiceFormatter = choiceFormatter;

}).call(this);


text:
package androidx.car.app.hardware.climate;

import androidx.annotation.NonNull;
import androidx.car.app.annotations.ExperimentalCarApi;
import androidx.car.app.hardware.common.CarZone;

import java.util.List;
import java.util.Set;

/**
 * Container class for information about the {@link
 * ClimateProfileRequest#FEATURE_HVAC_AUTO_RECIRCULATION} feature such as supported values for
 * the feature.
 */
@ExperimentalCarApi
public final class HvacAutoRecirculationProfile{

    @NonNull
    private final List<Set<CarZone>> mSupportedCarZoneSets;

    /**
     * Returns a list of supported zones in a car for the feature.
     */
    @NonNull
    public List<Set<CarZone>> getSupportedCarZoneSets() {
        return mSupportedCarZoneSets;
    }

    HvacAutoRecirculationProfile(Builder builder) {
        mSupportedCarZoneSets = builder.mSupportedCarZoneSets;
    }

    /** A builder for HvacAutoRecirculationProfile. */
    public static final class Builder {
        final List<Set<CarZone>> mSupportedCarZoneSets;

        /**
         * Creates an instance of builder.
         *
         * @param supportedCarZoneSets   a list of all car zones grouped together based on the bit
         *                            map of each area Id.
         */
        public Builder(@NonNull List<Set<CarZone>>  supportedCarZoneSets) {
            mSupportedCarZoneSets = supportedCarZoneSets;
        }

        /** Create a HvacAutoRecirculationProfile. */
        @NonNull
        public HvacAutoRecirculationProfile build() {
            return new HvacAutoRecirculationProfile(this);
        }
    }
}


text: DELETE FROM OPENMM_FOLDERS WHERE FOLDER_ID = ?


text:
const isDev = wx.getSystemInfoSync().platform === 'devtools';

const formatTime = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return (
        `${[year, month, day].map(formatNumber).join('/')
        } ${
            [hour, minute, second].map(formatNumber).join(':')}`
    );
};

const formatNumber = (n: number) => {
    const s = n.toString();

    return s[1] ? s : `0${s}`;
};

const whatType: IAnyObject = {};
const types = ['Array', 'Boolean', 'Date', 'Number', 'Object', 'RegExp', 'String', 'Error', 'Function', 'Promise'];

for (let i = 0, len = types.length; i < len; i++) {
    const c = types[i];

    whatType[`is${c}`] = ((type: string) => (arg: any) => Object.prototype.toString.call(arg) === `[object ${type}]`)(c);
}

const getUid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0;
    // eslint-disable-next-line no-mixed-operators
    const v = c === 'x' ? r : (r & 0x3 | 0x8);

    return v.toString(16);
});

/**
 * @description 截流函数
 * @param fn type:function 要被截留的函数
 * @param time type:numebr 函数调用间隔时间
 * @param ctx type:object 上下文this指向
 * @return function
 */
const throttle = (fn: (...params: any[]) => any, time = 200, ctx?: any) => {
    let previous: any = null;

    return function callback(this: any, ...reset: any[]) {
        console.log(ctx);
        const now = +new Date();
        const context = ctx || this;
        const args = reset;

        if (!previous) previous = now;
        const remaining = now - previous;

        if (time && (remaining >= time || remaining === 0)) {
            fn.apply(context, args);
            previous = now;
        }
    };
};

export {
    isDev,
    formatTime,
    formatNumber,
    whatType,
    getUid,
    throttle,
};


text:
<?php

namespace SastrawiTest\Morphology;

class InvalidAffixPairSpecificationTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->specification = new \Sastrawi\Morphology\InvalidAffixPairSpecification();
    }

    /**
     * Test contains invalid affix pair ber-i|di-an|ke-i|ke-kan|me-an|ter-an|per-an
     */
    public function testContainsInvalidAffixPair()
    {
        $this->assertFalse($this->specification->isSatisfiedBy('memberikan'));
        $this->assertFalse($this->specification->isSatisfiedBy('ketahui'));

        $this->assertTrue($this->specification->isSatisfiedBy('berjatuhi'));
        $this->assertTrue($this->specification->isSatisfiedBy('dipukulan'));
        $this->assertTrue($this->specification->isSatisfiedBy('ketiduri'));
        $this->assertTrue($this->specification->isSatisfiedBy('ketidurkan'));
        $this->assertTrue($this->specification->isSatisfiedBy('menduaan'));
        $this->assertTrue($this->specification->isSatisfiedBy('terduaan'));
        $this->assertTrue($this->specification->isSatisfiedBy('perkataan')); // wtf?
    }
}


text:
'use strict';

const minimist = require('minimist');
const redis = require('./lib/redis.js');
const logger = require('bunyan').createLogger({
    name: 'redis-distributed-messaging',
    level: 'trace'
});
const _ = require('underscore');
const os = require('os');
const async = require('async');

var argv = require('minimist')(process.argv.slice(2));
const MessageEmitter = require('./lib/message-emitter.js');
const MessageManager = require('./lib/message-manager.js');
const NodeManager = require('./lib/node-manager.js');
const clearErrorQueue = require('./lib/clear-error-queue.js')

let scope = {
    nodeList: [],
    nodeInfo: [],
    logger: logger
};

logger.info('app started', {pid: process.pid});

let publisher;
let subscriber;

scope.nodeName = `${os.hostname()}_${process.pid}`;

let messageEmitter = null;
let messageManager = null;
let nodeManager = null;

const initRedisConnections  = (callback) => {
    async.parallel({
        publisher: redis.getConnection.bind(null, 'publisher'),
        subscriber: redis.getConnection.bind(null,'subscriber')
    }, (error, result) => {
        scope.publisher = result.publisher;
        scope.subscriber = result.subscriber;
        callback(error);
    });
};

async.series([
    initRedisConnections,
    (callback) => {
         if(argv.getErrors) {
             logger.info('Start to get and clear errors queue...');
             clearErrorQueue(scope, () => {
                 logger.info('Error queue cleared, exit');
                 process.exit(0);
             })
        } else if(argv.flush) {
            logger.info('Clear node information, send kill message to other nodes..');
            scope.publisher.flushdb(callback);
            scope.publisher.publish('kill', JSON.stringify({node: scope.nodeName}));
        } else {
            callback(null);
        }
    },

    callback => {

        messageEmitter = new MessageEmitter(scope);
        messageManager = new MessageManager(scope);
        messageEmitter.subscribe({
            [`${scope.nodeName}:ping`] : message => messageManager.ping(message),
            [`${scope.nodeName}:message`] : message => messageManager.message(message),
            'newnode':  message => messageManager.newNode(message),
            'kill': message => messageManager.kill(message),
            'updatenodelist': message => messageManager.updateNodeList(message),
        }, callback)
    },

    callback => {
        nodeManager = new NodeManager(scope, messageEmitter);
        nodeManager.init(callback);
    },
    callback => {
        nodeManager.watchClosestNodeStatus();
    }
]);


text:
NS_ASSUME_NONNULL_BEGIN

@interface XZCollectionReusableView : UICollectionReusableView

@end

NS_ASSUME_NONNULL_END


text:
/*========== Coming Soon Background Image =========*/
.comingsoonVideo .app-content .coming-soon-content {
  z-index : 99;
}

.clockCard {
  float : right;
  border-radius : 0.50rem;
}

.comingsoonOne {
  background-image : url(../../../app-assets/images/backgrounds/bg-12.jpg);
  background-repeat : no-repeat;
  -webkit-background-size : cover;
          background-size : cover;
}

.getting-started {
  font-size : 2.4rem;
  border-radius : 60px;
  min-width : 360px;
}

.countdownFormat {
  font-size : 16px;
  padding-bottom : 0;
}

.socialIcon i {
  font-size : 28px;
  padding : 5px;
}

/*========== Coming Soon Flat Design =========*/
.clockFormat {
  border-radius : 60px;
}

.comingsoonFlat {
  background-image : url(../../../app-assets/images/backgrounds/bg-14.jpg);
  background-repeat : no-repeat;
  -webkit-background-size : cover;
          background-size : cover;
}


text:
package auth

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/dotcloud/docker/utils"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"strings"
)

// Where we store the config file
const CONFIGFILE = ".dockercfg"

// Only used for user auth + account creation
const INDEXSERVER = "https://index.docker.io/v1/"

//const INDEXSERVER = "https://indexstaging-docker.dotcloud.com/v1/"

var (
	ErrConfigFileMissing = errors.New("The Auth config file is missing")
)

type AuthConfig struct {
	Username      string `json:"username,omitempty"`
	Password      string `json:"password,omitempty"`
	Auth          string `json:"auth"`
	Email         string `json:"email"`
	ServerAddress string `json:"serveraddress,omitempty"`
}

type ConfigFile struct {
	Configs  map[string]AuthConfig `json:"configs,omitempty"`
	rootPath string
}

func IndexServerAddress() string {
	return INDEXSERVER
}

// create a base64 encoded auth string to store in config
func encodeAuth(authConfig *AuthConfig) string {
	authStr := authConfig.Username + ":" + authConfig.Password
	msg := []byte(authStr)
	encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
	base64.StdEncoding.Encode(encoded, msg)
	return string(encoded)
}

// decode the auth string
func decodeAuth(authStr string) (string, string, error) {
	decLen := base64.StdEncoding.DecodedLen(len(authStr))
	decoded := make([]byte, decLen)
	authByte := []byte(authStr)
	n, err := base64.StdEncoding.Decode(decoded, authByte)
	if err != nil {
		return "", "", err
	}
	if n > decLen {
		return "", "", fmt.Errorf("Something went wrong decoding auth config")
	}
	arr := strings.Split(string(decoded), ":")
	if len(arr) != 2 {
		return "", "", fmt.Errorf("Invalid auth configuration file")
	}
	password := strings.Trim(arr[1], "\x00")
	return arr[0], password, nil
}

// load up the auth config information and return values
// FIXME: use the internal golang config parser
func LoadConfig(rootPath string) (*ConfigFile, error) {
	configFile := ConfigFile{Configs: make(map[string]AuthConfig), rootPath: rootPath}
	confFile := path.Join(rootPath, CONFIGFILE)
	if _, err := os.Stat(confFile); err != nil {
		return &configFile, nil //missing file is not an error
	}
	b, err := ioutil.ReadFile(confFile)
	if err != nil {
		return &configFile, err
	}

	if err := json.Unmarshal(b, &configFile.Configs); err != nil {
		arr := strings.Split(string(b), "\n")
		if len(arr) < 2 {
			return &configFile, fmt.Errorf("The Auth config file is empty")
		}
		authConfig := AuthConfig{}
		origAuth := strings.Split(arr[0], " = ")
		if len(origAuth) != 2 {
			return &configFile, fmt.Errorf("Invalid Auth config file")
		}
		authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
		if err != nil {
			return &configFile, err
		}
		origEmail := strings.Split(arr[1], " = ")
		if len(origEmail) != 2 {
			return &configFile, fmt.Errorf("Invalid Auth config file")
		}
		authConfig.Email = origEmail[1]
		authConfig.ServerAddress = IndexServerAddress()
		configFile.Configs[IndexServerAddress()] = authConfig
	} else {
		for k, authConfig := range configFile.Configs {
			authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
			if err != nil {
				return &configFile, err
			}
			authConfig.Auth = ""
			configFile.Configs[k] = authConfig
			authConfig.ServerAddress = k
		}
	}
	return &configFile, nil
}

// save the auth config
func SaveConfig(configFile *ConfigFile) error {
	confFile := path.Join(configFile.rootPath, CONFIGFILE)
	if len(configFile.Configs) == 0 {
		os.Remove(confFile)
		return nil
	}

	configs := make(map[string]AuthConfig, len(configFile.Configs))
	for k, authConfig := range configFile.Configs {
		authCopy := authConfig

		authCopy.Auth = encodeAuth(&authCopy)
		authCopy.Username = ""
		authCopy.Password = ""
		authCopy.ServerAddress = ""
		configs[k] = authCopy
	}

	b, err := json.Marshal(configs)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(confFile, b, 0600)
	if err != nil {
		return err
	}
	return nil
}

// try to register/login to the registry server
func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, error) {
	client := &http.Client{}
	reqStatusCode := 0
	var status string
	var reqBody []byte

	serverAddress := authConfig.ServerAddress
	if serverAddress == "" {
		serverAddress = IndexServerAddress()
	}

	loginAgainstOfficialIndex := serverAddress == IndexServerAddress()

	// to avoid sending the server address to the server it should be removed before marshalled
	authCopy := *authConfig
	authCopy.ServerAddress = ""

	jsonBody, err := json.Marshal(authCopy)
	if err != nil {
		return "", fmt.Errorf("Config Error: %s", err)
	}

	// using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
	b := strings.NewReader(string(jsonBody))
	req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b)
	if err != nil {
		return "", fmt.Errorf("Server Error: %s", err)
	}
	reqStatusCode = req1.StatusCode
	defer req1.Body.Close()
	reqBody, err = ioutil.ReadAll(req1.Body)
	if err != nil {
		return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
	}

	if reqStatusCode == 201 {
		if loginAgainstOfficialIndex {
			status = "Account created. Please use the confirmation link we sent" +
				" to your e-mail to activate it."
		} else {
			status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it."
		}
	} else if reqStatusCode == 403 {
		if loginAgainstOfficialIndex {
			return "", fmt.Errorf("Login: Your account hasn't been activated. " +
				"Please check your e-mail for a confirmation link.")
		}
		return "", fmt.Errorf("Login: Your account hasn't been activated. " +
			"Please see the documentation of the registry " + serverAddress + " for instructions how to activate it.")
	} else if reqStatusCode == 400 {
		if string(reqBody) == "\"Username or email already exists\"" {
			req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
			req.SetBasicAuth(authConfig.Username, authConfig.Password)
			resp, err := client.Do(req)
			if err != nil {
				return "", err
			}
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return "", err
			}
			if resp.StatusCode == 200 {
				status = "Login Succeeded"
			} else if resp.StatusCode == 401 {
				return "", fmt.Errorf("Wrong login/password, please try again")
			} else {
				return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
					resp.StatusCode, resp.Header)
			}
		} else {
			return "", fmt.Errorf("Registration: %s", reqBody)
		}
	} else {
		return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
	}
	return status, nil
}

// this method matches a auth configuration to a server address or a url
func (config *ConfigFile) ResolveAuthConfig(registry string) AuthConfig {
	if registry == IndexServerAddress() || len(registry) == 0 {
		// default to the index server
		return config.Configs[IndexServerAddress()]
	}
	// if its not the index server there are three cases:
	//
	// 1. this is a full config url -> it should be used as is
	// 2. it could be a full url, but with the wrong protocol
	// 3. it can be the hostname optionally with a port
	//
	// as there is only one auth entry which is fully qualified we need to start
	// parsing and matching

	swapProtocol := func(url string) string {
		if strings.HasPrefix(url, "http:") {
			return strings.Replace(url, "http:", "https:", 1)
		}
		if strings.HasPrefix(url, "https:") {
			return strings.Replace(url, "https:", "http:", 1)
		}
		return url
	}

	resolveIgnoringProtocol := func(url string) AuthConfig {
		if c, found := config.Configs[url]; found {
			return c
		}
		registrySwappedProtocol := swapProtocol(url)
		// now try to match with the different protocol
		if c, found := config.Configs[registrySwappedProtocol]; found {
			return c
		}
		return AuthConfig{}
	}

	// match both protocols as it could also be a server name like httpfoo
	if strings.HasPrefix(registry, "http:") || strings.HasPrefix(registry, "https:") {
		return resolveIgnoringProtocol(registry)
	}

	url := "https://" + registry
	if !strings.Contains(registry, "/") {
		url = url + "/v1/"
	}
	return resolveIgnoringProtocol(url)
}


text:
KYCircularView
==============
![KYCircularView](https://github.com/kentya6/KYCircularView/blob/master/demo.gif?raw=true)


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

#ifndef nsXBLBinding_h_
#define nsXBLBinding_h_

#include "nsCOMPtr.h"
#include "nsAutoPtr.h"
#include "nsINodeList.h"
#include "nsIStyleRuleProcessor.h"
#include "nsClassHashtable.h"
#include "nsTArray.h"
#include "nsCycleCollectionParticipant.h"
#include "nsISupportsImpl.h"

class nsXBLPrototypeBinding;
class nsIContent;
class nsIAtom;
class nsIDocument;
class nsIScriptContext;
class nsObjectHashtable;
class nsXBLInsertionPoint;
typedef nsTArray<nsRefPtr<nsXBLInsertionPoint> > nsInsertionPointList;
struct JSContext;
struct JSObject;

// *********************************************************************/
// The XBLBinding class

class nsXBLBinding
{
public:
  nsXBLBinding(nsXBLPrototypeBinding* aProtoBinding);
  ~nsXBLBinding();

  /**
   * XBLBindings are refcounted.  They are held onto in 3 ways:
   * 1. The binding manager's binding table holds onto all bindings that are
   *    currently attached to a content node.
   * 2. Bindings hold onto their base binding.  This is important since
   *    the base binding itself may not be attached to anything.
   * 3. The binding manager holds an additional reference to bindings
   *    which are queued to fire their constructors.
   */

  NS_INLINE_DECL_REFCOUNTING(nsXBLBinding)

  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(nsXBLBinding)

  nsXBLPrototypeBinding* PrototypeBinding() { return mPrototypeBinding; }
  nsIContent* GetAnonymousContent() { return mContent.get(); }

  nsXBLBinding* GetBaseBinding() { return mNextBinding; }
  void SetBaseBinding(nsXBLBinding *aBinding);

  nsIContent* GetBoundElement() { return mBoundElement; }
  void SetBoundElement(nsIContent *aElement);

  bool IsStyleBinding() const { return mIsStyleBinding; }
  void SetIsStyleBinding(bool aIsStyle) { mIsStyleBinding = aIsStyle; }

  void MarkForDeath();
  bool MarkedForDeath() const { return mMarkedForDeath; }

  bool HasStyleSheets() const;
  bool InheritsStyle() const;
  bool ImplementsInterface(REFNSIID aIID) const;

  void GenerateAnonymousContent();
  void InstallAnonymousContent(nsIContent* aAnonParent, nsIContent* aElement);
  static void UninstallAnonymousContent(nsIDocument* aDocument,
                                        nsIContent* aAnonParent);
  void InstallEventHandlers();
  nsresult InstallImplementation();

  void ExecuteAttachedHandler();
  void ExecuteDetachedHandler();
  void UnhookEventHandlers();

  nsIAtom* GetBaseTag(PRInt32* aNameSpaceID);
  nsXBLBinding* RootBinding();
  nsXBLBinding* GetFirstStyleBinding();

  // Resolve all the fields for this binding and all ancestor bindings on the
  // object |obj|.  False return means a JS exception was set.
  bool ResolveAllFields(JSContext *cx, JSObject *obj) const;

  // Get the list of insertion points for aParent. The nsInsertionPointList
  // is owned by the binding, you should not delete it.
  void GetInsertionPointsFor(nsIContent* aParent,
                             nsInsertionPointList** aResult);

  nsInsertionPointList* GetExistingInsertionPointsFor(nsIContent* aParent);

  // XXXbz this aIndex has nothing to do with an index into the child
  // list of the insertion parent or anything.
  nsIContent* GetInsertionPoint(const nsIContent* aChild, PRUint32* aIndex);

  nsIContent* GetSingleInsertionPoint(PRUint32* aIndex,
                                      bool* aMultipleInsertionPoints);

  void AttributeChanged(nsIAtom* aAttribute, PRInt32 aNameSpaceID,
                        bool aRemoveFlag, bool aNotify);

  void ChangeDocument(nsIDocument* aOldDocument, nsIDocument* aNewDocument);

  void WalkRules(nsIStyleRuleProcessor::EnumFunc aFunc, void* aData);

  nsINodeList* GetAnonymousNodes();

  static nsresult DoInitJSClass(JSContext *cx, JSObject *global, JSObject *obj,
                                const nsAFlatCString& aClassName,
                                nsXBLPrototypeBinding* aProtoBinding,
                                JSObject** aClassObject);

  bool AllowScripts();  // XXX make const

  void RemoveInsertionParent(nsIContent* aParent);
  bool HasInsertionParent(nsIContent* aParent);

// MEMBER VARIABLES
protected:

  bool mIsStyleBinding;
  bool mMarkedForDeath;

  nsXBLPrototypeBinding* mPrototypeBinding; // Weak, but we're holding a ref to the docinfo
  nsCOMPtr<nsIContent> mContent; // Strong. Our anonymous content stays around with us.
  nsRefPtr<nsXBLBinding> mNextBinding; // Strong. The derived binding owns the base class bindings.

  nsIContent* mBoundElement; // [WEAK] We have a reference, but we don't own it.

  // A hash from nsIContent* -> (a sorted array of nsXBLInsertionPoint)
  nsClassHashtable<nsISupportsHashKey, nsInsertionPointList>* mInsertionPointTable;
};

#endif // nsXBLBinding_h_


text:
<?php

use PHPUnit\Framework\TestCase;

require 'common.php';

/**
 * @covers CrawlerVlive
 */
final class CrawlerVliveTest extends TestCase
{
    public function testCanBeCreatedFromVlive()
    {
        $this->assertInstanceOf(
            CrawlerVlive::class,
            new CrawlerVlive()
        );
    }

    public function testCanGetEnoughMessageWithoutDateConfig()
    {
        $crawler = new CrawlerVlive();
        $crawler->setConfig([]);
        $crawler->prepareCrawl();
        $crawler->executeCrawl();

        $this->assertGreaterThanOrEqual(10,count($crawler->getMessage()));
        foreach ($crawler->getMessage() as $key => $value) {
            $this->assertArrayHasKey('link',$value);
            $this->assertArrayHasKey('title',$value);
            $this->assertArrayHasKey('created_at_time',$value);
            $this->assertArrayHasKey('time',$value);
            $this->assertArrayHasKey('author',$value);
            $this->assertArrayHasKey('pics',$value);
        }
    }

    public function testCanGetFixedMessageWithDateConfig()
    {
        $crawler = new CrawlerVlive();
        $crawler->setConfig([
            'date' => '20170924',
            'country' => 'CN',
            'offset' => '-60'
        ]);
        $crawler->prepareCrawl();
        $crawler->executeCrawl();

        $this->assertEquals(48,count($crawler->getMessage()));
        foreach ($crawler->getMessage() as $key => $value) {
            $this->assertArrayHasKey('link',$value);
            $this->assertArrayHasKey('title',$value);
            $this->assertArrayHasKey('created_at_time',$value);
            $this->assertArrayHasKey('time',$value);
            $this->assertArrayHasKey('author',$value);
            $this->assertArrayHasKey('pics',$value);
        }
    }

    public function testCannotGetEnoughMessageWithPublicTimeCheckConfig()
    {
        $crawler = new CrawlerVlive();
        $crawler->setConfig([
            'date' => '20170924',
            'country' => 'CN',
            'offset' => '-60',
            'public_time_check' => '2017-09-24 23:01'
        ]);
        $crawler->prepareCrawl();
        $crawler->executeCrawl();

        $this->assertEquals(2,count($crawler->getMessage()));
        foreach ($crawler->getMessage() as $key => $value) {
            $this->assertArrayHasKey('link',$value);
            $this->assertArrayHasKey('title',$value);
            $this->assertArrayHasKey('created_at_time',$value);
            $this->assertArrayHasKey('time',$value);
            $this->assertArrayHasKey('author',$value);
            $this->assertArrayHasKey('pics',$value);
        }
    }
}


text:
package org.kie.workbench.common.stunner.core.client.canvas.event.command;

import org.kie.workbench.common.stunner.core.client.canvas.CanvasHandler;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.CommandResult;

public final class CanvasUndoCommandExecutedEvent<H extends CanvasHandler> extends AbstractCanvasCommandEvent<H> {

    public CanvasUndoCommandExecutedEvent(final H canvasHandler,
                                          final Command<H, CanvasViolation> command,
                                          final CommandResult<CanvasViolation> violation) {
        super(canvasHandler,
              command,
              violation);
    }
}


text:
A docker-compose stack with an Apache and MySQL server running Drupal 8.

# First Time

The default password (set in `docker-compose.yml` ) is: `Passw0rd`
You should change this before running the `rebuild-lamp-stack.sh` script.

The default port for the web server is: `2080`
You can set this to any unused port before starting a new Drupal stack.

To set up the stack for the first time, or destroy the current stack and set up a fresh install of drupal, run the script:
```
$ bash ./rebuild-lamp-stack.sh
```
Then open firefox and browse to the setup page to finish the install.
All the required details will be printed by the script when it runs.

# Starting and Stopping

Before shutting down, you should stop the stack first with:
```
$ bash ./stop-lamp-stack.sh
```
Any changes should be saved until you next run the stack.

Start a stack before connecting to it, with:
```
$ bash ./start-lamp-stack.sh
```

# Checking the Stack

You can check if everything is running OK with:
```
$ bash ./status-lamp-stack.sh
```

# Destroy the Stack

When you no longer need a web stack, you can destroy it by running:
```
$ bash ./destroy-lamp-stack.sh
```

Author: Tad Davis (tad@tinycactus.me)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 13: 158 (1959)

#### Original name
Cercospora dalbergiae-latifoliae Chidd.

### Remarks
null


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;

namespace AdventOfCode1016
{
    public class Day12
    {
        public string Input;

        public Day12(string input)
        {
            Input = input;
        }

    }

    public class Computer {

        public Dictionary<int,string> Program = new Dictionary<int, string>();
        public ProgramCursor Cursor
        {
            get; protected set;
        }
        protected Dictionary<string, Instruction> instructions = new Dictionary<string, Instruction>();
        protected Dictionary<string, Register> registers = new Dictionary<string, Register>();

        public int RegisterA
        {
            get { return registers["a"].Value;  }
            set { }
        }

        public int RegisterB
        {
            get { return registers["b"].Value; }
            set { }
        }

        public int RegisterC
        {
            get { return registers["c"].Value;  }
            set { }
        }

        public int RegisterD
        {
            get { return registers["d"].Value; }
            set { }
        }
       public Computer()
        {
            Initialize();
            registers["a"].Value = 0;
            registers["b"].Value = 0;
            registers["c"].Value = 0;
            registers["d"].Value = 0;
        }

        public Computer(int a = 0, int b = 0, int c = 0, int d = 0)
        {
            Initialize();
            registers["a"].Value = a;
            registers["b"].Value = b;
            registers["c"].Value = c;
            registers["d"].Value = d;
        }

        protected virtual void Initialize ()
        {
            // Should use depedency injection to inject a collection of registers to the computer class
            registers.Add("a", new Register("a"));
            registers.Add("b", new Register("b"));
            registers.Add("c", new Register("c"));
            registers.Add("d", new Register("d"));
            // Should use depedency injection to inject a set of instructions to the computer class
            // So when we would like to add a new instruction to the computer, no need to modify the Computer class
            instructions.Add("inc", new Instruction_INC());
            instructions.Add("dec", new Instruction_DEC());
            instructions.Add("cpy", new Instruction_CPY());
            instructions.Add("jnz", new Instruction_JNZ());

            Cursor = new ProgramCursor();
        }

        public void LoadProgramFromString(string listing)
        {
            Program = new Dictionary<int, string>();
            int cpt = 0;
            var lines = listing.Split('\n').Select(p => p.Trim()).ToList();
            foreach (var programLine in lines)
            {
                if (!String.IsNullOrEmpty(programLine)) {
                    Program.Add(cpt++, programLine);
                }
            }
        }

        public void Reset()
        {
            registers["a"].Value = 0;
            registers["b"].Value = 0;
            registers["c"].Value = 0;
            registers["d"].Value = 0;
            Cursor.Position = 0;
        }

        public void Reset(int a = 0, int b = 0, int c = 0, int d = 0)
        {
            registers["a"].Value = a;
            registers["b"].Value = b;
            registers["c"].Value = c;
            registers["d"].Value = d;
            Cursor.Position = 0;
        }

        public virtual void Run()
        {
            while (Program.ContainsKey(Cursor.Position)) {
                string[] programLine = Program[Cursor.Position].Split(' ');
                string code = programLine[0];
                string x = programLine[1];
                string y = (programLine.Length > 2) ? programLine[2] : String.Empty;
                instructions[code].Execute(registers, Cursor, x, y);
            }
        }
    }

    public class Register
    {
        public int Value { get; set; }
        public string Name { get; set; }
        public Register(string name)
        {
            Name = name;
            Value = 0;
        }
    }

    public class ProgramCursor
    {
        private int _position = 0;
        public int Position {
            get {
                return _position;
            }
            set {
                if (value < 0) {
                    _position = 0;
                } else {
                    _position = value;
                }
            }
         }
    }

    public abstract class Instruction
    {
        public string Name;
        public string Help;
        public string Code;
        public abstract void Execute(Dictionary<string, Register> registers, ProgramCursor cursor, string x, string y);
        public virtual void Execute(Dictionary<string, Register> registers, Dictionary<int,string> program, ProgramCursor cursor, string x, string y){

        }
    }

    public class Instruction_INC : Instruction
    {
        public Instruction_INC()
        {
            Name = "Increment";
            Help = "Increments register x, adding 1 to it, then continues with the next instruction.";
            Code = "inc";
        }
        public override void Execute(Dictionary<string, Register> registers, ProgramCursor cursor, string x, string y = "")
        {
            registers[x].Value++;
            cursor.Position++;
        }
    }

    public class Instruction_DEC : Instruction
    {
        public Instruction_DEC()
        {
            Name = "Decrement";
            Help = "Decrements register x, substracting 1 to it, then continues with the next instruction.";
            Code = "dec";
        }
        public override void Execute(Dictionary<string, Register> registers, ProgramCursor cursor, string x, string y = "")
        {
            registers[x].Value--;
            cursor.Position++;
        }
    }

    public class Instruction_JNZ : Instruction
    {
        public Instruction_JNZ()
        {
            Name = "Jump";
            Help = "Jumps to an instruction y away (positive means forward; negative means backward), but only if x is not zero.";
            Code = "jnz";
        }
        public override void Execute(Dictionary<string, Register> registers, ProgramCursor cursor, string x, string y)
        {
            bool goToNextInstruction = false;
            Regex regex = new Regex(@"(-?[0-9]+)");
            Match match = regex.Match(x);
            if (match.Success)
            {
                 var value = 0;
                 Int32.TryParse(match.Groups[1].Value, out value);
                 if (value == 0) {
                    goToNextInstruction = true;
                 }
            } else {
                if (registers[x].Value == 0) {
                    goToNextInstruction = true;
                }
            }

            var offset = 0;
            if (goToNextInstruction) {
                cursor.Position++;
            } else {
                if (char.IsLetter(y[0])) {
                    offset = registers[y].Value;
                } else {
                    Int32.TryParse(y, out offset);
                }
                cursor.Position += offset;
            }
        }
    }

    public class Instruction_CPY : Instruction
    {
        public Instruction_CPY()
        {
            Name = "Copy";
            Help = "Copies x (either an integer or the value of a register) into register y";
            Code = "CPY";
        }
        public override void Execute(Dictionary<string, Register> registers, ProgramCursor cursor, string x, string y)
        {
            if (char.IsLetter(y[0])) {
                Regex regex = new Regex(@"(-?[0-9]+)");
                Match match = regex.Match(x);
                if (match.Success)
                {
                    var value = 0;
                    Int32.TryParse(match.Groups[1].Value, out value);
                    registers[y].Value = value;
                } else {
                    registers[y].Value = registers[x].Value;
                }
            }
            cursor.Position++;
        }
    }
}


text:
package com.nucleus.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Toast;

import net.rdrei.android.dirchooser.DirectoryChooserConfig;
import net.rdrei.android.dirchooser.DirectoryChooserFragment;

import helper.AppConstant;

/**
 * Created by Sreeraag on 10-04-2016.
 */
public class DirChooserFragment extends Activity implements
        DirectoryChooserFragment.OnFragmentInteractionListener {

    private DirectoryChooserFragment mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final DirectoryChooserConfig config = DirectoryChooserConfig.builder()
                .newDirectoryName("DialogSample")
                .build();
        mDialog = DirectoryChooserFragment.newInstance(config);

        mDialog.show(getFragmentManager(), null);
    }
    @Override
    public void onSelectDirectory(@NonNull String path) {
        String[] parts = path.split("/0/");
        AppConstant.PHOTO_ALBUM = parts[1];
        mDialog.dismiss();
        Toast.makeText(getApplicationContext(),AppConstant.PHOTO_ALBUM+"has been selected", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(DirChooserFragment.this,MainActivity.class);
        startActivity(intent);
    }

    @Override
    public void onCancelChooser() {
        mDialog.dismiss();
    }
}


text:
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase
from looper.views import quick_loop

class QuickLoopTest(TestCase):

   def test_url_resolves_to_quick_loop_view(self):
       found = resolve('/quickloop/')
       self.assertEqual(found.func, quick_loop)

   def test_quick_loop_returns_correct_html(self):
       request = HttpRequest()
       response = quick_loop(request)
       expected_html = render_to_string('quickloop.html')
       self.assertEqual(response.content.decode(), expected_html)


text:
package edu.internet2.middleware.openid.message.encoding;

import edu.internet2.middleware.openid.common.OpenIDException;

/**
 * Exception with OpenID message encoding.
 */
public class EncodingException extends OpenIDException {

    /** Serial Version UID. */
    private static final long serialVersionUID = -3799369449630531301L;

    /** Constructor. */
    public EncodingException() {
        super();
    }

    /**
     * Constructor.
     *
     * @param message exception message
     */
    public EncodingException(String message) {
        super(message);
    }

    /**
     * Constructor.
     *
     * @param cause exception to be wrapped by this one
     */
    public EncodingException(Throwable cause) {
        super(cause);
    }

    /**
     * Constructor.
     *
     * @param message exception messaage
     * @param cause exception to be wrapped by this one
     */
    public EncodingException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
from __future__ import absolute_import, division, print_function

import datashape
from datashape import String
from datashape.predicates import isrecord
from odo.utils import copydoc

from .expressions import Expr, schema_method_list, ElemWise
from .arithmetic import Interp, Repeat, _mkbin, repeat, interp, _add, _radd

__all__ = ['Like', 'like', 'strlen', 'UnaryStringFunction']

class Like(Expr):

    """ Filter expression by string comparison

    >>> from blaze import symbol, like, compute
    >>> t = symbol('t', 'var * {name: string, city: string}')
    >>> expr = like(t, name='Alice*')

    >>> data = [('Alice Smith', 'New York'),
    ...         ('Bob Jones', 'Chicago'),
    ...         ('Alice Walker', 'LA')]
    >>> list(compute(expr, data))
    [('Alice Smith', 'New York'), ('Alice Walker', 'LA')]
    """
    __slots__ = '_hash', '_child', '_patterns'

    @property
    def patterns(self):
        return dict(self._patterns)

    @property
    def dshape(self):
        return datashape.var * self._child.dshape.subshape[0]

@copydoc(Like)
def like(child, **kwargs):
    return Like(child, tuple(kwargs.items()))

class UnaryStringFunction(ElemWise):

    """String function that only takes a single argument.
    """
    __slots__ = '_hash', '_child'

class strlen(UnaryStringFunction):
    schema = datashape.int64

def isstring(ds):
    measure = ds.measure
    return isinstance(getattr(measure, 'ty', measure), String)

_mod, _rmod = _mkbin('mod', Interp)
_mul, _rmul = _mkbin('mul', Repeat)

schema_method_list.extend([
    (isstring, set([_add, _radd, _mod, _rmod, _mul, _rmul, repeat, interp])),
    (lambda ds: isstring(ds) or (isrecord(ds.measure) and
                                 any(isinstance(getattr(typ, 'ty', typ),
                                                String)
                                     for typ in ds.measure.types)),
     set([like])),
    (lambda ds: isinstance(getattr(ds.measure, 'ty', ds.measure), String),
     set([strlen]))
])


text:
package org.apache.kafka.common.requests;

import org.apache.kafka.common.message.AlterPartitionResponseData;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.protocol.ByteBufferAccessor;
import org.apache.kafka.common.protocol.Errors;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public class AlterPartitionResponse extends AbstractResponse {

    private final AlterPartitionResponseData data;

    public AlterPartitionResponse(AlterPartitionResponseData data) {
        super(ApiKeys.ALTER_PARTITION);
        this.data = data;
    }

    @Override
    public AlterPartitionResponseData data() {
        return data;
    }

    @Override
    public Map<Errors, Integer> errorCounts() {
        Map<Errors, Integer> counts = new HashMap<>();
        updateErrorCounts(counts, Errors.forCode(data.errorCode()));
        data.topics().forEach(topicResponse -> topicResponse.partitions().forEach(partitionResponse -> {
            updateErrorCounts(counts, Errors.forCode(partitionResponse.errorCode()));
        }));
        return counts;
    }

    @Override
    public int throttleTimeMs() {
        return data.throttleTimeMs();
    }

    public static AlterPartitionResponse parse(ByteBuffer buffer, short version) {
        return new AlterPartitionResponse(new AlterPartitionResponseData(new ByteBufferAccessor(buffer), version));
    }
}


text:
var chai = require('chai');
var expect = chai.expect;
var Promise = require('bluebird');

describe('#withMessage()', function() {
	describe('on async validators', function() {

		before(function() {
			delete require.cache[require.resolve('../lib/express_validator')];
		});

		it('should not affect a passing validation', function(done) {
			var validator = require('../lib/express_validator')({
				customValidators: {
					test: function() {
						// A dummy passing validator
						return new Promise(function(resolve) {
							resolve();
						});
					}
				}
			});

			var req = {
				body: {
					testParam: 100
				}
			};

			validator(req, {}, function() {});
			req.check('testParam', 'Default Message')
				.test().withMessage('Custom Message');

			verify(done, function() {
				return req.asyncValidationErrors()
					.catch(function() {
						expect.fail(null, null, 'No errors should have been generated by the test');
					});
			});

		});

		it('should provide a custom message when a validation fails', function(done) {
			var validator = require('../lib/express_validator')({
				customValidators: {
					test: function() {
						// A dummy failing validator
						return new Promise(function(resolve, reject) {
							reject();
						});
					}
				}
			});

			var req = {
				body: {
					testParam: 100
				}
			};

			validator(req, {}, function() {});

			req.check('testParam', 'Default Message')
				.test().withMessage('Custom Message');

			verify(done, function() {
				return req.asyncValidationErrors()
					.catch(function(err) {
						expect(err).to.deep.equal([{
							msg: 'Custom Message',
							param: 'testParam',
							value: 100
						}]);
					});
			});
		});

		it('should provide the default message if it was not the validation to fail', function(done) {
			var validator = require('../lib/express_validator')({
				customValidators: {
					pass: function() {
						return new Promise(function(resolve) { resolve(); });
					},
					fail: function() {
						return new Promise(function(resolve, reject) { reject(); });
					}
				}
			});

			var req = {
				body: {
					testParam: 100
				}
			};

			validator(req, {}, function() {});

			req.check('testParam', 'Default Message')
				.fail() // Default Message
				.pass().withMessage('Passing Message')
				.fail() // Default Message
				.fail().withMessage('Failing Message')
				.fail() // Default Message
				.fail().withMessage('Failing Message 1')
				.fail().withMessage('Failing Message 2');

			var expected = [
				'Default Message',
				'Default Message',
				'Failing Message',
				'Default Message',
				'Failing Message 1',
				'Failing Message 2'];

			verify(done, function() {
				return req.asyncValidationErrors()
					.catch(function(err) {
						expect(err.map(function(e) {return e.msg;})).to.deep.equal(expected);
					});
			});
		});

		// Helper to handle resolving tests async
		function verify(done, f) {
			try {
				var test = f();
				if (test && test.then) {
					test.then(function() {
						done();
					})
					.catch(function(err) {
						done(err);
					});
				} else {
					done();
				}
			}
			catch (e) {
				done(e);
			}
		}
	});
});


text:
export default [{
  name: 'Jon Deng',
  avatar_url: 'https://avatars.githubusercontent.com/u/13730320?v=3',
  html_url: 'https://github.com/dengjonathan',
  title: 'Product Owner, Engineer',
  likes: 'Redux, trail running, functional programming',
  city: 'Los Angeles'
}, {
  name: 'David Bisrat',
  avatar_url: 'https://avatars.githubusercontent.com/u/20425875?v=3',
  html_url: 'https://github.com/dabisrat',
  title: 'Scrum Master, Engineer',
  likes: 'React, All things science, JavaScript: the good parts',
  city: 'Atlanta'
}, {
  name: 'Mitch Small',
  avatar_url: 'https://avatars.githubusercontent.com/u/12477375?v=3',
  html_url: 'https://github.com/fuzzwizard',
  title: 'Game Developer, Engineer',
  likes: 'food, videogames, yelling at his Rust compiler',
  city: 'Los Angeles'
}, {
  name: 'Andrew Cernek',
  avatar_url: 'https://avatars.githubusercontent.com/u/2206529?v=3',
  html_url: 'https://github.com/Numose',
  title: 'DevOps, Engineer',
  likes: 'Building stuff, cats, and big data',
  city: 'Phoenix'
}];


text:
package tachyon.worker.hierarchy;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import tachyon.StorageLevelAlias;
import tachyon.TestUtils;
import tachyon.UnderFileSystem;
import tachyon.conf.WorkerConf;
import tachyon.thrift.InvalidPathException;
import tachyon.util.CommonUtils;
import tachyon.worker.BlockHandler;

public class StorageTierTest {

  private static final long USER_ID = 1;

  private StorageTier[] mStorageTiers;

  @After
  public final void after() throws Exception {
    System.clearProperty("tachyon.worker.hierarchystore.level.max");
    System.clearProperty("tachyon.worker.hierarchystore.level0.alias");
    System.clearProperty("tachyon.worker.hierarchystore.level0.dirs.path");
    System.clearProperty("tachyon.worker.hierarchystore.level0.dirs.quota");
    System.clearProperty("tachyon.worker.hierarchystore.level1.alias");
    System.clearProperty("tachyon.worker.hierarchystore.level1.dirs.path");
    System.clearProperty("tachyon.worker.hierarchystore.level1.dirs.quota");
    WorkerConf.clear();
  }

  @Before
  public final void before() throws IOException, InvalidPathException {
    String tachyonHome =
        File.createTempFile("Tachyon", "").getAbsoluteFile() + "U" + System.currentTimeMillis();
    System.setProperty("tachyon.worker.hierarchystore.level.max", 2 + "");
    System.setProperty("tachyon.worker.hierarchystore.level0.alias", "MEM");
    System.setProperty("tachyon.worker.hierarchystore.level0.dirs.path", tachyonHome + "/ramdisk");
    System.setProperty("tachyon.worker.hierarchystore.level0.dirs.quota", 1000 + "");
    System.setProperty("tachyon.worker.hierarchystore.level1.alias", "HDD");
    System.setProperty("tachyon.worker.hierarchystore.level1.dirs.path", tachyonHome + "/disk1,"
        + tachyonHome + "/disk2");
    System.setProperty("tachyon.worker.hierarchystore.level1.dirs.quota", 4000 + "," + 4000);

    // Clear worker configurations which are set by other tests
    WorkerConf.clear();
    final int maxLevel = WorkerConf.get().STORAGE_LEVELS;
    mStorageTiers = new StorageTier[maxLevel];
    StorageTier nextTier = null;
    for (int level = maxLevel - 1; level >= 0; level --) {
      String[] dirPaths = WorkerConf.get().STORAGE_TIER_DIRS[level].split(",");
      for (int i = 0; i < dirPaths.length; i ++) {
        dirPaths[i] = dirPaths[i].trim();
      }
      StorageLevelAlias storageLevelAlias = WorkerConf.get().STORAGE_LEVEL_ALIAS[level];
      String[] strDirCapacities = WorkerConf.get().STORAGE_TIER_DIR_QUOTA[level].split(",");
      long[] dirCapacities = new long[dirPaths.length];
      for (int i = 0, j = 0; i < dirPaths.length; i ++) {
        // The storage directory quota for each storage directory
        dirCapacities[i] = CommonUtils.parseSpaceSize(strDirCapacities[j].trim());
        if (j < strDirCapacities.length - 1) {
          j ++;
        }
      }
      StorageTier curTier =
          new StorageTier(level, storageLevelAlias, dirPaths, dirCapacities, "/data", "/user",
              nextTier, null);
      mStorageTiers[level] = curTier;
      curTier.initialize();
      for (StorageDir dir : curTier.getStorageDirs()) {
        initializeStorageDir(dir, USER_ID);
      }
      nextTier = curTier;
    }
  }

  private void createBlockFile(StorageDir dir, long blockId, int blockSize) throws IOException {
    byte[] buf = TestUtils.getIncreasingByteArray(blockSize);
    BlockHandler bhSrc =
        BlockHandler.get(dir.getUserTempFilePath(USER_ID, blockId));
    dir.requestSpace(USER_ID, blockSize);
    dir.updateTempBlockAllocatedBytes(USER_ID, blockId, blockSize);
    try {
      bhSrc.append(0, ByteBuffer.wrap(buf));
    } finally {
      bhSrc.close();
    }
    dir.cacheBlock(USER_ID, blockId);
  }

  @Test
  public void getStorageDirTest() throws IOException {
    long blockId = 1;
    List<Long> removedBlockIds = new ArrayList<Long>();
    StorageDir dir = mStorageTiers[0].requestSpace(USER_ID, 100, new HashSet<Integer>(),
        removedBlockIds);
    createBlockFile(dir, blockId, 100);
    StorageDir dir1 = mStorageTiers[0].getStorageDirByBlockId(1);
    Assert.assertEquals(dir, dir1);
    dir1 = mStorageTiers[0].getStorageDirByBlockId(2);
    Assert.assertEquals(null, dir1);
    dir = mStorageTiers[1].getStorageDirByIndex(1);
    Assert.assertEquals(mStorageTiers[1].getStorageDirs()[1], dir);
    dir1 = mStorageTiers[1].getStorageDirByIndex(2);
    Assert.assertEquals(null, dir1);
  }

  private void initializeStorageDir(StorageDir dir, long userId) throws IOException {
    UnderFileSystem ufs = dir.getUfs();
    ufs.mkdirs(dir.getUserTempPath(userId), true);
    CommonUtils.changeLocalFileToFullPermission(dir.getUserTempPath(userId));
  }

  @Test
  public void isLastTierTest() {
    Assert.assertEquals(false, mStorageTiers[0].isLastTier());
    Assert.assertEquals(true, mStorageTiers[1].isLastTier());
  }

  @Test
  public void requestSpaceTest() throws IOException {
    long blockId = 1;
    List<Long> removedBlockIds = new ArrayList<Long>();
    Assert.assertEquals(1000, mStorageTiers[0].getCapacityBytes());
    Assert.assertEquals(8000, mStorageTiers[1].getCapacityBytes());
    StorageDir dir = mStorageTiers[0].requestSpace(USER_ID, 500, new HashSet<Integer>(),
        removedBlockIds);
    dir.updateTempBlockAllocatedBytes(USER_ID, blockId, 500);
    Assert.assertEquals(mStorageTiers[0].getStorageDirs()[0], dir);
    Assert.assertEquals(500, dir.getAvailableBytes());
    Assert.assertEquals(500, dir.getUsedBytes());
    StorageDir dir1 = mStorageTiers[0].requestSpace(USER_ID, 501, new HashSet<Integer>(),
        removedBlockIds);
    Assert.assertEquals(null, dir1);
    createBlockFile(dir, blockId, 500);
    boolean request = mStorageTiers[0].requestSpace(dir, USER_ID, 501, new HashSet<Integer>(),
        removedBlockIds);
    Assert.assertTrue(request);
    Assert.assertEquals(499, dir.getAvailableBytes());
    Assert.assertEquals(501, dir.getUsedBytes());
    Assert.assertTrue(mStorageTiers[1].containsBlock(blockId));
    Assert.assertEquals(500, mStorageTiers[1].getUsedBytes());
    request = mStorageTiers[0].requestSpace(dir, USER_ID, 500, new HashSet<Integer>(),
        removedBlockIds);
    Assert.assertEquals(false, request);
  }
}


text:
package okio.samples;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import okio.Buffer;
import okio.ByteString;

public final class GoldenValue {
  public void run() throws Exception {
    Point point = new Point(8.0, 15.0);
    ByteString pointBytes = serialize(point);
    System.out.println(pointBytes.base64());

    ByteString goldenBytes = ByteString.decodeBase64("rO0ABXNyAB5va2lvLnNhbXBsZ"
        + "XMuR29sZGVuVmFsdWUkUG9pbnTdUW8rMji1IwIAAkQAAXhEAAF5eHBAIAAAAAAAAEAuA"
        + "AAAAAAA");
    Point decoded = (Point) deserialize(goldenBytes);
    assertEquals(point, decoded);
  }

  private ByteString serialize(Object o) throws IOException {
    Buffer buffer = new Buffer();
    try (ObjectOutputStream objectOut = new ObjectOutputStream(buffer.outputStream())) {
      objectOut.writeObject(o);
    }
    return buffer.readByteString();
  }

  private Object deserialize(ByteString byteString) throws IOException, ClassNotFoundException {
    Buffer buffer = new Buffer();
    buffer.write(byteString);
    try (ObjectInputStream objectIn = new ObjectInputStream(buffer.inputStream())) {
      Object result = objectIn.readObject();
      if (objectIn.read() != -1) throw new IOException("Unconsumed bytes in stream");
      return result;
    }
  }

  static final class Point implements Serializable {
    double x;
    double y;

    Point(double x, double y) {
      this.x = x;
      this.y = y;
    }
  }

  private void assertEquals(Point a, Point b) {
    if (a.x != b.x || a.y != b.y) throw new AssertionError();
  }

  public static void main(String... args) throws Exception {
    new GoldenValue().run();
  }
}


text:
module BpCustomFields
  module DisplayHelper

    def display_field(field)
      case field.field_type
      when 'gallery'
        field.to_a
      when 'image'
        display_image_field(field)
      when 'video'
        display_video_field(field)
      else
        field.value
      end
    end

    private

    def display_image_field(field)
      image_tag field.file.url, class: "bpcf-image-#{field.label}", alt: field.label
    end

    def display_video_field(field)
      video = BpCustomFields::Video.new(field.address)
      video_embed_html(video)
    end

    def video_embed_html(video)
      content_tag :div, class: "bpcf-embed-container" do
        content_tag :iframe, nil, src: video.embed_address, frameborder: 0, allowfullscreen: ''
      end
    end

  end
end


text:
silverstripe-wysihtml5
======================

Implementation of xing/wysihtml5 as a SilverStripe form type

Source
======

If anyone was wondering, this comes from [xing/wysihtml5](https://github.com/xing/wysihtml5) (which is a pretty sweet wysiwyg for simple things)

Compatibility
-------------

2.4 only so far, but if someone wants to do the required work, I'm happy to make a new branch for it.

Badness
=======

Oh, it's very bad. You probably shouldn't use this, unless you're in a rush (and if you're using a 2.4 site, you probably are).