text:
package org.apache.flink.runtime.taskexecutor;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.runtime.blob.PermanentBlobService;
import org.apache.flink.runtime.broadcast.BroadcastVariableManager;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.execution.librarycache.BlobLibraryCacheManager;
import org.apache.flink.runtime.execution.librarycache.LibraryCacheManager;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
import org.apache.flink.runtime.io.network.TaskEventDispatcher;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
import org.apache.flink.runtime.shuffle.ShuffleEnvironmentContext;
import org.apache.flink.runtime.shuffle.ShuffleServiceLoader;
import org.apache.flink.runtime.state.TaskExecutorLocalStateStoresManager;
import org.apache.flink.runtime.taskexecutor.slot.TaskSlotTable;
import org.apache.flink.runtime.taskexecutor.slot.TaskSlotTableImpl;
import org.apache.flink.runtime.taskexecutor.slot.TimerService;
import org.apache.flink.runtime.taskmanager.Task;
import org.apache.flink.runtime.taskmanager.UnresolvedTaskManagerLocation;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * Container for {@link TaskExecutor} services such as the {@link MemoryManager}, {@link IOManager},
 * {@link ShuffleEnvironment}. All services are exclusive to a single {@link TaskExecutor}.
 * Consequently, the respective {@link TaskExecutor} is responsible for closing them.
 */
public class TaskManagerServices {
	private static final Logger LOG = LoggerFactory.getLogger(TaskManagerServices.class);

	@VisibleForTesting
	public static final String LOCAL_STATE_SUB_DIRECTORY_ROOT = "localState";

	/** TaskManager services. */
	private final UnresolvedTaskManagerLocation unresolvedTaskManagerLocation;
	private final long managedMemorySize;
	private final IOManager ioManager;
	private final ShuffleEnvironment<?, ?> shuffleEnvironment;
	private final KvStateService kvStateService;
	private final BroadcastVariableManager broadcastVariableManager;
	private final TaskSlotTable<Task> taskSlotTable;
	private final JobTable jobTable;
	private final JobLeaderService jobLeaderService;
	private final TaskExecutorLocalStateStoresManager taskManagerStateStore;
	private final TaskEventDispatcher taskEventDispatcher;
	private final ExecutorService ioExecutor;
	private final LibraryCacheManager libraryCacheManager;

	TaskManagerServices(
		UnresolvedTaskManagerLocation unresolvedTaskManagerLocation,
		long managedMemorySize,
		IOManager ioManager,
		ShuffleEnvironment<?, ?> shuffleEnvironment,
		KvStateService kvStateService,
		BroadcastVariableManager broadcastVariableManager,
		TaskSlotTable<Task> taskSlotTable,
		JobTable jobTable,
		JobLeaderService jobLeaderService,
		TaskExecutorLocalStateStoresManager taskManagerStateStore,
		TaskEventDispatcher taskEventDispatcher,
		ExecutorService ioExecutor,
		LibraryCacheManager libraryCacheManager) {

		this.unresolvedTaskManagerLocation = Preconditions.checkNotNull(unresolvedTaskManagerLocation);
		this.managedMemorySize = managedMemorySize;
		this.ioManager = Preconditions.checkNotNull(ioManager);
		this.shuffleEnvironment = Preconditions.checkNotNull(shuffleEnvironment);
		this.kvStateService = Preconditions.checkNotNull(kvStateService);
		this.broadcastVariableManager = Preconditions.checkNotNull(broadcastVariableManager);
		this.taskSlotTable = Preconditions.checkNotNull(taskSlotTable);
		this.jobTable = Preconditions.checkNotNull(jobTable);
		this.jobLeaderService = Preconditions.checkNotNull(jobLeaderService);
		this.taskManagerStateStore = Preconditions.checkNotNull(taskManagerStateStore);
		this.taskEventDispatcher = Preconditions.checkNotNull(taskEventDispatcher);
		this.ioExecutor = Preconditions.checkNotNull(ioExecutor);
		this.libraryCacheManager = Preconditions.checkNotNull(libraryCacheManager);
	}

	// --------------------------------------------------------------------------------------------
	//  Getter/Setter
	// --------------------------------------------------------------------------------------------

	long getManagedMemorySize() {
		return managedMemorySize;
	}

	public IOManager getIOManager() {
		return ioManager;
	}

	public ShuffleEnvironment<?, ?> getShuffleEnvironment() {
		return shuffleEnvironment;
	}

	public KvStateService getKvStateService() {
		return kvStateService;
	}

	public UnresolvedTaskManagerLocation getUnresolvedTaskManagerLocation() {
		return unresolvedTaskManagerLocation;
	}

	public BroadcastVariableManager getBroadcastVariableManager() {
		return broadcastVariableManager;
	}

	public TaskSlotTable<Task> getTaskSlotTable() {
		return taskSlotTable;
	}

	public JobTable getJobTable() {
		return jobTable;
	}

	public JobLeaderService getJobLeaderService() {
		return jobLeaderService;
	}

	public TaskExecutorLocalStateStoresManager getTaskManagerStateStore() {
		return taskManagerStateStore;
	}

	public TaskEventDispatcher getTaskEventDispatcher() {
		return taskEventDispatcher;
	}

	public Executor getIOExecutor() {
		return ioExecutor;
	}

	public LibraryCacheManager getLibraryCacheManager() {
		return libraryCacheManager;
	}

	// --------------------------------------------------------------------------------------------
	//  Shut down method
	// --------------------------------------------------------------------------------------------

	/**
	 * Shuts the {@link TaskExecutor} services down.
	 */
	public void shutDown() throws FlinkException {

		Exception exception = null;

		try {
			taskManagerStateStore.shutdown();
		} catch (Exception e) {
			exception = e;
		}

		try {
			ioManager.close();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			shuffleEnvironment.close();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			kvStateService.shutdown();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			taskSlotTable.close();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			jobLeaderService.stop();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			ioExecutor.shutdown();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			jobTable.close();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		try {
			libraryCacheManager.shutdown();
		} catch (Exception e) {
			exception = ExceptionUtils.firstOrSuppressed(e, exception);
		}

		taskEventDispatcher.clearAll();

		if (exception != null) {
			throw new FlinkException("Could not properly shut down the TaskManager services.", exception);
		}
	}

	// --------------------------------------------------------------------------------------------
	//  Static factory methods for task manager services
	// --------------------------------------------------------------------------------------------

	/**
	 * Creates and returns the task manager services.
	 *
	 * @param taskManagerServicesConfiguration task manager configuration
	 * @param permanentBlobService permanentBlobService used by the services
	 * @param taskManagerMetricGroup metric group of the task manager
	 * @param ioExecutor executor for async IO operations
	 * @param fatalErrorHandler to handle class loading OOMs
	 * @return task manager components
	 * @throws Exception
	 */
	public static TaskManagerServices fromConfiguration(
			TaskManagerServicesConfiguration taskManagerServicesConfiguration,
			PermanentBlobService permanentBlobService,
			MetricGroup taskManagerMetricGroup,
			ExecutorService ioExecutor,
			FatalErrorHandler fatalErrorHandler) throws Exception {

		// pre-start checks
		checkTempDirs(taskManagerServicesConfiguration.getTmpDirPaths());

		final TaskEventDispatcher taskEventDispatcher = new TaskEventDispatcher();

		// start the I/O manager, it will create some temp directories.
		final IOManager ioManager = new IOManagerAsync(taskManagerServicesConfiguration.getTmpDirPaths());

		final ShuffleEnvironment<?, ?> shuffleEnvironment = createShuffleEnvironment(
			taskManagerServicesConfiguration,
			taskEventDispatcher,
			taskManagerMetricGroup,
			ioExecutor);
		final int listeningDataPort = shuffleEnvironment.start();

		final KvStateService kvStateService = KvStateService.fromConfiguration(taskManagerServicesConfiguration);
		kvStateService.start();

		final UnresolvedTaskManagerLocation unresolvedTaskManagerLocation = new UnresolvedTaskManagerLocation(
			taskManagerServicesConfiguration.getResourceID(),
			taskManagerServicesConfiguration.getExternalAddress(),
			// we expose the task manager location with the listening port
			// iff the external data port is not explicitly defined
			taskManagerServicesConfiguration.getExternalDataPort() > 0 ?
				taskManagerServicesConfiguration.getExternalDataPort() :
				listeningDataPort);

		final BroadcastVariableManager broadcastVariableManager = new BroadcastVariableManager();

		final TaskSlotTable<Task> taskSlotTable = createTaskSlotTable(
			taskManagerServicesConfiguration.getNumberOfSlots(),
			taskManagerServicesConfiguration.getTaskExecutorResourceSpec(),
			taskManagerServicesConfiguration.getTimerServiceShutdownTimeout(),
			taskManagerServicesConfiguration.getPageSize());

		final JobTable jobTable = DefaultJobTable.create();

		final JobLeaderService jobLeaderService = new DefaultJobLeaderService(unresolvedTaskManagerLocation, taskManagerServicesConfiguration.getRetryingRegistrationConfiguration());

		final String[] stateRootDirectoryStrings = taskManagerServicesConfiguration.getLocalRecoveryStateRootDirectories();

		final File[] stateRootDirectoryFiles = new File[stateRootDirectoryStrings.length];

		for (int i = 0; i < stateRootDirectoryStrings.length; ++i) {
			stateRootDirectoryFiles[i] = new File(stateRootDirectoryStrings[i], LOCAL_STATE_SUB_DIRECTORY_ROOT);
		}

		final TaskExecutorLocalStateStoresManager taskStateManager = new TaskExecutorLocalStateStoresManager(
			taskManagerServicesConfiguration.isLocalRecoveryEnabled(),
			stateRootDirectoryFiles,
			ioExecutor);

		final boolean failOnJvmMetaspaceOomError =
			taskManagerServicesConfiguration.getConfiguration().getBoolean(CoreOptions.FAIL_ON_USER_CLASS_LOADING_METASPACE_OOM);
		final LibraryCacheManager libraryCacheManager = new BlobLibraryCacheManager(
			permanentBlobService,
			BlobLibraryCacheManager.defaultClassLoaderFactory(
				taskManagerServicesConfiguration.getClassLoaderResolveOrder(),
				taskManagerServicesConfiguration.getAlwaysParentFirstLoaderPatterns(),
				failOnJvmMetaspaceOomError ? fatalErrorHandler : null));

		return new TaskManagerServices(
			unresolvedTaskManagerLocation,
			taskManagerServicesConfiguration.getManagedMemorySize().getBytes(),
			ioManager,
			shuffleEnvironment,
			kvStateService,
			broadcastVariableManager,
			taskSlotTable,
			jobTable,
			jobLeaderService,
			taskStateManager,
			taskEventDispatcher,
			ioExecutor,
			libraryCacheManager);
	}

	private static TaskSlotTable<Task> createTaskSlotTable(
			final int numberOfSlots,
			final TaskExecutorResourceSpec taskExecutorResourceSpec,
			final long timerServiceShutdownTimeout,
			final int pageSize) {
		final TimerService<AllocationID> timerService = new TimerService<>(
			new ScheduledThreadPoolExecutor(1),
			timerServiceShutdownTimeout);
		return new TaskSlotTableImpl<>(
			numberOfSlots,
			TaskExecutorResourceUtils.generateTotalAvailableResourceProfile(taskExecutorResourceSpec),
			TaskExecutorResourceUtils.generateDefaultSlotResourceProfile(taskExecutorResourceSpec, numberOfSlots),
			pageSize,
			timerService);
	}

	private static ShuffleEnvironment<?, ?> createShuffleEnvironment(
			TaskManagerServicesConfiguration taskManagerServicesConfiguration,
			TaskEventDispatcher taskEventDispatcher,
			MetricGroup taskManagerMetricGroup,
			Executor ioExecutor) throws FlinkException {

		final ShuffleEnvironmentContext shuffleEnvironmentContext = new ShuffleEnvironmentContext(
			taskManagerServicesConfiguration.getConfiguration(),
			taskManagerServicesConfiguration.getResourceID(),
			taskManagerServicesConfiguration.getNetworkMemorySize(),
			taskManagerServicesConfiguration.isLocalCommunicationOnly(),
			taskManagerServicesConfiguration.getBindAddress(),
			taskEventDispatcher,
			taskManagerMetricGroup,
			ioExecutor);

		return ShuffleServiceLoader
			.loadShuffleServiceFactory(taskManagerServicesConfiguration.getConfiguration())
			.createShuffleEnvironment(shuffleEnvironmentContext);
	}

	/**
	 * Validates that all the directories denoted by the strings do actually exist or can be created, are proper
	 * directories (not files), and are writable.
	 *
	 * @param tmpDirs The array of directory paths to check.
	 * @throws IOException Thrown if any of the directories does not exist and cannot be created or is not writable
	 *                     or is a file, rather than a directory.
	 */
	private static void checkTempDirs(String[] tmpDirs) throws IOException {
		for (String dir : tmpDirs) {
			if (dir != null && !dir.equals("")) {
				File file = new File(dir);
				if (!file.exists()) {
					if (!file.mkdirs()) {
						throw new IOException("Temporary file directory " + file.getAbsolutePath() + " does not exist and could not be created.");
					}
				}
				if (!file.isDirectory()) {
					throw new IOException("Temporary file directory " + file.getAbsolutePath() + " is not a directory.");
				}
				if (!file.canWrite()) {
					throw new IOException("Temporary file directory " + file.getAbsolutePath() + " is not writable.");
				}

				if (LOG.isInfoEnabled()) {
					long totalSpaceGb = file.getTotalSpace() >> 30;
					long usableSpaceGb = file.getUsableSpace() >> 30;
					double usablePercentage = (double) usableSpaceGb / totalSpaceGb * 100;
					String path = file.getAbsolutePath();
					LOG.info(String.format("Temporary file directory '%s': total %d GB, " + "usable %d GB (%.2f%% usable)",
						path, totalSpaceGb, usableSpaceGb, usablePercentage));
				}
			} else {
				throw new IllegalArgumentException("Temporary file directory #$id is null.");
			}
		}
	}
}


text:
local test_env = require("test/test_environment")
local run = test_env.run

test_env.unload_luarocks()

describe("LuaRocks path tests #blackbox #b_path", function()
   before_each(function()
      test_env.setup_specs()
   end)

   it("LuaRocks path bin", function()
      assert.is_true(run.luarocks_bool("path --bin"))
   end)

   it("LuaRocks path lr-path", function()
      assert.is_true(run.luarocks_bool("path --lr-path"))
   end)

   it("LuaRocks path lr-cpath", function()
      assert.is_true(run.luarocks_bool("path --lr-cpath"))
   end)

   it("LuaRocks path with tree", function()
      assert.is_true(run.luarocks_bool("path --tree=lua_modules"))
   end)
end)

redpajama_set_name: RedPajamaGithub


text:
;(function (root, factory, undef) {
	if (typeof exports === "object") {
		// CommonJS
		module.exports = exports = factory(require("./core"));
	}
	else if (typeof define === "function" && define.amd) {
		// AMD
		define(["./core"], factory);
	}
	else {
		// Global (browser)
		factory();
	}
}(this, function (CryptoJS) {

	return CryptoJS.enc.Hex;

}));


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee18766a6e8">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court District of Kansas</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2014-02-25</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2009-01-12</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-6_08-cr-10175</identifier>
<identifier type="local">P0b002ee18766a6e8</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2014-02-25</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2014-02-25</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ksd-6_08-cr-10175</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-6_08-cr-10175</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>6:08-cr-10175</caseNumber>
 <caseOffice>Wichita</caseOffice>
 <caseType>criminal</caseType>
 <party fullName="USA" lastName="USA" role="Plaintiff"></party>
 <party firstName="Frenchie" fullName="Frenchie D. Wilson" lastName="Wilson" middleName="D." role="Defendant"></party>
</extension>
<titleInfo>
 <title>USA v. Wilson</title>
 <partNumber>6:08-cr-10175</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-6_08-cr-10175/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">6:08-cr-10175;08-10175</identifier>
<name type="corporate">
 <namePart>United States District Court District of Kansas</namePart>
 <namePart>10th Circuit</namePart>
 <namePart>Wichita</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>USA</displayForm>
 <namePart type="family">USA</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<name type="personal">
 <displayForm>Frenchie D. Wilson</displayForm>
 <namePart type="family">Wilson</namePart>
 <namePart type="given">Frenchie</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ksd-6_08-cr-10175</accessId>
 <courtType>District</courtType>
 <courtCode>ksd</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtState>Kansas</courtState>
 <courtSortOrder>2190</courtSortOrder>
 <caseNumber>6:08-cr-10175</caseNumber>
 <caseOffice>Wichita</caseOffice>
 <caseType>criminal</caseType>
 <party fullName="USA" lastName="USA" role="Plaintiff"></party>
 <party firstName="Frenchie" fullName="Frenchie D. Wilson" lastName="Wilson" middleName="D." role="Defendant"></party>
 <state>Kansas</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ksd-6_08-cr-10175-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-6_08-cr-10175/USCOURTS-ksd-6_08-cr-10175-0/mods.xml">
 <titleInfo>
  <title>USA v. Wilson</title>
  <subTitle>MEMORANDUM AND ORDER denying 17 Motion to Suppress as to Frenchie D. Wilson (1). Signed by District Judge J. Thomas Marten on 1/12/09. (mss)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2009-01-12</dateIssued>
</originInfo>
 <relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-6_08-cr-10175/pdf/USCOURTS-ksd-6_08-cr-10175-0.pdf">
  <identifier type="FDsys Unique ID">D09002ee18767fdf1</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-6_08-cr-10175/USCOURTS-ksd-6_08-cr-10175-0</identifier>
 <identifier type="former granule identifier">ksd-6_08-cr-10175_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ksd-6_08-cr-10175/USCOURTS-ksd-6_08-cr-10175-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ksd-6_08-cr-10175/pdf/USCOURTS-ksd-6_08-cr-10175-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 6:08-cr-10175; USA v. Wilson; </searchTitle>
  <courtName>United States District Court District of Kansas</courtName>
  <state>Kansas</state>
  <accessId>USCOURTS-ksd-6_08-cr-10175-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2009-01-12</dateIssued>
  <docketText>MEMORANDUM AND ORDER denying 17 Motion to Suppress as to Frenchie D. Wilson (1). Signed by District Judge J. Thomas Marten on 1/12/09. (mss)</docketText>
</extension>
</relatedItem>
</mods>


text:
using System;
using iLoan.Library.DataModels;
using iLoan.Library.DTOs;
using iLoan.Library.Interfaces;

namespace iLoan.Library
{
    public static class LoanFactory
    {
        public static ILoan CreateLoan(LoanDTO loanDto)
        {
            switch (loanDto.Type)
            {
                case LoanType.Series:
                    return new SeriesLoan {Amount = loanDto.Amount, Interest = loanDto.Interest, RepaymentYears = loanDto.RepaymentYears};
                case LoanType.Anuity:
                    return new AnuityLoan {Amount = loanDto.Amount, Interest = loanDto.Interest, RepaymentYears = loanDto.RepaymentYears};
            }

            throw new ArgumentException("Arguments could not be parsed correctly.");
        }
    }
}


text:
from thespian.system.transport import (TransmitIntent, SendStatus,
                                       MAX_TRANSMIT_RETRIES)
from thespian.system.timing import timePeriodSeconds
from datetime import timedelta
from pytest import mark
try: from unittest.mock import patch
except ImportError:
    try: from mock import patch
    except ImportError:
        patch = None
from contextlib import contextmanager

@contextmanager
def update_elapsed_time(time_base, elapsed):
    with patch('thespian.system.timing.currentTime') as p_ctime:
        p_ctime.return_value = time_base + (timePeriodSeconds(elapsed)
                                            if isinstance(elapsed, timedelta)
                                            else elapsed)
        yield p_ctime.return_value

class TestUnitSendStatus(object):

    def testSendStatusSuccess(self):
        assert SendStatus.Sent == SendStatus.Sent
        assert SendStatus.Sent

    def testSendStatusFailures(self):
        assert SendStatus.Failed == SendStatus.Failed
        assert not SendStatus.Failed
        assert SendStatus.NotSent == SendStatus.NotSent
        assert not SendStatus.NotSent
        assert SendStatus.BadPacket == SendStatus.BadPacket
        assert not SendStatus.BadPacket
        assert SendStatus.DeadTarget == SendStatus.DeadTarget
        assert not SendStatus.DeadTarget

    def testSendStatusComparisons(self):
        assert SendStatus.Sent != SendStatus.Failed
        assert SendStatus.Sent != SendStatus.NotSent
        assert SendStatus.Sent != SendStatus.BadPacket
        assert SendStatus.Sent != SendStatus.DeadTarget

        assert SendStatus.Failed != SendStatus.Sent
        assert SendStatus.Failed != SendStatus.NotSent
        assert SendStatus.Failed != SendStatus.BadPacket
        assert SendStatus.Failed != SendStatus.DeadTarget

        assert SendStatus.NotSent != SendStatus.Failed
        assert SendStatus.NotSent != SendStatus.Sent
        assert SendStatus.NotSent != SendStatus.BadPacket
        assert SendStatus.NotSent != SendStatus.DeadTarget

        assert SendStatus.BadPacket != SendStatus.Failed
        assert SendStatus.BadPacket != SendStatus.NotSent
        assert SendStatus.BadPacket != SendStatus.Sent
        assert SendStatus.BadPacket != SendStatus.DeadTarget

        assert SendStatus.DeadTarget != SendStatus.Failed
        assert SendStatus.DeadTarget != SendStatus.NotSent
        assert SendStatus.DeadTarget != SendStatus.BadPacket
        assert SendStatus.DeadTarget != SendStatus.Sent

class TestUnitTransmitIntent(object):

    def testNormalTransmit(self):
        ti = TransmitIntent('addr', 'msg')
        assert ti.targetAddr == 'addr'
        assert ti.message == 'msg'
        assert ti.result == None

    def testNormalTransmitStr(self):
        ti = TransmitIntent('addr', 'msg')
        # Just ensure no exceptions are thrown
        assert str(ti)

    def testNormalTransmitIdentification(self):
        ti = TransmitIntent('addr', 'msg')
        # Just ensure no exceptions are thrown
        assert ti.identify()

    def testNormalTransmitResetAddress(self):
        ti = TransmitIntent('addr', 'msg')
        assert ti.targetAddr == 'addr'
        assert ti.message == 'msg'
        ti.changeTargetAddr('addr2')
        assert ti.targetAddr == 'addr2'
        assert ti.message == 'msg'

    def testNormalTransmitResetMessage(self):
        ti = TransmitIntent('addr', 'msg')
        assert ti.targetAddr == 'addr'
        assert ti.message == 'msg'
        ti.changeMessage('message2')
        assert ti.targetAddr == 'addr'
        assert ti.message == 'message2'

    def testTransmitIntentSetResult(self):
        ti = TransmitIntent('addr', 'msg')
        assert None == ti.result
        ti.result = SendStatus.Sent
        assert ti.result == SendStatus.Sent
        ti.result = SendStatus.Failed
        assert ti.result == SendStatus.Failed

    def testTransmitIntentSetBadResultType(self):
        ti = TransmitIntent('addr', 'msg')
        assert None == ti.result

    def _success(self, result, intent):
        self.successes.append( (result, intent) )
    def _failed(self, result, intent):
        self.failures.append( (result, intent) )

    def testTransmitIntentCallbackSuccess(self):
        ti = TransmitIntent('addr', 'msg')
        ti.result = SendStatus.Sent
        # Ensure no exception thrown
        ti.completionCallback()
        # And again
        ti.completionCallback()

    def testTransmitIntentCallbackFailureNotSent(self):
        ti = TransmitIntent('addr', 'msg')
        ti.result = SendStatus.NotSent
        # Ensure no exception thrown
        ti.completionCallback()
        # And again
        ti.completionCallback()

    def testTransmitIntentCallbackFailureFailed(self):
        ti = TransmitIntent('addr', 'msg')
        ti.result = SendStatus.Failed
        # Ensure no exception thrown
        ti.completionCallback()
        # And again
        ti.completionCallback()

    def testTransmitIntentCallbackSuccessWithTarget(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.Sent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti)]
        assert self.failures == []
        # And again
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti)]
        assert self.failures == []

    def testTransmitIntentCallbackFailureNotSentWithTarget(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.NotSent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti)]
        # And again
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti)]

    def testTransmitIntentCallbackFailureFailedWithTarget(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.Failed
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti)]
        # And again
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti)]

    def testTransmitIntentCallbackSuccessWithChainedTargets(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.addCallback(self._success, self._failed)
        ti.result = SendStatus.Sent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti), (SendStatus.Sent, ti)]
        assert self.failures == []
        # And again
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti), (SendStatus.Sent, ti)]
        assert self.failures == []

    def testTransmitIntentCallbackFailureNotSentWithChainedTargets(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.addCallback(self._success, self._failed)
        ti.result = SendStatus.NotSent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti),
                                 (SendStatus.NotSent, ti)]
        # And again
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti),
                                 (SendStatus.NotSent, ti)]

    def testTransmitIntentCallbackFailureFailedWithChainedTargets(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.addCallback(self._success, self._failed)
        ti.result = SendStatus.Failed
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti),
                                 (SendStatus.Failed, ti)]
        # And again
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti),
                                 (SendStatus.Failed, ti)]

    def testTransmitIntentCallbackSuccessWithChangedTargetsAdded(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.Sent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti)]
        assert self.failures == []
        # And again
        ti.addCallback(self._success, self._failed)
        ti.completionCallback()
        assert self.successes == [(SendStatus.Sent, ti), (SendStatus.Sent, ti)]
        assert self.failures == []

    def testTransmitIntentCallbackFailureNotSentWithChangedTargetsAdded(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.NotSent
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti)]
        # And again
        ti.addCallback(self._success, self._failed)
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.NotSent, ti),
                                 (SendStatus.NotSent, ti)]

    def testTransmitIntentCallbackFailureFailedWithChangedTargetsAdded(self):
        self.successes = []
        self.failures = []
        ti = TransmitIntent('addr', 'msg',
                            onSuccess = self._success,
                            onError = self._failed)
        ti.result = SendStatus.Failed
        # Ensure no exception thrown
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti)]
        # And again
        ti.addCallback(self._success, self._failed)
        ti.completionCallback()
        assert self.successes == []
        assert self.failures == [(SendStatus.Failed, ti),
                                 (SendStatus.Failed, ti)]

    def testTransmitIntentRetry(self):
        ti = TransmitIntent('addr', 'msg')
        for x in range(MAX_TRANSMIT_RETRIES+1):
            assert ti.retry()
        assert not ti.retry()

    @mark.skipif(not patch, reason='requires mock patch')
    def testTransmitIntentRetryTiming(self):
        maxPeriod = timedelta(milliseconds=90)
        period = timedelta(milliseconds=30)
        now = 0.01
        timepad = timedelta(microseconds=10) # avoid float imprecision
        with update_elapsed_time(now, timedelta(0)):
            ti = TransmitIntent('addr', 'msg',
                                maxPeriod=maxPeriod,
                                retryPeriod=period)
            assert not ti.timeToRetry()

        with update_elapsed_time(now, period + timepad):
            assert not ti.timeToRetry()

            assert ti.retry()
            assert not ti.timeToRetry()

        with update_elapsed_time(now, period + period + timepad):
            assert ti.timeToRetry()
            assert ti.retry()
            assert not ti.timeToRetry()

        with update_elapsed_time(now, period * 3 + timepad):
            assert not ti.timeToRetry()  # Each retry increases

        with update_elapsed_time(now, period * 4 + timepad):
            assert ti.timeToRetry()
            assert not ti.retry()  # Exceeds maximum time

    @mark.skipif(not patch, reason='requires mock patch')
    def testTransmitIntentRetryTimingExceedsLimit(self):
        maxPeriod = timedelta(seconds=90)
        period = timedelta(microseconds=1)
        now = 1.23
        timepad = timedelta(microseconds=10) # avoid float imprecision
        with update_elapsed_time(now, timedelta(0)):
            ti = TransmitIntent('addr', 'msg',
                                maxPeriod=maxPeriod,
                                retryPeriod=period)
            assert not ti.timeToRetry()

        timeoffset = timedelta(0)
        for N in range(MAX_TRANSMIT_RETRIES+1):
            # Indicate "failure" and the need to retry
            with update_elapsed_time(now, timeoffset + timepad):
                assert ti.retry()
            # Wait for the indication that it is time to retry
            time_to_retry = False
            for x in range(90):
                with update_elapsed_time(now, timeoffset + timepad):
                    # Only call timeToRetry once, because it auto-resets
                    time_to_retry = ti.timeToRetry()
                    if time_to_retry: break
                timeoffset += (period + (period / 2))
                # = period * 1.5, but python2 cannot multiply
                # timedelta by fractions.
            assert time_to_retry

        with update_elapsed_time(now, timeoffset + timepad):
            assert not ti.retry()

    def testTransmitIntentDelay(self):
        maxPeriod = timedelta(milliseconds=90)
        period = timedelta(milliseconds=30)
        ti = TransmitIntent('addr', 'msg',
                            maxPeriod=maxPeriod,
                            retryPeriod=period)
        delay = ti.delay()
        assert delay > timedelta(milliseconds=88)
        assert delay < timedelta(milliseconds=91)

    def testTransmitIntentRetryDelay(self):
        maxPeriod = timedelta(milliseconds=90)
        period = timedelta(milliseconds=30)
        ti = TransmitIntent('addr', 'msg',
                            maxPeriod=maxPeriod,
                            retryPeriod=period)
        ti.retry()
        delay = ti.delay()
        assert delay > timedelta(milliseconds=28)
        assert delay < timedelta(milliseconds=31)

    def testTransmitIntentRetryRetryDelay(self):
        maxPeriod = timedelta(milliseconds=90)
        period = timedelta(milliseconds=30)
        ti = TransmitIntent('addr', 'msg',
                            maxPeriod=maxPeriod,
                            retryPeriod=period)
        ti.retry()
        ti.retry()
        delay = ti.delay()
        assert delay > timedelta(milliseconds=58)
        assert delay < timedelta(milliseconds=61)


text:
#pragma once
#include <aws/textract/Textract_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Textract
{
namespace Model
{

  /**
   *
The bounding box around the detected page, text, key-value pair, table, table
   * cell, or selection element on a document page. The left
   * (x-coordinate) and top (y-coordinate) are coordinates that
   * represent the top and left sides of the bounding box. Note that the upper-left
   * corner of the image is the origin (0,0).

The top and
   * left values returned are ratios of the overall document page size.
   * For example, if the input image is 700 x 200 pixels, and the top-left coordinate
   * of the bounding box is 350 x 50 pixels, the API returns a left
   * value of 0.5 (350/700) and a top value of 0.25 (50/200).

The
   * width and height values represent the dimensions of
   * the bounding box as a ratio of the overall document page dimension. For example,
   * if the document page size is 700 x 200 pixels, and the bounding box width is 70
   * pixels, the width returned is 0.1.

See Also:
   AWS
   * API Reference

   */
  class AWS_TEXTRACT_API BoundingBox
  {
  public:
    BoundingBox();
    BoundingBox(Aws::Utils::Json::JsonView jsonValue);
    BoundingBox& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The width of the bounding box as a ratio of the overall document page
     * width.

     */
    inline double GetWidth() const{ return m_width; }

    /**
     *
The width of the bounding box as a ratio of the overall document page
     * width.

     */
    inline bool WidthHasBeenSet() const { return m_widthHasBeenSet; }

    /**
     *
The width of the bounding box as a ratio of the overall document page
     * width.

     */
    inline void SetWidth(double value) { m_widthHasBeenSet = true; m_width = value; }

    /**
     *
The width of the bounding box as a ratio of the overall document page
     * width.

     */
    inline BoundingBox& WithWidth(double value) { SetWidth(value); return *this;}

    /**
     *
The height of the bounding box as a ratio of the overall document page
     * height.

     */
    inline double GetHeight() const{ return m_height; }

    /**
     *
The height of the bounding box as a ratio of the overall document page
     * height.

     */
    inline bool HeightHasBeenSet() const { return m_heightHasBeenSet; }

    /**
     *
The height of the bounding box as a ratio of the overall document page
     * height.

     */
    inline void SetHeight(double value) { m_heightHasBeenSet = true; m_height = value; }

    /**
     *
The height of the bounding box as a ratio of the overall document page
     * height.

     */
    inline BoundingBox& WithHeight(double value) { SetHeight(value); return *this;}

    /**
     *
The left coordinate of the bounding box as a ratio of overall document page
     * width.

     */
    inline double GetLeft() const{ return m_left; }

    /**
     *
The left coordinate of the bounding box as a ratio of overall document page
     * width.

     */
    inline bool LeftHasBeenSet() const { return m_leftHasBeenSet; }

    /**
     *
The left coordinate of the bounding box as a ratio of overall document page
     * width.

     */
    inline void SetLeft(double value) { m_leftHasBeenSet = true; m_left = value; }

    /**
     *
The left coordinate of the bounding box as a ratio of overall document page
     * width.

     */
    inline BoundingBox& WithLeft(double value) { SetLeft(value); return *this;}

    /**
     *
The top coordinate of the bounding box as a ratio of overall document page
     * height.

     */
    inline double GetTop() const{ return m_top; }

    /**
     *
The top coordinate of the bounding box as a ratio of overall document page
     * height.

     */
    inline bool TopHasBeenSet() const { return m_topHasBeenSet; }

    /**
     *
The top coordinate of the bounding box as a ratio of overall document page
     * height.

     */
    inline void SetTop(double value) { m_topHasBeenSet = true; m_top = value; }

    /**
     *
The top coordinate of the bounding box as a ratio of overall document page
     * height.

     */
    inline BoundingBox& WithTop(double value) { SetTop(value); return *this;}

  private:

    double m_width;
    bool m_widthHasBeenSet;

    double m_height;
    bool m_heightHasBeenSet;

    double m_left;
    bool m_leftHasBeenSet;

    double m_top;
    bool m_topHasBeenSet;
  };

} // namespace Model
} // namespace Textract
} // namespace Aws


text:
package net.cloudslides.app;

import net.cloudslides.app.model.User;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;

public class HomeApp extends Application {

	private static HomeApp ApplicationInstance = null;
	private static User localuser = null;

	/**
	 * 检查程序是否第一次启动。
	 * @author Felix
	 * @return 是否第一次运行
	 */
	public boolean isFirstLaunch() {

		SharedPreferences sharedPreferences = getSharedPreferences(Define.CONFINFO,MODE_PRIVATE);
		return sharedPreferences.getBoolean(Define.APP_IS_FIRST_LAUNCH_KEY, true);
	}

	/**
	 * 标记程序已经启动过。
	 * @author Felix
	 */
	public void markLaunched() {

		SharedPreferences sharedPreferences = getSharedPreferences(	Define.CONFINFO,MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putBoolean(Define.APP_IS_FIRST_LAUNCH_KEY, false);
		editor.commit();
	}

	/**
	 * 获取当前应用程序的 Application 对象。
	 * @author Felix
	 * @return 全局Application单类对象
	 */
	public static HomeApp getMyApplication() {
		return ApplicationInstance;
	}

	/**
	 * 获取本地用户
	 * @author Felix
	 */
	public static User getLocalUser(){
		return localuser;
	}

	/**
	 * 配置本地用户
	 * @author Felix
	 */
	public static void setLocalUser(User user)
	{
		localuser=user;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		ApplicationInstance = this;
		initImageLoader(getApplicationContext());
	}
	/**
	 * 初始化imageloader
	 * @param context
	 * @author Felix
	 */

	public static void initImageLoader(Context context) {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
        .cacheInMemory(true)
        .cacheOnDisc(true)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .showImageOnFail(R.drawable.ic_error)
        .showStubImage(R.drawable.empty_picture_144)
        .showImageForEmptyUri(R.drawable.ic_error)
        .build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
		.tasksProcessingOrder(QueueProcessingType.LIFO)
		.defaultDisplayImageOptions(options)
		.threadPoolSize(3)
		.build();
		Log.d("cache存储路径",StorageUtils.getCacheDirectory(getMyApplication()).getAbsolutePath());
		ImageLoader.getInstance().init(config);
		Log.i("initImageLoader", "初始化uil");
	}
}


text:
const path = require('path');

// External Paths:
// Paths used for writing files and navigating the package source
const rootDirectory = path.resolve(__dirname, '../');
const componentsDirectory = path.join(rootDirectory, '.gulp/components/');
const optionsDirectory = `${componentsDirectory}options/`;

// Internal Paths:
// Paths used inside themes, schemes, widgets, etc.
// Relative to the Sublime Text Packages directory
//
// Sublime Text expects forward-slashed paths
const packagesRoot = 'Packages/gruvbox/';
const assetsDirectory = 'gruvbox/assets/';
const commonsDirectory = `${assetsDirectory}commons/`;

const midstroke = `${commonsDirectory}midstroke__`;
const spacegray = `${commonsDirectory}spacegray__`;
const thick = `${commonsDirectory}thick__`;

const paths = {
  external: {
    root: rootDirectory,
    components: componentsDirectory,
    options: optionsDirectory,
  },
  internal: {
    packagesRoot,
    assets: assetsDirectory,
    commons: commonsDirectory,
    midstroke,
    spacegray,
    thick,
  },
};

module.exports = paths;


text:
require 'research/asterism.rb'

include Geometry

red=DrawStyle.new
red.line_thickness = 5
red.line_color = 0
red.line_alpha = 1
red.fill = true
red.fill_color = 0xFF5522
rectangle({:x=>43, :y=>16, :width=>100, :height=>20, :style=>red}).draw(TopSprite)
blue = red.clone
blue.fill_color = 0x2255FF
blue.fill_alpha = 0.2
c = circle ({:x=>50, :y=>80, :radius =>30, :style=>blue })
c.draw(TopSprite)


text:
package com.platypii.baseline.util.cache;

import androidx.annotation.NonNull;
import com.google.gson.reflect.TypeToken;
import com.platypii.baseline.util.LocalCache;
import java.lang.reflect.Type;
import java.util.List;

class TestCache extends LocalCache<String> {
    TestCache() {
        super("cloud.cache.test");
    }

    @NonNull
    @Override
    public Type listType() {
        return new TypeToken<List<String>>(){}.getType();
    }

    @NonNull
    @Override
    public String getId(@NonNull String item) {
        return item;
    }
}


text:
<?php
$this->breadcrumbs=array(
	'Users'=>array('index'),
	$model->id,
);

$this->menu=array(
	array('label'=>'List User','url'=>array('index')),
	array('label'=>'Create User','url'=>array('create')),
	array('label'=>'Update User','url'=>array('update','id'=>$model->id)),
	array('label'=>'Delete User','url'=>'#','linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
	array('label'=>'Manage User','url'=>array('admin')),
);
?>

<?php echo CHtml::image('images/users_48.png', ''); ?> View User #<?php echo $model->id; ?>

<?php $this->widget('bootstrap.widgets.TbDetailView',array(
	'data'=>$model,
	'attributes'=>array(
		'id',
		'email',
		'password',
		'is_admin',
		'blocked',
                'created'
	),
)); ?>


text:
---
uid: SolidEdgeDraft.ModelLink.Range3d(System.Double@,System.Double@,System.Double@,System.Double@,System.Double@,System.Double@,System.Object,System.Object)
summary:
remarks:
syntax:
    parameters:
    - id: ConfigFileName
      description: Specifies the name of a configuration file to be used in creating the projection.
    - id: ConfigurationName
      description: Specifies a configuration name within the identified configuration file to be used in creating the projection.
    - id: highX
      description: Specifies the x coordinate of the upper right corner of the referenced object.
    - id: highY
      description: Specifies the y coordinate of the upper right corner of the referenced object.
    - id: highZ
      description: Specifies the z coordinate of the upper right corner of the referenced object.
    - id: lowX
      description: Specifies the x coordinate of the lower left corner of the referenced object.
    - id: lowY
      description: Specifies the y coordinate of the lower left corner of the referenced object.
    - id: lowZ
      description: Specifies the z coordinate of the lower left corner of the referenced object.
---


text:
/*global $:true process_vidly_status_response:true */

$(function() {
    'use strict';
    // Previously checked approval groups can not be unchecked
    $('input[name="approvals"]:checked').each(function() {
        $(this)
          .attr('disabled', 'disabled')
          .attr('title', "You can't uncheck previously requested approvals")
          .parents('label')
            .addClass('un-uncheckable')
            .append($('<small>').text("(Once checked, you can't uncheck it)"));
    });

    if ($('#vidly-submission').length) {
        var $element = $('#vidly-submission');
        $.ajax({
          url: '/manage/vidly/status/',
          data: {id: $element.data('id')},
          success: function(response) {
              process_vidly_status_response(response, $element);
          }
        });
    }

    // Curated groups is only available during event edit
    // Autocomplete curated groups
    function process_curated_groups(element, callback) {
        var data = [];
        $(element.val().split(',')).each(function () {
            data.push({id: this, text: this});
        });
        console.log('process_curated_groups');console.dir(data);
        callback(data);
    }

    $('#id_recruitmentmessage').select2();
    $('#id_curated_groups').select2({
        placeholder: "Search for a Mozillians group",
        tags: [],
        minimumInputLength: 2,
        ajax: {
            url: '/manage/curated-groups-autocomplete/',
            dataType: 'json',
            data: function (term, page) {
                return {q: term};
            },
            results: function (data, page) {
                //console.log('DATA');
                //console.dir(data);
                var rows = [];
                $.each(data.groups, function(i, group) {
                    rows.push({id: group[0], text: group[1]});
                });
                return {results: rows};
            },
        },
        formatSelection: function(object) {
            console.log('OBJECT', object);
            return object.id;
        },
        xxxmatcher: function (term, text, option) {
            console.log('term', term, 'text', text);
            return false;
        },
        initSelection: process_curated_groups
    });

    // due to our integration with bootstrap 3 we have to do this to all select2 widgets
    $('#id_curated_groups').css('width', '100%');
    $('#id_recruitmentmessage').css('width', '100%');

    var url = $('#privacy-vidly-mismatch').data('url');
    $.getJSON(url)
    .then(function(response) {
        if (response) {
            $('#privacy-vidly-mismatch').show();
        }
    });

    $('a.really-delete').click(function() {
        $('.really-delete-metadata').toggle();
        $('.really-delete-confirmation').toggle();
        return false;
    });
    $('.really-delete-confirmation a.cancel').click(function() {
        $('.really-delete-metadata').toggle();
        $('.really-delete-confirmation').toggle();
        return false;
    });
});


text:
package drift

import (
  "log"
  "io/ioutil"
)

type revision struct {
  data  []byte
  path  string
}

type changeset struct {
  headers string
  sql     string
}

// Reads a file from a path and parses the file into a revision struct
// the filesystem argument represents a generic filesystem
// OSFileSystem is an implemention of the local filesystem
// this can be used by ReadRevision('mypath', OSFileSystem{})
func ReadRevision(path string, fs filesystem) (*revision, error){
  f, err := fs.Open(path)
  if err != nil {
    return nil, err
  }
  defer f.Close()
  out, err := ioutil.ReadAll(f)
  if err != nil {
    return nil, err
  }
  return &revision{out, path}, nil
}

// parses the changesets out of a revision file
func ParseChangesets(rev *revision) ([]changeset, error){
  s := NewScanner(rev.data)
  for s.HasMoreTokens() {
    tok, err := s.NextToken()
    if err != nil {
      log.Println(err)
    } else {
      log.Println(string(tok.runes), " : ", s.offset)
    }
  }
  return nil, nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Signum.Utilities;
using Signum.Entities;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using Signum.Engine.Linq;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.DataStructures;
using NpgsqlTypes;

namespace Signum.Engine.Maps
{
    public partial class Table
    {
        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Expression? id = GetIdExpression(tableAlias);

            if (IsView)
            {
                var bindings = this.Fields.Values.Select(ef => new FieldBinding(ef.FieldInfo, ef.Field.GetExpression(tableAlias, binder, id!, null))).ToReadOnly();

                var hasValue = id == null ? Expression.Constant(true): SmartEqualizer.NotEqualNullable(id, Expression.Constant(null, id.Type.Nullify()));

                return new EmbeddedEntityExpression(this.Type, hasValue, bindings, null, this);
            }
            else
            {
                Schema.Current.AssertAllowed(Type, inUserInterface: false);

                var period = GenerateSystemPeriod(tableAlias, binder);
                var bindings = GenerateBindings(tableAlias, binder, id!, period);
                var mixins = GenerateMixins(tableAlias, binder, id!, period);

                var result = new EntityExpression(this.Type, (PrimaryKeyExpression)id!, period, tableAlias, bindings, mixins, period, avoidExpandOnRetrieving: false);

                return result;
            }
        }

        internal static ConstructorInfo intervalConstructor = typeof(Interval<DateTime>).GetConstructor(new[] { typeof(DateTime), typeof(DateTime) })!;

        internal IntervalExpression? GenerateSystemPeriod(Alias tableAlias, QueryBinder binder, bool force = false)
        {
            return this.SystemVersioned != null && (force || binder.systemTime is SystemTime.Interval) ? new IntervalExpression(typeof(Interval<DateTime>),
                this.SystemVersioned.StartColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                this.SystemVersioned.EndColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                this.SystemVersioned.PostgreeSysPeriodColumnName?.Let(c => new ColumnExpression(typeof(NpgsqlRange<DateTime>), tableAlias, c)),
                asUtc: true
            ) : null;
        }

        internal ReadOnlyCollection<FieldBinding> GenerateBindings(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            List<FieldBinding> result = new List<FieldBinding>
            {
                new FieldBinding(Table.fiId, id)
            };

            foreach (var ef in this.Fields.Values)
            {
                var fi = ef.FieldInfo;

                if (!ReflectionTools.FieldEquals(fi, fiId))
                    result.Add(new FieldBinding(fi, ef.Field.GetExpression(tableAlias, binder, id, period)));
            }

            if (this.Type.IsEntity())
                result.AddRange(Schema.Current.GetAdditionalQueryBindings(PropertyRoute.Root(this.Type), (PrimaryKeyExpression)id, period));

            return result.ToReadOnly();
        }

        internal ReadOnlyCollection<MixinEntityExpression>? GenerateMixins(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            if (this.Mixins == null)
                return null;

            return this.Mixins.Values.Select(m => (MixinEntityExpression)m.GetExpression(tableAlias, binder, id, period)).ToReadOnly();
        }

        internal Expression? GetIdExpression(Alias alias)
        {
            var field = Fields.TryGetC(Table.fiId.Name);

            if (field == null)
            {
                field = GetViewPrimaryKey();
                if (field == null)
                    return null;

                if (field.Field is FieldReference fr)
                    return new ColumnExpression(Signum.Entities.PrimaryKey.Type(fr.ReferenceTable.Type).Nullify(), alias, fr.Name);
            }

            return field.Field!.GetExpression(alias, null!, null!, null);
        }

        public EntityField? GetViewPrimaryKey()
        {
            return Fields.Values.FirstOrDefault(f => f.Field is IColumn && ((IColumn)f.Field).PrimaryKey);
        }

        ColumnExpression ITablePrivate.GetPrimaryOrder(Alias alias)
        {
            var res = GetIdExpression(alias);

            return res is PrimaryKeyExpression pe?
                (ColumnExpression)pe.Value :
                (ColumnExpression)res!;
        }
    }

    public partial class TableMList
    {
        internal PrimaryKeyExpression RowIdExpression(Alias tableAlias)
        {
            var primary = (IColumn)this.PrimaryKey;

            return new PrimaryKeyExpression(new ColumnExpression(primary.Type.Nullify(), tableAlias, primary.Name));
        }

        internal PrimaryKeyExpression BackColumnExpression(Alias tableAlias)
        {
            return new PrimaryKeyExpression(new ColumnExpression(BackReference.Type.Nullify(), tableAlias, BackReference.Name));
        }

        internal ColumnExpression OrderExpression(Alias tableAlias)
        {
            return new ColumnExpression(typeof(int), tableAlias, ((IColumn)this.Order!).Name);
        }

        internal Expression FieldExpression(Alias tableAlias, QueryBinder binder, IntervalExpression? externalPeriod, bool withRowId)
        {
            var rowId = RowIdExpression(tableAlias);

            var exp = Field.GetExpression(tableAlias, binder, rowId, externalPeriod);

            if (!withRowId)
                return exp;

            var type = this.Field.FieldType;

            var ci = typeof(MList<>.RowIdElement).MakeGenericType(type).GetConstructor(new[] { type, typeof(PrimaryKey), typeof(int?) });

            var order =  Order == null ? (Expression)Expression.Constant(null, typeof(int?)) : OrderExpression(tableAlias).Nullify();

            return Expression.New(ci, exp, rowId.UnNullify(), order);
        }

        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Schema.Current.AssertAllowed(this.BackReference.ReferenceTable.Type, inUserInterface: false);

            Type elementType = typeof(MListElement<,>).MakeGenericType(BackReference.FieldType, Field.FieldType);

            var rowId = RowIdExpression(tableAlias);
            IntervalExpression? period = GenerateSystemPeriod(tableAlias, binder);

            return new MListElementExpression(
                rowId,
                (EntityExpression)this.BackReference.GetExpression(tableAlias, binder, null!, period),
                this.Order == null ? null : OrderExpression(tableAlias),
                this.Field.GetExpression(tableAlias, binder, rowId, period),
                period,
                this,
                tableAlias);
        }

        internal IntervalExpression? GenerateSystemPeriod(Alias tableAlias, QueryBinder binder, bool force = false)
        {
            return this.SystemVersioned != null && (force || binder.systemTime is SystemTime.Interval) ? new IntervalExpression(typeof(Interval<DateTime>),
                this.SystemVersioned.StartColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                this.SystemVersioned.EndColumnName?.Let(c => new ColumnExpression(typeof(DateTime), tableAlias, c)),
                this.SystemVersioned.PostgreeSysPeriodColumnName?.Let(c => new ColumnExpression(typeof(NpgsqlRange<DateTime>), tableAlias, c)),
                asUtc: true
            ) : null;
        }

        ColumnExpression ITablePrivate.GetPrimaryOrder(Alias alias)
        {
            return (ColumnExpression)RowIdExpression(alias).Value;
        }
    }

    public abstract partial class Field
    {
        internal abstract Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period);
    }

    public partial class FieldPrimaryKey
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            return new PrimaryKeyExpression(new ColumnExpression(this.Type.Nullify(), tableAlias, this.Name).Nullify());
        }
    }

    public partial class FieldValue
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            var column = new ColumnExpression(this.Type, tableAlias, this.Name);

            if(this.Type == this.FieldType)
                return column;

            return Expression.Convert(column, this.FieldType);
        }
    }

    public partial class FieldTicks
    {
        public static readonly PropertyInfo piDateTimeTicks = ReflectionTools.GetPropertyInfo((DateTime d) => d.Ticks);

        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            if (this.Type == this.FieldType)
               return new ColumnExpression(this.Type, tableAlias, this.Name);

            if (this.Type == typeof(DateTime))
                return Expression.Property(new ColumnExpression(this.Type, tableAlias, this.Name), piDateTimeTicks);

            throw new NotImplementedException("FieldTicks of type {0} not supported".FormatWith(this.Type));
        }
    }

    public partial class FieldReference
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            Type cleanType = IsLite ? Lite.Extract(FieldType)! : FieldType;

            var result = new EntityExpression(cleanType, new PrimaryKeyExpression(new ColumnExpression(this.Type.Nullify(), tableAlias, Name)), period, null, null, null, null, AvoidExpandOnRetrieving);

            if(this.IsLite)
                return binder.MakeLite(result, null);
            else
                return result;
        }
    }

    public partial class FieldEnum
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            return Expression.Convert(new ColumnExpression(this.Type, tableAlias, Name), FieldType);
        }
    }

    public partial class FieldMList
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            return new MListExpression(FieldType, (PrimaryKeyExpression)id, period, TableMList); // keep back id empty for some seconds
        }
    }

    public partial class FieldEmbedded
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            var bindings = (from kvp in EmbeddedFields
                            let fi = kvp.Value.FieldInfo
                            select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id, period)))
                            .Concat(Schema.Current.GetAdditionalQueryBindings(this.Route, (PrimaryKeyExpression)id, period))
                            .ToReadOnly();

            Expression hasValue = HasValue == null ? SmartEqualizer.NotEqualNullable(id,
                id is PrimaryKeyExpression ? QueryBinder.NullId(((PrimaryKeyExpression)id).ValueType) : (Expression)Expression.Constant(null, id.Type.Nullify())) :
                new ColumnExpression(((IColumn)HasValue).Type, tableAlias, HasValue.Name);

            return new EmbeddedEntityExpression(this.FieldType, hasValue, bindings, this, null);
        }
    }

    public partial class FieldMixin
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            var bindings = (from kvp in Fields
                            let fi = kvp.Value.FieldInfo
                            select new FieldBinding(fi, kvp.Value.Field.GetExpression(tableAlias, binder, id, period)))
                            .Concat(Schema.Current.GetAdditionalQueryBindings(this.Route, (PrimaryKeyExpression)id, period))
                            .ToReadOnly();

            return new MixinEntityExpression(this.FieldType, bindings, tableAlias, this);
        }
    }

    public partial class FieldImplementedBy
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            var implementations = ImplementationColumns.SelectDictionary(t => t, (t, ic) =>
                 new EntityExpression(t, new PrimaryKeyExpression(new ColumnExpression(ic.Type.Nullify(), tableAlias, ic.Name)), period, null, null, null, null, AvoidExpandOnRetrieving));

            var result = new ImplementedByExpression(IsLite ? Lite.Extract(FieldType)! : FieldType, SplitStrategy, implementations);

            if (this.IsLite)
                return binder.MakeLite(result, null);
            else
                return result;
        }
    }

    public partial class FieldImplementedByAll
    {
        internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression? period)
        {
            Expression result = new ImplementedByAllExpression(
                IsLite ? Lite.Extract(FieldType)! : FieldType,
                new ColumnExpression(Column.Type, tableAlias, Column.Name),
                new TypeImplementedByAllExpression(new PrimaryKeyExpression(new ColumnExpression(ColumnType.Type.Nullify(), tableAlias, ColumnType.Name))),
                period);

            if (this.IsLite)
                return binder.MakeLite(result, null);
            else
                return result;
        }
    }
}


text:
var Yadda = require('yadda');
Yadda.plugins.mocha.ScenarioLevelPlugin.init();

var mongoose = require('mongoose');

process.env.DB = 'subTest';

require('../../examples/subresource/app');
var library = require('./definitions/sub.steps');

var parentResource = require('../../examples/subresource/resources/parent');

new Yadda.FeatureFileSearch('test/subresource').each(function(file) {
  featureFile(file, function(feature) {
    var yadda = Yadda.createInstance(library);

    afterEach((done) => {
      parentResource.db.connection.db.dropDatabase(function(err, result) {
        done();
      });
    });

    scenarios(feature.scenarios, function(scenario, done) {
      yadda.run(scenario.steps, done);
    });
  });
});


text:
/*
Problem 7.* Arithmetical expressions
    • Write a program that calculates the value of given arithmetical expression.
    • The expression can contain the following elements only:
        ◦ Real numbers, e.g.  5 ,  18.33 ,  3.14159 ,  12.6
        ◦ Arithmetic operators:  + ,  - ,  * ,  /  (standard priorities)
        ◦ Mathematical functions:  ln(x) ,  sqrt(x) ,  pow(x,y)
        ◦ Brackets (for changing the default priorities):  ( ,  )
Examples:

                input                                   output

(3+5.3) * 2.7 - ln(22) / pow(2.2, -1.7)                 ~10.6

pow(2, 3.14) * (3 - (3 * sqrt(2) - 3.2) + 1.5*0.3)      ~21.22

Hint: Use the classical Shunting-yard algorithm and Reverse Polish notation.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _07_ArithmeticalExpressions
{
    class ArithmeticalExpressions
    {
        static void Main(string[] args)
        {
        }
    }
}


text:
package cloudcallcenter

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// BeginContactFlowVersionModification invokes the cloudcallcenter.BeginContactFlowVersionModification API synchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/begincontactflowversionmodification.html
func (client *Client) BeginContactFlowVersionModification(request *BeginContactFlowVersionModificationRequest) (response *BeginContactFlowVersionModificationResponse, err error) {
	response = CreateBeginContactFlowVersionModificationResponse()
	err = client.DoAction(request, response)
	return
}

// BeginContactFlowVersionModificationWithChan invokes the cloudcallcenter.BeginContactFlowVersionModification API asynchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/begincontactflowversionmodification.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) BeginContactFlowVersionModificationWithChan(request *BeginContactFlowVersionModificationRequest) (<-chan *BeginContactFlowVersionModificationResponse, <-chan error) {
	responseChan := make(chan *BeginContactFlowVersionModificationResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.BeginContactFlowVersionModification(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// BeginContactFlowVersionModificationWithCallback invokes the cloudcallcenter.BeginContactFlowVersionModification API asynchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/begincontactflowversionmodification.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) BeginContactFlowVersionModificationWithCallback(request *BeginContactFlowVersionModificationRequest, callback func(response *BeginContactFlowVersionModificationResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *BeginContactFlowVersionModificationResponse
		var err error
		defer close(result)
		response, err = client.BeginContactFlowVersionModification(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// BeginContactFlowVersionModificationRequest is the request struct for api BeginContactFlowVersionModification
type BeginContactFlowVersionModificationRequest struct {
	*requests.RpcRequest
	ContactFlowId string `position:"Body" name:"ContactFlowId"`
	InstanceId    string `position:"Body" name:"InstanceId"`
}

// BeginContactFlowVersionModificationResponse is the response struct for api BeginContactFlowVersionModification
type BeginContactFlowVersionModificationResponse struct {
	*responses.BaseResponse
	RequestId      string      `json:"RequestId" xml:"RequestId"`
	Success        bool        `json:"Success" xml:"Success"`
	Code           string      `json:"Code" xml:"Code"`
	Message        string      `json:"Message" xml:"Message"`
	HttpStatusCode int         `json:"HttpStatusCode" xml:"HttpStatusCode"`
	ContactFlow    ContactFlow `json:"ContactFlow" xml:"ContactFlow"`
}

// CreateBeginContactFlowVersionModificationRequest creates a request to invoke BeginContactFlowVersionModification API
func CreateBeginContactFlowVersionModificationRequest() (request *BeginContactFlowVersionModificationRequest) {
	request = &BeginContactFlowVersionModificationRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("CloudCallCenter", "2017-07-05", "BeginContactFlowVersionModification", "", "")
	request.Method = requests.POST
	return
}

// CreateBeginContactFlowVersionModificationResponse creates a response to parse from BeginContactFlowVersionModification response
func CreateBeginContactFlowVersionModificationResponse() (response *BeginContactFlowVersionModificationResponse) {
	response = &BeginContactFlowVersionModificationResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Mulodo PHP Trainning Laravel 5</title>

<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- TODC Bootstrap theme -->
<link href="css/todc-bootstrap.min.css" rel="stylesheet">

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
@include('todc.nav');
	<!--main-->
	@yield('content')
	<!--/main-->

	<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
	<script
		src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	<!-- Include all compiled plugins (below), or include individual files as needed -->
	<script src="js/bootstrap.min.js"></script>
</body>
</html>


text:
export * from './client.decorator';
export * from './ctx.decorator';
export * from './event-pattern.decorator';
export * from './grpc-service.decorator';
export * from './message-pattern.decorator';
export * from './payload.decorator';


text:
      {{message.owner || 'Anonymous'}}
      {{message.content}}

    <form class="form" name="form" ng-submit="chat.postMessage(form)" novalidate>
      <input type="text" name="content" class="chat-input" ng-model="chat.chatMessage.content" ng-minlength="10" ng-maxlength="200" required="" placeholder="Between 10 and 200 symbols"></input>
      <button class="btn chat-post-button" type="submit">Post</button>
    </form>


text:
"use strict";
define(['settings', 'helper', 'cheqroom-core'], function(settings, helper, cr) {
        var run = function() {
            var common = cr.common;

            test('isValidPhone', function() {
                ok(common.isValidPhone("+14155552671"));
                ok(common.isValidPhone("14155552671"));
                ok(common.isValidPhone("+442071838750"));
                ok(common.isValidPhone("+551155256325"));
                ok(common.isValidPhone("470883893")); //no country code
                ok(common.isValidPhone("054-5237745"));
                ok(common.isValidPhone("054-52377454")) //contains non ascii value
            });

            test('isValidEmail', function(){
                  ok(common.isValidEmail("test@test.com"));
                  ok(!common.isValidEmail("test"));
                  ok(common.isValidEmail("example@made.for.digital"));
                  ok(common.isValidEmail("Clayton.O'Brien@ampcontrolgroup.com"));
                  ok(!common.isValidEmail("josé.mourinho@noclub.com"))
            })

            test('isValidUrl', function(){
              ok(common.isValidUrl("https://1drv.ms/x/s!Apc_qRK-hoOumU3wmiUAB7j4vLGX"));
            })
        };

        return {run: run}
    }
);


text:
//
//  CBLC4Document.h
//  CouchbaseLite
//
//  Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <Foundation/Foundation.h>
#import "c4.h"

NS_ASSUME_NONNULL_BEGIN

@interface CBLC4Document : NSObject

@property (readonly, nonatomic) C4Document* rawDoc;

/** Revision flag of the selected revision. */
@property (readonly, nonatomic) C4RevisionFlags revFlags;

/** Sequence of the selected revision. */
@property (readonly, nonatomic) C4SequenceNumber sequence;

/** Revision ID of the selected revision. */
@property (readonly, nonatomic) C4String revID;

/** Body of the selected revision. */
@property (readonly, nonatomic) FLDict body;

+ (instancetype) document: (C4Document*)document;

/** Not available */
- (instancetype) init NS_UNAVAILABLE;

- (instancetype) initWithRawDoc: (C4Document*)rawDoc;

@end

NS_ASSUME_NONNULL_END


text:
package vg.civcraft.mc.civhelp.civguide;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import vg.civcraft.mc.civhelp.CivHelpPlugin;
import vg.civcraft.mc.civhelp.civguide.books.CivGuideBook;
import vg.civcraft.mc.civhelp.civguide.books.CivGuideReader;
import vg.civcraft.mc.civhelp.civguide.listener.CivGuideCommandListener;
import vg.civcraft.mc.civhelp.civguide.listener.CivGuidePlayerListener;

public class CivGuide {
	private static CivGuide instance;
	private CivGuidePlayerListener playerListener;
	private CivGuideCommandListener commandListener;
	private HashMap<String, CivGuideBook> guideBooks;
	private HashMap<UUID, CivGuideReader> playersWithBooks;
	public String bookauthor = ChatColor.DARK_PURPLE+"CivCraft";
	private static CivHelpPlugin help;

	public CivGuide(){
		help = CivHelpPlugin.getInstance();
	}

	public void onCommand(Player sender, String[] args) {
		commandListener.handleCommand(sender, args);
	}

	public void onDisable() {
		for (Player player : help.getServer().getOnlinePlayers())
			player.getInventory().setContents(removeBooks(player.getInventory().getContents()));

		guideBooks.clear();
		playersWithBooks.clear();

	}

	public void onEnable() {
		instance = this;
		playerListener = new CivGuidePlayerListener();
		commandListener = new CivGuideCommandListener();
		playersWithBooks = new HashMap<UUID, CivGuideReader>();
		guideBooks = new HashMap<String, CivGuideBook>();
		loadBooks();
		help.getServer().getPluginManager().registerEvents(playerListener, help);

		for (Player player : help.getServer().getOnlinePlayers())
			player.getInventory().setContents(removeBooks(player.getInventory().getContents()));

	}

	private void loadBooks() {
		help.saveDefaultConfig();
		help.reloadConfig();
		FileConfiguration config = help.getConfig();
		if (!config.contains("booklist")){return;}

		List<String> booklist = config.getStringList("booklist");
		if (booklist == null){return;}

		String defaultbook = config.getString("defaultbook", "");

		String fullname;
		List<String> pages;
		CivGuideBook book;

		for (String bookname : booklist){
			if (!config.contains("books."+bookname) || bookname.isEmpty()){continue;}

			fullname = config.getString("books."+bookname+".fullname", bookname);
			pages = config.getStringList("books."+bookname+".pages");
			book = new CivGuideBook(fullname);
			book.addPages(pages);
			guideBooks.put(bookname.toLowerCase(), book);
			if (bookname.equalsIgnoreCase(defaultbook)){
				guideBooks.put("default", book);
			}
		}
	}

	public static CivGuide getInstance(){
		return instance;
	}

	public HashMap<String, CivGuideBook> getGuideBooks(){
		return guideBooks;
	}

	public boolean isGuideBook(String bookname){
		if (guideBooks.containsKey(bookname)){return true;}
		for (CivGuideBook book: guideBooks.values()){
			if (book.getName().equalsIgnoreCase(bookname))
				return true;
		}
		return false;
	}

	public boolean sendGuideBook(Player player, String bookname){
		if (!isGuideBook(bookname) || player == null){
			return false;
		}

		String booknamefixed = fixbookname(bookname);

		ItemStack inhand = player.getItemInHand();
		if (!(inhand.getType().equals(Material.AIR))){
			if (!(inhand.getType().equals(Material.WRITTEN_BOOK))){
				player.sendMessage(ChatColor.DARK_GREEN+"[CivGuide] "+ChatColor.DARK_RED+"You're hand needs to be empty before you can summon a guidebook.");
				return false;
			}
			BookMeta handbook = (BookMeta)inhand.getItemMeta();
			if (!(handbook.getAuthor().equals(bookauthor))){
				player.sendMessage(ChatColor.DARK_GREEN+"[CivGuide] "+ChatColor.DARK_RED+"You're hand needs to be empty before you can summon a guidebook.");
				return false;
			} else{
				player.setItemInHand(new ItemStack(Material.AIR));
			}
		}

		player.setItemInHand(guideBooks.get(booknamefixed).makeBookItem());
		playersWithBooks.put(player.getUniqueId(), new CivGuideReader());
		return true;
	}

	private String fixbookname(String bookname) {
		if (guideBooks.containsKey(bookname)){return bookname;}
		String name = bookname;
		for (String book: guideBooks.keySet()){
			if (guideBooks.get(book).getName().equalsIgnoreCase(bookname)){
				name = book;
				break;
			}
		}
		return name;
	}

	public boolean hasBook(Player player){
		if (player == null){
			return false;
		} else{
			return hasBook(player.getUniqueId());
		}
	}

	public boolean hasBook(UUID uuid){
		if (uuid == null){return false;}
		if (playersWithBooks.containsKey(uuid)){
			return true;
		}
		return false;
	}

	public boolean isReading(Player player){
		if (player == null){
			return false;
		} else {
			return isReading(player.getUniqueId());
		}
	}

	public boolean isReading(UUID uuid) {
		if (!hasBook(uuid)){
			return false;
		}
		return playersWithBooks.get(uuid).isReading();
	}

	public long getReadTimeSecs(Player player){
		if (player == null){
			return 0;
		} else{
			return getReadTimeSecs(player.getUniqueId());
		}
	}

	public long getReadTimeSecs(UUID uuid){
		long ret = 0;
		if (isReading(uuid)){
			ret = playersWithBooks.get(uuid).getReadTimeSecs();
		}
		return ret;
	}

	public long getOwnTimeSecs(Player player){
		if (player == null){
			return 0;
		} else{
			return getOwnTimeSecs(player.getUniqueId());
		}
	}

	public long getOwnTimeSecs(UUID uuid){
		long ret = 0;
		if (hasBook(uuid)){
			ret = playersWithBooks.get(uuid).getOwnTime();
		}
		return ret;
	}

	public void setReading(Player player, boolean reading){
		if (player == null)
			return;
		setReading(player.getUniqueId(), reading);
	}

	public void setReading(UUID uuid, boolean reading) {
		if (!hasBook(uuid))
			return;
		playersWithBooks.get(uuid).setReading(reading);
	}

	public void removeBook(Player player){
		removeBook(player, -1);
	}

	public void removeBook(Player player, int slot){
		if (player == null){
			return;
		} else if (!hasBook(player))
			return;
		playersWithBooks.remove(player.getUniqueId());
		ItemStack inhand;
		if (slot == -1){
			inhand = player.getItemInHand();
		} else{
			inhand = player.getInventory().getItem(slot);
		}
		if (inhand == null){return;}
		if (!(inhand.getType().equals(Material.WRITTEN_BOOK))){
			return;
		}
		BookMeta bookdat = (BookMeta)inhand.getItemMeta();
		if (bookdat.getAuthor().equals(bookauthor)){
			player.setItemInHand(new ItemStack(Material.AIR));
		}

	}

	public List<ItemStack> removeBooks(List<ItemStack> items){
		for (ItemStack item : items){
			if (item.getType().equals(Material.WRITTEN_BOOK)){
				if (((BookMeta)item.getItemMeta()).getAuthor().equals(bookauthor)){
					item.setType(Material.AIR);
				}
			}
		}
		return items;
	}

	public ItemStack[] removeBooks(ItemStack[] items) {
		for (ItemStack item : items){
			if (item == null){continue;}
			if (item.getType().equals(Material.WRITTEN_BOOK)){
				if (((BookMeta)item.getItemMeta()).getAuthor().equals(bookauthor)){
					item.setType(Material.AIR);
				}
			}
		}
		return items;
	}

}


text:
require 'plotly/castable'

module Plotly
  class Line
    include Castable

    ATTRS = %i(width color).freeze
    attr_accessor(*ATTRS)

    # @option opts [Fixnum] width
    # @option opts [String] color 'rgba(0, 0, 200, .5)'
    def initialize(opts)
      return unless opts.is_a?(Hash)
      opts.each { |k, v| instance_variable_set("@#{k}", v) }
    end
  end
end


text:
.. _conditions:

Conditions
==========

Overview
--------

In complex forms it is often the case that some inputs need to be hidden or
disabled under certain conditions, such as an earlier field having a particular
value, this is what *conditions* in Manner provide.

Conditions in Manner, which are separate from :ref:`validators`, build on bound
predicates and additionally specify resulting *actions*. An action might be
something like "hide fields X, Y and Z" or "enable fields A, B and C" or
possibly even both.

.. note::

   Internally conditions keep track of pending predicate results and a cache of
   results for the previous inputs, which means they need an extra layer of
   indirection if they are to be used with multiple models.

Condition actions
-----------------

*Condition actions* are the way a condition acts on the result of a bound
predicate, multiple condition actions may occur for a single
condition. Available actions are: ``hide``, ``show``, ``disable`` and
``enable``.

.. note::

   Conditions will always emit a resulting action, the result of the bound
   predicate will dictate what the result of an action will be: The ``hide``
   action will suggest hiding the bound fields on success and showing them on
   failure, and vice versa for ``show``; likewise the ``disable`` action will
   suggest disabling the bound fields on success and enabling them on failure,
   and vice versa for ``enable``.

   The result of conflicting actions for a single field is not well defined.

Creating a condition
--------------------

Conditions are only marginally more complex than validators to construct, in
addition to containing a bound predicate they must also specify actions; the
``when`` function assists in this regard by creating a *condition
checker*. Still, this is only a short two-step process:

1. Create a conditions definition that can be reused, read as: When ``one`` is
   equal to 42 then hide ``x``, ``y`` and ``z``, and enable ``a``, ``b`` and
   ``c``:

   .. code-block:: javascript

      import * as P from "manner/predicates";
      import * as C from "manner/conditions";
      let someConditions = C.conditions(
        C.when(P.is('one', P.equalTo(42)),
               // Hide "x", "y" and "z" fields on valid input.
               C.hide('x', 'y', 'z'),
               // Enable "a", "b" and "c" fields on valid input.
               C.enable('a', 'b', 'c')));

2. Instantiate a conditions definition to create an instance, a *condition*,
   with its own state suitable for repeated use with one particular model:

   .. code-block:: javascript

      let formConditions = C.instantiate(someConditions);
      formConditions(my_model);  // => Condition results

The ultimate result of invoking a condition is an ``Immutable.Map`` of field
names to :ref:`condition status <condition status>`, which can then be used to
update the state of a form.

Long-running predicates
-----------------------

A condition takes an optional second argument: a callback function,
passed the result of a condition checker, that is called as soon as the result is
resolved.

Asynchronous predicates may prevent a validator from resolving for an extended
period of time thus delaying any important user interface updates, in this case
the callback function can be used to update the user interface as predicate
results are resolved.

.. _condition status:

Condition status
----------------

The results of a condition are more complex than those of a predicate because
there are three possible states: ``hidden``, ``disabled`` and
``normal``. Conditions have a separate ``Status`` to predicates for two main
reasons:

1. There is an additional state;

2. Every state constructor accepts an optional message, which may be useful when
   describing why something is available or unavailable in a user interface


text:
//
//  ImojiSDKUI
//
//  Created by Nima Khoshini
//  Copyright (C) 2015 Imoji
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <ImojiSDK/IMImojiSession.h>
#import <ImojiSDK/IMCategoryFetchOptions.h>
#import "IMCollectionViewSplashCell.h"

typedef NS_ENUM(NSUInteger, IMCollectionViewContentType) {
    IMCollectionViewContentTypeImojis,
    IMCollectionViewContentTypeImojiCategories,
    IMCollectionViewContentTypeRecentsSplash,
    IMCollectionViewContentTypeCollectionSplash,
    IMCollectionViewContentTypeNoConnectionSplash,
    IMCollectionViewContentTypeEnableFullAccessSplash,
    IMCollectionViewContentTypeNoResultsSplash
};

extern NSUInteger const IMCollectionViewNumberOfItemsToLoad;

@class IMImojiSession, IMImojiCategoryObject, IMImojiObject, IMCollectionLoadingView;

@protocol IMCollectionViewDelegate;

/**
 * A resuable collection view for displaying stickers backed by the ImojiSDK.
 */
@interface IMCollectionView : UICollectionView <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>

/**
* @abstract The current imoji session
*/
@property(nonatomic, strong, readonly, nonnull) IMImojiSession *session;

/**
* @abstract The type of content currently displayed in collection view
*/
@property(nonatomic, readonly) IMCollectionViewContentType contentType;

/**
 * @abstract The number of Imoji stickers to load. Defaults to IMCollectionViewNumberOfItemsToLoad.
 */
@property(nonatomic) NSUInteger numberOfImojisToLoad;

/**
 * @abstract The size in which to display the Imoji's. By default this is set to 100x100 and the collection view
 * will expand the cell to occupy any remaining space so that the cells fill the rows.
 */
@property(nonatomic) CGSize preferredImojiDisplaySize;

/**
 * @abstract The image bundle to use for displaying shared assets such as splash screen images. Defaults to
 * [IMResourceBundleUtil assetsBundle]
*/
@property(nonatomic, strong, nonnull) NSBundle *imagesBundle;

/**
 * @abstract Whether or not tapping on an Imoji sticker should animate. If YES, processCellAnimations is called when
 * the user selects an Imoji.
*/
@property(nonatomic) BOOL animateSelection;

/**
 * @abstract Whether or not infinite scrolling of content is enabled. Defaults to NO.
*/
@property(nonatomic) BOOL infiniteScroll;

/**
 * @abstract Indicates that the current view is loading. Only for the initial view.
 * Subsequent loading views, such as loading the next page of results within a category,
 * are handled by IMCollectionViewStatusCell.
 */
@property(nonatomic, strong, nullable) IMCollectionLoadingView *loadingView;

/**
 * @abstract The default rendering options to use for displaying the stickers.
*/
@property(nonatomic, strong, nonnull) IMImojiObjectRenderingOptions *renderingOptions;

@property(nonatomic, weak, nullable) id <IMCollectionViewDelegate> collectionViewDelegate;

/**
 * @abstract Creates a collection view with the specified Imoji session
 */
- (nonnull instancetype)initWithSession:(nonnull IMImojiSession *)session;

/**
 * @abstract Creates a collection view with the specified Imoji session
 */
+ (nonnull instancetype)imojiCollectionViewWithSession:(nonnull IMImojiSession *)session;

@end

@interface IMCollectionView (ImojiLoading)

/**
 * @abstract Loads Imoji stickers into the collection view using getFeaturedImojisWithNumberOfResults from IMImojiSession
 */
- (void)loadFeaturedImojis;

/**
 * @abstract Loads Imoji categories into the collection view using getImojiCategoriesWithClassification from IMImojiSession
 * DEPRECATED: Use loadImojiCategoriesWithOptions instead
 */
- (void)loadImojiCategories:(IMImojiSessionCategoryClassification)classification DEPRECATED_ATTRIBUTE;

/**
 * @abstract Loads Imoji categories into the collection view using getImojiCategoriesWithOptions from IMImojiSession
 * @param categoryFetchOptions A set of options for category retrieval.
 * @param contextualSearchPhrase When set, instructs the server to return categories relevant to the search phrase.
 */
- (void)loadImojiCategoriesWithOptions:(nullable IMCategoryFetchOptions *)categoryFetchOptions;

/**
 * @abstract Loads Imoji from a given search term into the collection view using searchImojisWithTerm from IMImojiSession
 * The collection view will automatically scroll through multiple pages of stickers if they exist
 */
- (void)loadImojisFromSearch:(nullable NSString *)searchTerm;

/**
 * @abstract Parses a given sentence for popular Imoji stickers
 */
- (void)loadImojisFromSentence:(nonnull NSString *)sentence;

/**
 * @abstract Loads Imoji stickers into the collection view using fetchImojisByIdentifiers from IMImojiSession
 */
- (void)loadImojisFromIdentifiers:(nonnull NSArray *)imojiIdentifiers;

/**
 * @abstract Loads Imoji stickers for an authenticated user into the collection view using
 * getImojisForAuthenticatedUserWithResultSetResponseCallback from IMImojiSession
 */
- (void)loadUserCollectionImojis;

/**
 * @abstract Loads Imoji stickers for an authenticated user into the recents view using
 * getImojisForAuthenticatedUserWithResultSetResponseCallback from IMImojiSession
 */
- (void)loadRecents;

/**
 * @abstract Loads Imoji stickers from a category
 */
- (void)loadImojisFromCategory:(nonnull IMImojiCategoryObject *)category;

/**
 * @abstract Shows specified splash content in the collection view
 */
- (void)displaySplashOfType:(IMCollectionViewSplashCellType)splashType;

@end

@interface IMCollectionView (Override)

- (void)processCellAnimations:(nonnull NSIndexPath *)currentIndexPath;

- (nullable id)contentForIndexPath:(nonnull NSIndexPath *)path;

- (BOOL)isPathShowingLoadingIndicator:(nonnull NSIndexPath *)indexPath;

@end

@protocol IMCollectionViewDelegate <NSObject>

@optional

/**
 * @abstract Notified when the specified content has completed loading
 */
- (void)imojiCollectionView:(nonnull IMCollectionView *)collectionView didFinishLoadingContentType:(IMCollectionViewContentType)contentType;

/**
 * @abstract Notified when the user has tapped on the a given splash cell
 */
- (void)userDidSelectSplash:(IMCollectionViewSplashCellType)splashType fromCollectionView:(nonnull IMCollectionView *)collectionView;

/**
 * @abstract Notified when a user selected an imoji
 */
- (void)userDidSelectImoji:(nonnull IMImojiObject *)imoji fromCollectionView:(nonnull IMCollectionView *)collectionView;

/**
 * @abstract Notified when a user selected a category
 */
- (void)userDidSelectCategory:(nonnull IMImojiCategoryObject *)category fromCollectionView:(nonnull IMCollectionView *)collectionView;

- (void)imojiCollectionViewDidScroll:(nonnull IMCollectionView *)collectionView;

/**
 * @abstract Notified when a user selected an attribution link
 */
- (void)userDidSelectAttributionLink:(nonnull NSURL *)attributionLink fromCollectionView:(nonnull IMCollectionView *)collectionView;

@end