text:
.. _automap_toplevel:

Automap
=======

.. automodule:: sqlalchemy.ext.automap

API Reference
-------------

.. autofunction:: automap_base

.. autoclass:: AutomapBase
	:members:

.. autofunction:: classname_for_table

.. autofunction:: name_for_scalar_relationship

.. autofunction:: name_for_collection_relationship

.. autofunction:: generate_relationship


text:
ActiveRecord::Schema.define(version: 20141013213821) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "projects", force: true do |t|
    t.string   "title",                             null: false
    t.integer  "wordcount_goal",                    null: false
    t.integer  "goal_time_limit",                   null: false
    t.integer  "current_wordcount", default: 0,     null: false
    t.boolean  "active",            default: true,  null: false
    t.boolean  "archived",          default: false
    t.boolean  "completed",         default: false
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "name",       null: false
    t.string   "email",      null: false
    t.string   "password",   null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

redpajama_set_name: RedPajamaGithub


text:
using Binance.Utility;

namespace Binance.Stream
{
    /// <summary>
    /// An <see cref="IJsonStreamPublisher{TStream}"/> with automatic stream control.
    /// </summary>
    /// <typeparam name="TStream"></typeparam>
    public interface IAutoJsonStreamPublisher<out TStream> : IJsonStreamPublisher<TStream>
        where TStream : IJsonStream
    {
        /// <summary>
        /// Get the JSON stream controller.
        /// </summary>
        IJsonStreamController<TStream> Controller { get; }
    }
}


text:
@interface PodsDummy_PPiFlatSegmentedControl : NSObject
@end
@implementation PodsDummy_PPiFlatSegmentedControl
@end


text:
package org.jabref.logic.util.io;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jabref.BibtexTestData;
import org.jabref.logic.bibtex.FieldContentParserPreferences;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class FileBasedTestCase {

    private BibEntry entry;
    private Path rootDir;

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Mock
    private ImportFormatPreferences prefs;

    @Before
    public void setUp() throws IOException {
        when(prefs.getFieldContentParserPreferences()).thenReturn(new FieldContentParserPreferences());

        BibDatabase database = BibtexTestData.getBibtexDatabase(prefs);
        entry = database.getEntries().iterator().next();

        rootDir = temporaryFolder.getRoot().toPath();

        Path subDir = Files.createDirectory(rootDir.resolve("Organization Science"));
        Path pdfSubDir = Files.createDirectory(rootDir.resolve("pdfs"));

        Files.createFile(subDir.resolve("HipKro03 - Hello.pdf"));
        Files.createFile(rootDir.resolve("HipKro03 - Hello.pdf"));

        Path pdfSubSubDir = Files.createDirectory(pdfSubDir.resolve("sub"));
        Files.createFile(pdfSubSubDir.resolve("HipKro03-sub.pdf"));

        Files.createDirectory(rootDir.resolve("2002"));
        Path dir2003 = Files.createDirectory(rootDir.resolve("2003"));
        Files.createFile(dir2003.resolve("Paper by HipKro03.pdf"));

        Path dirTest = Files.createDirectory(rootDir.resolve("test"));
        Files.createFile(dirTest.resolve(".TEST"));
        Files.createFile(dirTest.resolve("TEST["));
        Files.createFile(dirTest.resolve("TE.ST"));
        Files.createFile(dirTest.resolve("foo.dat"));

        Path graphicsDir = Files.createDirectory(rootDir.resolve("graphicsDir"));
        Path graphicsSubDir = Files.createDirectories(graphicsDir.resolve("subDir"));

        Files.createFile(graphicsSubDir.resolve("HipKro03test.jpg"));
        Files.createFile(graphicsSubDir.resolve("HipKro03test.png"));

    }

    @Test
    public void testFindAssociatedFiles() {

        List<BibEntry> entries = Collections.singletonList(entry);
        List<String> extensions = Arrays.asList("jpg", "pdf");
        List<File> dirs = Arrays.asList(rootDir.resolve("graphicsDir").toFile(), rootDir.resolve("pdfs").toFile());

        Map<BibEntry, List<File>> results = FileUtil.findAssociatedFiles(entries, extensions, dirs, false);

        assertEquals(2, results.get(entry).size());
        assertTrue(results.get(entry)
                .contains(rootDir.resolve(Paths.get("graphicsDir", "subDir", "HipKro03test.jpg")).toFile()));
        assertFalse(results.get(entry)
                .contains(rootDir.resolve(Paths.get("graphicsDir", "subDir", "HipKro03test.png")).toFile()));
        assertTrue(results.get(entry).contains(rootDir.resolve(Paths.get("pdfs", "sub", "HipKro03-sub.pdf")).toFile()));
    }

    @Test
    public void testFindFilesException() {
        List<String> extensions = Arrays.asList("jpg", "pdf");
        List<File> dirs = Arrays.asList(rootDir.resolve("asdfasdf/asdfasdf").toFile());
        Set<Path> results = FileFinder.findFiles(extensions, dirs);

        assertEquals(Collections.emptySet(), results);
    }

    @Test(expected = NullPointerException.class)
    public void testFindFilesNullPointerException() {

        FileFinder.findFiles(null, null);
    }

}


text:
package de.tor.tribes.util.sos;

import de.tor.tribes.control.GenericManager;
import de.tor.tribes.control.ManageableType;
import de.tor.tribes.types.Defense;
import de.tor.tribes.types.DefenseInformation;
import de.tor.tribes.types.SOSRequest;
import de.tor.tribes.types.ext.Tribe;
import de.tor.tribes.types.ext.Village;
import de.tor.tribes.util.xml.JDomUtils;
import java.util.List;
import org.apache.commons.collections4.IterableUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;

/**
 *
 * @author Torridity
 */
public class SOSManager extends GenericManager<SOSRequest> {

  private static Logger logger = LogManager.getLogger("SOSManager");
  private static SOSManager SINGLETON = null;

  public static synchronized SOSManager getSingleton() {
    if (SINGLETON == null) {
      SINGLETON = new SOSManager();
    }
    return SINGLETON;
  }

  SOSManager() {
    super(false);
  }

  @Override
    public int importData(Element pElm, String pExtension) {
    if (pElm == null) {
        logger.error("Element argument is 'null'");
        return -1;
    }
    int result = 0;
    invalidate();
    logger.info("Loading SOS information");

    try {
      for (Element e : (List<Element>) JDomUtils.getNodes(pElm, "sosRequests/sosRequest")) {
        SOSRequest s = new SOSRequest();
        s.loadFromXml(e);
        addManagedElement(s);
        result++;
      }
      logger.debug("SOS requests loaded successfully");
    } catch (Exception e) {
      result = result * (-1) - 1;
      logger.error("Failed to load SOS requests", e);
    }
    revalidate(true);
    return result;
  }

  @Override
  public Element getExportData(final List<String> pGroupsToExport) {
    Element sosRequests = new Element("sosRequests");

    logger.debug("Generating SOS information");
    try {
      for (ManageableType t : getAllElements()) {
        Element e = t.toXml("sosRequest");
        if(e != null) {
            sosRequests.addContent(e);
        }
      }
      logger.debug("SOS information generated");
    } catch (Exception e) {
      logger.warn("Failed to generate SOS XML", e);
    }

    return sosRequests;
  }

  public SOSRequest getRequest(final Tribe pTribe) {
    if (pTribe == null) {
      return null;
    }

    return IterableUtils.find(getAllElements(),
        (o) -> o.getDefender().equals(pTribe)
    );
  }

  public void addRequest(SOSRequest pRequest) {
    SOSRequest r = getRequest(pRequest.getDefender());
    if (r != null) {
      r.merge(pRequest);
      fireDataChangedEvents();
    } else {
      addManagedElement(pRequest);
    }
  }

  public int getOverallTargetCount() {
    int cnt = 0;
    for (ManageableType t : getAllElements()) {
      SOSRequest r = (SOSRequest) t;
      cnt+= r.getTargets().size();
    }
    return cnt;
  }

  public boolean hasTransferredSupports() {
    for (ManageableType t : getAllElements()) {
      SOSRequest r = (SOSRequest) t;
      for(Village target: r.getTargets()) {
        DefenseInformation info = r.getDefenseInformation(target);
        for (Defense d : info.getSupports()) {
          if (d.isTransferredToBrowser()) {
            return true;
          }
        }
      }
    }
    return false;
  }
}


text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Comparator;
import java.util.function.Function;
import java.util.stream.Collector;

/** Collectors utilities for {@code common.collect} internals. */
@GwtCompatible
final class CollectCollectors {
  static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap(
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    checkNotNull(keyFunction);
    checkNotNull(valueFunction);
    return Collector.of(
        ImmutableBiMap.Builder<K, V>::new,
        (builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
        ImmutableBiMap.Builder::combine,
        ImmutableBiMap.Builder::build,
        new Collector.Characteristics[0]);
  }

  private static final Collector<Object, ?, ImmutableList<Object>> TO_IMMUTABLE_LIST =
      Collector.of(
          ImmutableList::<Object>builder,
          ImmutableList.Builder::add,
          ImmutableList.Builder::combine,
          ImmutableList.Builder::build);

  static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
    return (Collector) TO_IMMUTABLE_LIST;
  }

  static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    checkNotNull(keyFunction);
    checkNotNull(valueFunction);
    return Collector.of(
        ImmutableMap.Builder<K, V>::new,
        (builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
        ImmutableMap.Builder::combine,
        ImmutableMap.Builder::build);
  }

  private static final Collector<Object, ?, ImmutableSet<Object>> TO_IMMUTABLE_SET =
      Collector.of(
          ImmutableSet::<Object>builder,
          ImmutableSet.Builder::add,
          ImmutableSet.Builder::combine,
          ImmutableSet.Builder::build);

  static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
    return (Collector) TO_IMMUTABLE_SET;
  }

  static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
      Comparator<? super K> comparator,
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    checkNotNull(comparator);
    checkNotNull(keyFunction);
    checkNotNull(valueFunction);
    /*
     * We will always fail if there are duplicate keys, and the keys are always sorted by
     * the Comparator, so the entries can come in in arbitrary order -- so we report UNORDERED.
     */
    return Collector.of(
        () -> new ImmutableSortedMap.Builder<K, V>(comparator),
        (builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
        ImmutableSortedMap.Builder::combine,
        ImmutableSortedMap.Builder::build,
        Collector.Characteristics.UNORDERED);
  }

  static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
      Comparator<? super E> comparator) {
    checkNotNull(comparator);
    return Collector.of(
        () -> new ImmutableSortedSet.Builder<E>(comparator),
        ImmutableSortedSet.Builder::add,
        ImmutableSortedSet.Builder::combine,
        ImmutableSortedSet.Builder::build);
  }

  @GwtIncompatible
  private static final Collector<Range<Comparable>, ?, ImmutableRangeSet<Comparable>>
      TO_IMMUTABLE_RANGE_SET =
          Collector.of(
              ImmutableRangeSet::<Comparable>builder,
              ImmutableRangeSet.Builder::add,
              ImmutableRangeSet.Builder::combine,
              ImmutableRangeSet.Builder::build);

  @GwtIncompatible
  static <E extends Comparable<? super E>>
      Collector<Range<E>, ?, ImmutableRangeSet<E>> toImmutableRangeSet() {
    return (Collector) TO_IMMUTABLE_RANGE_SET;
  }

  @GwtIncompatible
  static <T, K extends Comparable<? super K>, V>
      Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap(
          Function<? super T, Range<K>> keyFunction,
          Function<? super T, ? extends V> valueFunction) {
    checkNotNull(keyFunction);
    checkNotNull(valueFunction);
    return Collector.of(
        ImmutableRangeMap::<K, V>builder,
        (builder, input) -> builder.put(keyFunction.apply(input), valueFunction.apply(input)),
        ImmutableRangeMap.Builder::combine,
        ImmutableRangeMap.Builder::build);
  }
}


text:
'''
Basic example. This script queries the manager and prints out the current users,
then creates a user named user1 (if it does not already exist), then deletes
it again. Note how these settings are done by writing to the "Config" space,
then doing a "reload" to activate.
'''

#============================ adjust path =====================================

import sys
import os
if __name__ == "__main__":
    here = sys.path[0]
    sys.path.insert(0, os.path.join(here, '..', 'libs'))
    sys.path.insert(0, os.path.join(here, '..', 'external_libs'))

#============================ imports =========================================

import urllib3
import traceback
import certifi

# generic SmartMeshSDK imports
from SmartMeshSDK                      import sdk_version
# VManager-specific imports
from VManagerSDK.vmanager              import Configuration
from VManagerSDK.vmgrapi               import VManagerApi
from VManagerSDK.vmanager.rest         import ApiException
from VManagerSDK.vmanager              import UserWriteConfig

#============================ defines =========================================

DFLT_VMGR_HOST          = "127.0.0.1"

urllib3.disable_warnings() # disable warnings that show up about self-signed certificates

#============================ main ============================================

try:
    # print banner
    print '\nVMgr_UserCreate-Delete Example (c) Dust Networks'
    print 'SmartMesh SDK {0}\n'.format('.'.join([str(i) for i in sdk_version.VERSION]))

    mgrhost = raw_input('Enter the IP address of the manager (e.g. {0} ): '.format(DFLT_VMGR_HOST))
    if mgrhost == "":
        mgrhost = DFLT_VMGR_HOST

    # log in as user "dust"
    config = Configuration()
    config.username     = 'dust'
    config.password     = 'dust'
    config.verify_ssl   = False

    if os.path.isfile(certifi.where()):
        config.ssl_ca_cert  = certifi.where()
    else:
        config.ssl_ca_cert = os.path.join(os.path.dirname(sys.executable), "cacert.pem")

    # initialize the VManager Python library
    voyager = VManagerApi(host=mgrhost)

    # ==== Create a new user in configuration memory if doesn't already exist
    userName       = "user1"
    userExists     = False
    # read the list of users first (in Config area) to see if it already exists
    print "\n The current users in Config are ..."
    myUsers = voyager.usersApi.get_config_users()
    for x in myUsers.users:
        print '    {0}'.format(x.user_id)
        if x.user_id == userName:
            userExists = True

    # create the new user if not already there
    if not userExists:
        print '\n Creating a new user called {0}\n'.format(userName)
        userConfigbody = UserWriteConfig()
        userConfigbody.description     = "NewUser1"
        userConfigbody.password        = "secretpw"
        userConfigbody.privilege       = "user"
        voyager.usersApi.add_config_user(userName, userConfigbody)

    # execute a reload to activate any new changes made in Config area
    voyager.configApi.reload_config()

    # read the list of users in "Active" area
    print "\n The current Active users are ..."
    myActiveUsers = voyager.usersApi.get_users()
    for x in myActiveUsers.users:
        print ('    {0}'.format(x.user_id))

    # Delete the user from the system (Config area then reload)
    print "\n Deleting the user we just created"
    voyager.usersApi.delete_config_user(userName)
    voyager.configApi.reload_config()

    print "\n The current Active users are now ..."
    myActiveUsers = voyager.usersApi.get_users()
    for x in myActiveUsers.users:
        print ('    {0}'.format(x.user_id))

    print 'Script ended normally'

except:
    traceback.print_exc()
    print ('\n Script ended with an error.')
    sys.exit()


text:
package it.ozimov.springboot.mail.utils;

import org.assertj.core.api.JUnitSoftAssertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.internet.MimeMessage;

import static org.mockito.Mockito.verify;

@RunWith(SpringRunner.class)
public class MimeMessageHelperExtTest {

    private static final String HEADER_DEPOSITION_NOTIFICATION_TO = "Disposition-Notification-To";

    private static final String HEADER_RETURN_RECEIPT = "Return-Receipt-To";

    @Rule
    public final JUnitSoftAssertions assertions = new JUnitSoftAssertions();

    @Mock
    public MimeMessage mimeMessage;

    public static final String ENCODING = "UTF-16";

    @Test
    public void shouldConstructorWithMimeMessage() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage);

        //Assert
        assertions.assertThat(mimeMessageHelperExt.getMimeMessage()).isEqualTo(mimeMessage);
    }

    @Test
    public void shouldConstructorWithMimeMessageAndEncoding() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage, ENCODING);

        //Assert
        assertions.assertThat(mimeMessageHelperExt.getMimeMessage()).isEqualTo(mimeMessage);
        assertions.assertThat(mimeMessageHelperExt.getEncoding()).isEqualTo(ENCODING);
    }

    @Test
    public void shouldConstructorWithMimeMessageAndMultipart() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage, false);
        MimeMessageHelperExt mimeMessageHelperExtMultipart = new MimeMessageHelperExt(mimeMessage, true);

        //Assert
        assertions.assertThat(mimeMessageHelperExt.getMimeMessage()).isEqualTo(mimeMessage);

        assertions.assertThat(mimeMessageHelperExt.isMultipart()).isFalse();
        assertions.assertThat(mimeMessageHelperExtMultipart.isMultipart()).isTrue();
    }

    @Test
    public void shouldConstructorWithMimeMessageMultipartAndEncding() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage, false, ENCODING);
        MimeMessageHelperExt mimeMessageHelperExtMultipart = new MimeMessageHelperExt(mimeMessage, true, ENCODING);

        //Assert
        assertions.assertThat(mimeMessageHelperExt.getMimeMessage()).isEqualTo(mimeMessage);
        assertions.assertThat(mimeMessageHelperExt.getEncoding()).isEqualTo(ENCODING);

        assertions.assertThat(mimeMessageHelperExt.isMultipart()).isFalse();
        assertions.assertThat(mimeMessageHelperExtMultipart.isMultipart()).isTrue();
    }

    @Test
    public void shouldConstructorWithMimeMessageMultipartMode() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExtMixed = new MimeMessageHelperExt(mimeMessage, 1);
        MimeMessageHelperExt mimeMessageHelperExtRelated = new MimeMessageHelperExt(mimeMessage, 2);

        //Assert
        assertions.assertThat(mimeMessageHelperExtMixed.getMimeMessage()).isEqualTo(mimeMessage);
        assertions.assertThat(mimeMessageHelperExtMixed.getRootMimeMultipart().getContentType()).containsIgnoringCase("multipart/mixed");

        assertions.assertThat(mimeMessageHelperExtRelated.getRootMimeMultipart().getContentType()).containsIgnoringCase("multipart/related");
    }

    @Test
    public void shouldConstructorWithMimeMessageMultipartModeAndEncding() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExtMixed = new MimeMessageHelperExt(mimeMessage, 1, ENCODING);
        MimeMessageHelperExt mimeMessageHelperExtRelated = new MimeMessageHelperExt(mimeMessage, 2, ENCODING);

        //Assert
        assertions.assertThat(mimeMessageHelperExtMixed.getMimeMessage()).isEqualTo(mimeMessage);
        assertions.assertThat(mimeMessageHelperExtMixed.getRootMimeMultipart().getContentType()).containsIgnoringCase("multipart/mixed");
        assertions.assertThat(mimeMessageHelperExtMixed.getEncoding()).isEqualTo(ENCODING);

        assertions.assertThat(mimeMessageHelperExtRelated.getRootMimeMultipart().getContentType()).containsIgnoringCase("multipart/related");
    }

    @Test
    public void shouldConstructorsWork() throws Exception {
        //Act
        MimeMessageHelperExt mimeMessageHelperExt5 = new MimeMessageHelperExt(mimeMessage, 1);
        MimeMessageHelperExt mimeMessageHelperExt6 = new MimeMessageHelperExt(mimeMessage, 1, "UTF-8");

        //Assert

//        assertions.assertThat(mimeMessageHelperExt1).is
    }

    @Test
    public void shouldSetHeaderReturnReceipt() throws Exception {
        //Arrange
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage);
        String expectedReturnReceipt = "marco-tullio@roma.aeterna";

        //Act
        mimeMessageHelperExt.setHeaderReturnReceipt(expectedReturnReceipt);

        //Assert
        verify(mimeMessage).setHeader(HEADER_RETURN_RECEIPT, expectedReturnReceipt);
    }

    @Test
    public void shouldSetHeaderDepositionNotificationTo() throws Exception {
        //Arrange
        MimeMessageHelperExt mimeMessageHelperExt = new MimeMessageHelperExt(mimeMessage);
        String expectedDepositionNotificationTo = "marco-tullio@roma.aeterna";

        //Act
        mimeMessageHelperExt.setHeaderDepositionNotificationTo(expectedDepositionNotificationTo);

        //Assert
        verify(mimeMessage).setHeader(HEADER_DEPOSITION_NOTIFICATION_TO, expectedDepositionNotificationTo);
    }

}


text:
@interface NSCharacterSet (NSSet)

//Note: has to be a class method because NSCharacter is a class cluster
+ (NSSet*)setFromCharacterSet:(NSCharacterSet*)characterSet;

@end


text:
<?php

namespace AframeVR\Core\Helpers;

use \AframeVR\Interfaces\EntityInterface;

/**
 * Many of the primitives are entities that compose a geometric mesh, meaning they
 * primarily prescribe the geometry and material components.
 * Most of the mesh
 * primitives share common attributes, especially for mapping to the material component.
 * These common attributes won't be described in individual
 * documentation pages for each primitive so they will be listed here
 */
trait MeshAttributes
{

    /**
     * Load component for this entity or set it's attr
     *
     * @param string $component_name
     * @param null|string $attr_data
     * @throws \AframeVR\Core\Exceptions\BadComponentCallException
     * @return object|null
     */
    abstract public function attr(string $component_name, string $attr_data = null);

    /**
     * material.color
     *
     * @param string $color
     * @return EntityInterface
     */
    public function color(string $color): EntityInterface
    {
        $this->attr('Material')
            ->shader()
            ->color($color);
        return $this;
    }

    /**
     * material.metalness
     *
     * @param int|float $metalness
     * @return EntityInterface
     */
    public function metalness(float $metalness): EntityInterface
    {
        $this->attr('Material')
            ->shader()
            ->metalness($metalness);
        return $this;
    }

    /**
     * material.opacity
     *
     * @param float $opacity
     * @return EntityInterface
     */
    public function opacity(float $opacity): EntityInterface
    {
        $this->attr('Material')->opacity($opacity);
        return $this;
    }

    /**
     * material.repeat
     *
     * @param float $x
     * @param float $y
     *
     * @return EntityInterface
     */
    public function repeat(float $x, float $y): EntityInterface
    {
        $this->attr('Material')->repeat($x, $y);
        return $this;
    }

    /**
     * material.roughness
     *
     * @param float $roughness
     * @return EntityInterface
     */
    public function roughness(float $roughness): EntityInterface
    {
        $this->attr('Material')
            ->shader()
            ->roughness($roughness);
        return $this;
    }

    /**
     * material.shader
     *
     * @param string $shader
     * @return EntityInterface
     */
    public function shader($shader): EntityInterface
    {
        $this->attr('Material')->shader($shader);
        return $this;
    }

    /**
     * material.src
     *
     * @param null|string $src
     * @return EntityInterface
     */
    public function src(string $src = null): EntityInterface
    {
        $this->attr('Material')
            ->shader()
            ->src($src);
        return $this;
    }

    /**
     * material.transparent
     *
     * @param bool $transparent
     * @return EntityInterface
     */
    public function transparent(bool $transparent = false): EntityInterface
    {
        $this->attr('Material')->transparent($transparent);
        return $this;
    }
}


text:
"""The zip file system implementation."""

import zipfile

# This is necessary to prevent a circular import.
import dfvfs.vfs.zip_file_entry

from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import zip_path_spec
from dfvfs.resolver import resolver
from dfvfs.vfs import file_system

class ZipFileSystem(file_system.FileSystem):
  """Class that implements a file system object using zipfile."""

  LOCATION_ROOT = u'/'
  TYPE_INDICATOR = definitions.TYPE_INDICATOR_ZIP

  def __init__(self, resolver_context):
    """Initializes the file system object.

    Args:
      resolver_context: the resolver context (instance of resolver.Context).
    """
    super(ZipFileSystem, self).__init__(resolver_context)
    self._file_object = None
    self._zip_file = None

  def _Close(self):
    """Closes the file system object.

    Raises:
      IOError: if the close failed.
    """
    self._zip_file.close()
    self._zip_file = None

    self._file_object.close()
    self._file_object = None

  def _Open(self, path_spec=None, mode='rb'):
    """Opens the file system object defined by path specification.

    Args:
      path_spec: optional path specification (instance of path.PathSpec).
                 The default is None.
      mode: optional file access mode. The default is 'rb' read-only binary.

    Raises:
      AccessError: if the access to open the file was denied.
      IOError: if the file system object could not be opened.
      PathSpecError: if the path specification is incorrect.
      ValueError: if the path specification is invalid.
    """
    if not path_spec.HasParent():
      raise errors.PathSpecError(
          u'Unsupported path specification without parent.')

    file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)

    zip_file = zipfile.ZipFile(file_object, 'r')

    self._file_object = file_object
    self._zip_file = zip_file

  def FileEntryExistsByPathSpec(self, path_spec):
    """Determines if a file entry for a path specification exists.

    Args:
      path_spec: a path specification (instance of path.PathSpec).

    Returns:
      Boolean indicating if the file entry exists.
    """
    zip_info = None
    location = getattr(path_spec, u'location', None)

    if (location is None or
        not location.startswith(self.LOCATION_ROOT)):
      return

    if len(location) == 1:
      return True

    try:
      zip_info = self._zip_file.getinfo(location[1:])
    except KeyError:
      pass

    return zip_info is not None

  def GetFileEntryByPathSpec(self, path_spec):
    """Retrieves a file entry for a path specification.

    Args:
      path_spec: a path specification (instance of path.PathSpec).

    Returns:
      A file entry (instance of vfs.ZipFileEntry) or None.
    """
    zip_info = None
    location = getattr(path_spec, u'location', None)

    if (location is None or
        not location.startswith(self.LOCATION_ROOT)):
      return

    if len(location) == 1:
      return dfvfs.vfs.zip_file_entry.ZipFileEntry(
          self._resolver_context, self, path_spec, is_root=True,
          is_virtual=True)

    try:
      zip_info = self._zip_file.getinfo(location[1:])
    except KeyError:
      pass

    if zip_info is None:
      return
    return dfvfs.vfs.zip_file_entry.ZipFileEntry(
        self._resolver_context, self, path_spec, zip_info=zip_info)

  def GetRootFileEntry(self):
    """Retrieves the root file entry.

    Returns:
      A file entry (instance of vfs.FileEntry).
    """
    path_spec = zip_path_spec.ZipPathSpec(
        location=self.LOCATION_ROOT, parent=self._path_spec.parent)
    return self.GetFileEntryByPathSpec(path_spec)

  def GetZipFile(self):
    """Retrieves the zip file object.

    Returns:
      The zip file object (instance of zipfile.ZipFile).
    """
    return self._zip_file


text:
Flushes all cached content to disk and restricts permitted operations to read commands.  With the exception of reads, none of the commands made on a frozen database execute.  It remains in this state until you run the [`RELEASE`](Console-Command-Release-Db.md) command.

Executing this command requires server administration rights.  You can only execute it on remote databases.  If you would like to freeze or release a local database, use the `ODatabase.freeze()` and `ODatabase.release()` methods directly through the OrientDB API.

>You may find this command useful in the event that you would like to perform backups on a live database.  To do so, freeze the database, perform a file system snapshot, then release the database.  You can now copy the snapshot anywhere you want.

>This works best when the backup doesn't take very long to run.

**Syntax**

```sql
FREEZE DATABASE
```

**Example**

- Freezes the current database:

  orientdb> FREEZE DATABASE

>To unfreeze a database, use the [`RELEASE DATABASE`](Console-Command-Release-Db.md) command.

>For more information on other commands, please refer to [Console Commands](Console-Commands.md) and [SQL Commands](../sql/SQL-Commands.md).


text:
<?php

class MY_Controller extends MX_Controller{

    function __construct(){
        parent::__construct();
        $this->load->module('Themes');
        $this->load->module('Map_housing');
        //$this->load->module('Data_member');

    }

}


text:
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.

namespace UnitsNet
{
    /// <summary>
    /// Specifies if the comparison between numbers is absolute or relative.
    /// </summary>
    public enum ComparisonType
    {
        /// <summary>
        /// Error margin in relative size to a reference value.
        /// </summary>
        Relative,

        /// <summary>
        /// Error margin as absolute size.
        /// </summary>
        Absolute
    }
}


text:
'use strict';
const test = require('tap').test;
const Runner = require('../lib/runner');

const slice = Array.prototype.slice;
const noop = () => {};

test('nested tests and hooks aren\'t allowed', t => {
	t.plan(1);

	const runner = new Runner();

	runner.chain.test(a => {
		t.throws(() => {
			runner.chain.test(noop);
		}, {message: 'All tests and hooks must be declared synchronously in your test file, and cannot be nested within other tests or hooks.'});
		a.pass();
	});

	runner.run({}).then(() => {
		t.end();
	});
});

test('tests must be declared synchronously', t => {
	t.plan(1);

	const runner = new Runner();

	runner.chain.test(a => {
		a.pass();
		return Promise.resolve();
	});

	runner.run({});

	t.throws(() => {
		runner.chain.test(noop);
	}, {message: 'All tests and hooks must be declared synchronously in your test file, and cannot be nested within other tests or hooks.'});

	t.end();
});

test('runner emits a "test" event', t => {
	const runner = new Runner();

	runner.chain.test('foo', a => {
		a.pass();
	});

	runner.on('test', props => {
		t.ifError(props.error);
		t.is(props.title, 'foo');
		t.not(props.duration, undefined);
		t.end();
	});

	runner.run({});
});

test('run serial tests before concurrent ones', t => {
	const runner = new Runner();
	const arr = [];

	runner.chain.test(a => {
		arr.push('c');
		a.end();
	});

	runner.chain.serial(a => {
		arr.push('a');
		a.end();
	});

	runner.chain.serial(a => {
		arr.push('b');
		a.end();
	});

	runner.run({}).then(() => {
		t.strictDeepEqual(arr, ['a', 'b', 'c']);
		t.end();
	});
});

test('anything can be skipped', t => {
	const runner = new Runner();
	const arr = [];

	function pusher(title) {
		return a => {
			arr.push(title);
			a.pass();
		};
	}

	runner.chain.after(pusher('after'));
	runner.chain.after.skip(pusher('after.skip'));

	runner.chain.afterEach(pusher('afterEach'));
	runner.chain.afterEach.skip(pusher('afterEach.skip'));

	runner.chain.before(pusher('before'));
	runner.chain.before.skip(pusher('before.skip'));

	runner.chain.beforeEach(pusher('beforeEach'));
	runner.chain.beforeEach.skip(pusher('beforeEach.skip'));

	runner.chain.test(pusher('concurrent'));
	runner.chain.test.skip(pusher('concurrent.skip'));

	runner.chain.serial(pusher('serial'));
	runner.chain.serial.skip(pusher('serial.skip'));

	runner.run({}).then(() => {
		// Note that afterEach and beforeEach run twice because there are two actual tests - "serial" and "concurrent"
		t.strictDeepEqual(arr, [
			'before',
			'beforeEach',
			'serial',
			'afterEach',
			'beforeEach',
			'concurrent',
			'afterEach',
			'after'
		]);
		t.end();
	});
});

test('include skipped tests in results', t => {
	const runner = new Runner();

	runner.chain.before('before', noop);
	runner.chain.before.skip('before.skip', noop);

	runner.chain.beforeEach('beforeEach', noop);
	runner.chain.beforeEach.skip('beforeEach.skip', noop);

	runner.chain.test.serial('test', a => a.pass());
	runner.chain.test.serial.skip('test.skip', noop);

	runner.chain.after('after', noop);
	runner.chain.after.skip('after.skip', noop);

	runner.chain.afterEach('afterEach', noop);
	runner.chain.afterEach.skip('afterEach.skip', noop);

	const titles = [];

	runner.on('test', test => {
		titles.push(test.title);
	});

	runner.run({}).then(() => {
		t.strictDeepEqual(titles, [
			'before',
			'before.skip',
			'beforeEach for test',
			'beforeEach.skip for test',
			'test',
			'afterEach for test',
			'afterEach.skip for test',
			'test.skip',
			'after',
			'after.skip'
		]);

		t.end();
	});
});

test('test types and titles', t => {
	t.plan(10);

	const fn = a => {
		a.pass();
	};

	function named(a) {
		a.pass();
	}

	const runner = new Runner();
	runner.chain.before(named);
	runner.chain.beforeEach(fn);
	runner.chain.after(fn);
	runner.chain.afterEach(named);
	runner.chain.test('test', fn);

	// See https://github.com/avajs/ava/issues/1027
	const supportsFunctionNames = noop.name === 'noop';

	const tests = [
		{
			type: 'before',
			title: 'named'
		},
		{
			type: 'beforeEach',
			title: supportsFunctionNames ? 'fn for test' : 'beforeEach for test'
		},
		{
			type: 'test',
			title: 'test'
		},
		{
			type: 'afterEach',
			title: 'named for test'
		},
		{
			type: 'after',
			title: supportsFunctionNames ? 'fn' : 'after'
		}
	];

	runner.on('test', props => {
		const test = tests.shift();
		t.is(props.title, test.title);
		t.is(props.type, test.type);
	});

	runner.run({}).then(t.end);
});

test('skip test', t => {
	t.plan(5);

	const runner = new Runner();
	const arr = [];

	runner.chain.test(a => {
		arr.push('a');
		a.pass();
	});

	runner.chain.skip(() => {
		arr.push('b');
	});

	t.throws(() => {
		runner.chain.skip('should be a todo');
	}, new TypeError('Expected an implementation. Use `test.todo()` for tests without an implementation.'));

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.testCount, 2);
		t.is(stats.passCount, 1);
		t.is(stats.skipCount, 1);
		t.strictDeepEqual(arr, ['a']);
		t.end();
	});
});

test('test throws when given no function', t => {
	t.plan(1);

	const runner = new Runner();

	t.throws(() => {
		runner.chain.test();
	}, new TypeError('Expected an implementation. Use `test.todo()` for tests without an implementation.'));
});

test('todo test', t => {
	t.plan(6);

	const runner = new Runner();
	const arr = [];

	runner.chain.test(a => {
		arr.push('a');
		a.pass();
	});

	runner.chain.todo('todo');

	t.throws(() => {
		runner.chain.todo('todo', () => {});
	}, new TypeError('`todo` tests are not allowed to have an implementation. Use `test.skip()` for tests with an implementation.'));

	t.throws(() => {
		runner.chain.todo();
	}, new TypeError('`todo` tests require a title'));

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.testCount, 2);
		t.is(stats.passCount, 1);
		t.is(stats.todoCount, 1);
		t.strictDeepEqual(arr, ['a']);
		t.end();
	});
});

test('only test', t => {
	t.plan(3);

	const runner = new Runner();
	const arr = [];

	runner.chain.test(a => {
		arr.push('a');
		a.pass();
	});

	runner.chain.only(a => {
		arr.push('b');
		a.pass();
	});

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.testCount, 1);
		t.is(stats.passCount, 1);
		t.strictDeepEqual(arr, ['b']);
		t.end();
	});
});

test('throws if you try to set a hook as exclusive', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.beforeEach.only('', noop);
	}, new TypeError('`only` is only for tests and cannot be used with hooks'));

	t.end();
});

test('throws if you try to set a before hook as always', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.before.always('', noop);
	}, new TypeError('`always` can only be used with `after` and `afterEach`'));

	t.end();
});

test('throws if you try to set a test as always', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.test.always('', noop);
	}, new TypeError('`always` can only be used with `after` and `afterEach`'));

	t.end();
});

test('throws if you give a function to todo', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.test.todo('todo with function', noop);
	}, new TypeError('`todo` tests are not allowed to have an implementation. Use ' +
	'`test.skip()` for tests with an implementation.'));

	t.end();
});

test('throws if todo has no title', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.test.todo();
	}, new TypeError('`todo` tests require a title'));

	t.end();
});

test('throws if todo has failing, skip, or only', t => {
	const runner = new Runner();

	const errorMessage = '`todo` tests are just for documentation and cannot be' +
		' used with `skip`, `only`, or `failing`';

	t.throws(() => {
		runner.chain.test.failing.todo('test');
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.test.skip.todo('test');
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.test.only.todo('test');
	}, new TypeError(errorMessage));

	t.end();
});

test('throws if todo isn\'t a test', t => {
	const runner = new Runner();

	const errorMessage = '`todo` is only for documentation of future tests and' +
		' cannot be used with hooks';

	t.throws(() => {
		runner.chain.before.todo('test');
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.beforeEach.todo('test');
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.after.todo('test');
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.afterEach.todo('test');
	}, new TypeError(errorMessage));

	t.end();
});

test('throws if test has skip and only', t => {
	const runner = new Runner();

	t.throws(() => {
		runner.chain.test.only.skip('test', noop);
	}, new TypeError('`only` tests cannot be skipped'));

	t.end();
});

test('throws if failing is used on non-tests', t => {
	const runner = new Runner();

	const errorMessage = '`failing` is only for tests and cannot be used with hooks';

	t.throws(() => {
		runner.chain.beforeEach.failing('', noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.before.failing('', noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.afterEach.failing('', noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.after.failing('', noop);
	}, new TypeError(errorMessage));

	t.end();
});

test('throws if only is used on non-tests', t => {
	const runner = new Runner();

	const errorMessage = '`only` is only for tests and cannot be used with hooks';

	t.throws(() => {
		runner.chain.beforeEach.only(noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.before.only(noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.afterEach.only(noop);
	}, new TypeError(errorMessage));

	t.throws(() => {
		runner.chain.after.only(noop);
	}, new TypeError(errorMessage));

	t.end();
});

test('validate accepts skipping failing tests', t => {
	t.plan(2);

	const runner = new Runner();

	runner.chain.test.skip.failing('skip failing', noop);

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.testCount, 1);
		t.is(stats.skipCount, 1);
		t.end();
	});
});

test('runOnlyExclusive option test', t => {
	t.plan(1);

	const runner = new Runner();
	const options = {runOnlyExclusive: true};
	const arr = [];

	runner.chain.test(() => {
		arr.push('a');
	});

	runner.run(options).then(stats => {
		t.is(stats, null);
		t.end();
	});
});

test('options.serial forces all tests to be serial', t => {
	t.plan(1);

	const runner = new Runner({serial: true});
	const arr = [];

	runner.chain.cb(a => {
		setTimeout(() => {
			arr.push(1);
			a.end();
		}, 200);
		a.pass();
	});

	runner.chain.cb(a => {
		setTimeout(() => {
			arr.push(2);
			a.end();
		}, 100);
		a.pass();
	});

	runner.chain.test(a => {
		a.pass();
		t.strictDeepEqual(arr, [1, 2]);
		t.end();
	});

	runner.run({});
});

test('options.bail will bail out', t => {
	t.plan(1);

	const runner = new Runner({bail: true});

	runner.chain.test(a => {
		t.pass();
		a.fail();
	});

	runner.chain.test(() => {
		t.fail();
	});

	runner.run({}).then(() => {
		t.end();
	});
});

test('options.bail will bail out (async)', t => {
	t.plan(2);

	const runner = new Runner({bail: true});
	const tests = [];

	runner.chain.cb(a => {
		setTimeout(() => {
			tests.push(1);
			a.fail();
			a.end();
		}, 100);
		a.pass();
	});

	runner.chain.cb(a => {
		setTimeout(() => {
			tests.push(2);
			a.end();
		}, 300);
		a.pass();
	});

	runner.run({}).then(() => {
		t.strictDeepEqual(tests, [1]);
		// With concurrent tests there is no stopping the second `setTimeout` callback from happening.
		// See the `bail + serial` test below for comparison
		setTimeout(() => {
			t.strictDeepEqual(tests, [1, 2]);
			t.end();
		}, 250);
	});
});

test('options.bail + serial - tests will never happen (async)', t => {
	t.plan(2);

	const runner = new Runner({
		bail: true,
		serial: true
	});
	const tests = [];

	runner.chain.cb(a => {
		setTimeout(() => {
			tests.push(1);
			a.fail();
			a.end();
		}, 100);
	});

	runner.chain.cb(a => {
		setTimeout(() => {
			tests.push(2);
			a.end();
		}, 300);
	});

	runner.run({}).then(() => {
		t.strictDeepEqual(tests, [1]);
		setTimeout(() => {
			t.strictDeepEqual(tests, [1]);
			t.end();
		}, 250);
	});
});

test('options.match will not run tests with non-matching titles', t => {
	t.plan(5);

	const runner = new Runner({
		match: ['*oo', '!foo']
	});

	runner.chain.test('mhm. grass tasty. moo', a => {
		t.pass();
		a.pass();
	});

	runner.chain.test('juggaloo', a => {
		t.pass();
		a.pass();
	});

	runner.chain.test('foo', a => {
		t.fail();
		a.pass();
	});

	runner.chain.test(a => {
		t.fail();
		a.pass();
	});

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.skipCount, 0);
		t.is(stats.passCount, 2);
		t.is(stats.testCount, 2);
		t.end();
	});
});

test('options.match hold no effect on hooks with titles', t => {
	t.plan(4);

	const runner = new Runner({
		match: ['!before*']
	});

	let actual;

	runner.chain.before('before hook with title', () => {
		actual = 'foo';
	});

	runner.chain.test('after', a => {
		t.is(actual, 'foo');
		a.pass();
	});

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.skipCount, 0);
		t.is(stats.passCount, 1);
		t.is(stats.testCount, 1);
		t.end();
	});
});

test('options.match overrides .only', t => {
	t.plan(5);

	const runner = new Runner({
		match: ['*oo']
	});

	runner.chain.test('moo', a => {
		t.pass();
		a.pass();
	});

	runner.chain.test.only('boo', a => {
		t.pass();
		a.pass();
	});

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.skipCount, 0);
		t.is(stats.passCount, 2);
		t.is(stats.testCount, 2);
		t.end();
	});
});

test('options.match includes anonymous tests in negative matches', t => {
	t.plan(4);

	const runner = new Runner({
		match: ['!*oo']
	});

	runner.chain.test('foo', a => {
		t.fail();
		a.pass();
	});

	runner.chain.test(a => {
		t.pass();
		a.pass();
	});

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.skipCount, 0);
		t.is(stats.passCount, 1);
		t.is(stats.testCount, 1);
		t.end();
	});
});

test('macros: Additional args will be spread as additional args on implementation function', t => {
	t.plan(3);

	const runner = new Runner();

	runner.chain.test('test1', function (a) {
		t.deepEqual(slice.call(arguments, 1), ['foo', 'bar']);
		a.pass();
	}, 'foo', 'bar');

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.passCount, 1);
		t.is(stats.testCount, 1);
		t.end();
	});
});

test('macros: Customize test names attaching a `title` function', t => {
	t.plan(8);

	const expectedTitles = [
		'defaultA',
		'suppliedB',
		'defaultC'
	];

	const expectedArgs = [
		['A'],
		['B'],
		['C']
	];

	function macroFn(avaT) {
		t.deepEqual(slice.call(arguments, 1), expectedArgs.shift());
		avaT.pass();
	}

	macroFn.title = (title, firstArg) => (title || 'default') + firstArg;

	const runner = new Runner();

	runner.on('test', props => {
		t.is(props.title, expectedTitles.shift());
	});

	runner.chain.test(macroFn, 'A');
	runner.chain.test('supplied', macroFn, 'B');
	runner.chain.test(macroFn, 'C');

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.passCount, 3);
		t.is(stats.testCount, 3);
		t.end();
	});
});

test('match applies to macros', t => {
	t.plan(3);

	function macroFn(avaT) {
		avaT.pass();
	}

	macroFn.title = (title, firstArg) => `${firstArg}bar`;

	const runner = new Runner({
		match: ['foobar']
	});

	runner.on('test', props => {
		t.is(props.title, 'foobar');
	});

	runner.chain.test(macroFn, 'foo');
	runner.chain.test(macroFn, 'bar');

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.passCount, 1);
		t.is(stats.testCount, 1);
		t.end();
	});
});

test('arrays of macros', t => {
	const expectedArgsA = [
		['A'],
		['B'],
		['C']
	];

	const expectedArgsB = [
		['A'],
		['B'],
		['D']
	];

	function macroFnA(a) {
		t.deepEqual(slice.call(arguments, 1), expectedArgsA.shift());
		a.pass();
	}

	function macroFnB(a) {
		t.deepEqual(slice.call(arguments, 1), expectedArgsB.shift());
		a.pass();
	}

	const runner = new Runner();

	runner.chain.test([macroFnA, macroFnB], 'A');
	runner.chain.test([macroFnA, macroFnB], 'B');
	runner.chain.test(macroFnA, 'C');
	runner.chain.test(macroFnB, 'D');

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.passCount, 6);
		t.is(stats.testCount, 6);
		t.is(expectedArgsA.length, 0);
		t.is(expectedArgsB.length, 0);
		t.end();
	});
});

test('match applies to arrays of macros', t => {
	t.plan(3);

	// Foo
	function fooMacro(a) {
		t.fail();
		a.pass();
	}
	fooMacro.title = (title, firstArg) => `${firstArg}foo`;

	function barMacro(avaT) {
		avaT.pass();
	}
	barMacro.title = (title, firstArg) => `${firstArg}bar`;

	function bazMacro(a) {
		t.fail();
		a.pass();
	}
	bazMacro.title = firstArg => `${firstArg}baz`;

	const runner = new Runner({
		match: ['foobar']
	});

	runner.on('test', props => {
		t.is(props.title, 'foobar');
	});

	runner.chain.test([fooMacro, barMacro, bazMacro], 'foo');
	runner.chain.test([fooMacro, barMacro, bazMacro], 'bar');

	runner.run({}).then(() => {
		const stats = runner.buildStats();
		t.is(stats.passCount, 1);
		t.is(stats.testCount, 1);
		t.end();
	});
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.ilivoo</groupId>
	<artifactId>common</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<packaging>pom</packaging>

	<name>common</name>
	<url>http://www.ilivoo.com</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<junit.version>4.10</junit.version>
		<spring.version>3.0.7.RELEASE</spring.version>
		<sfl4j.version>1.7.5</sfl4j.version>
		<log4j.version>1.2.17</log4j.version>
		<javassist.version>3.12.1.GA</javassist.version>
	</properties>

	<dependencies>
		<!-- junit 配置 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- log 配置 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${sfl4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${sfl4j.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${sfl4j.version}</version>
		</dependency>
		<!-- spring 配置 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>${javassist.version}</version>
		</dependency>
	</dependencies>
	<modules>
		<module>socket</module>
		<module>utility</module>
		<module>resource</module>
		<module>event</module>
		<module>schedule</module>
		<module>recache</module>
	</modules>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
				<executions>
					<execution>
						<id>default-compile</id>
						<phase>compile</phase>
						<goals>
							<goal>compile</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
/**
 * External dependencies
 */
import styled, { createGlobalStyle } from 'styled-components';
import { useState } from '@googleforcreators/react';
import {
  ContextMenu,
  ContextMenuComponents,
  Icons,
  Headline,
  Text,
  PLACEMENT,
} from '@googleforcreators/design-system';

/**
 * Internal dependencies
 */
import StoryContext from '../../../../app/story/context';
import Row from '../../row';
import Color from '..';

export default {
  title: 'Stories Editor/Components/Form/Color',
  component: Color,
};

const GlobalStyle = createGlobalStyle`
  *, *::before, *::after {
    box-sizing: border-box;
  }
`;

const Background = styled.div`
  background-color: ${({ theme }) => theme.colors.bg.primary};
  width: 100%;
  height: 100vh;
  position: relative;
  z-index: 0;
`;

const DesignPanelWrapper = styled.div`
  position: absolute;
  top: 0;
  bottom: 0;
  width: 312px;
  padding: 16px;
  background-color: ${({ theme }) => theme.colors.bg.secondary};
`;

const DesignMenuWrapper = styled.div`
  padding: 50px;
  display: flex;
  height: 100%;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
`;

const DesignMenuSingle = styled.div`
  width: 600px;
`;

const ContextMenuWrapper = styled.div`
  display: flex;
`;

const ColorInputWrapper = styled.div`
  width: ${({ $width }) => $width}px;
  flex: 0 0 ${({ $width }) => $width}px;
`;

function ColorInput({ initialColor, ...rest }) {
  const [color, setColor] = useState(initialColor);

  return <Color onChange={setColor} label="Color" value={color} {...rest} />;
}

const RED = { type: 'solid', color: { r: 255, g: 0, b: 0 } };
const BLUE = { type: 'solid', color: { r: 0, g: 0, b: 255 } };
const GREEN = { type: 'solid', color: { r: 0, g: 255, b: 0 } };
const YELLOW = { type: 'solid', color: { r: 255, g: 255, b: 0 } };
const MAGENTA = { type: 'solid', color: { r: 255, g: 0, b: 255 } };
const CYAN = { type: 'solid', color: { r: 0, g: 255, b: 255 } };
const RED_GREEN = {
  type: 'linear',
  stops: [
    { color: { r: 255, g: 0, b: 0 }, position: 0 },
    { color: { r: 0, g: 255, b: 0 }, position: 1 },
  ],
  rotation: 0.375,
};

function Wrapper({ children }) {
  const [globalColors, setGlobalColors] = useState([RED, GREEN, BLUE]);
  const [storyColors, setStoryColors] = useState([CYAN, MAGENTA, YELLOW]);
  const updateStory = ({
    properties: { globalStoryStyles, currentStoryStyles },
  }) => {
    if (globalStoryStyles) {
      setGlobalColors(globalStoryStyles.colors);
    }
    if (currentStoryStyles) {
      setStoryColors(currentStoryStyles.colors);
    }
  };
  const storyContext = {
    state: {
      currentPage: {
        background: RED,
      },
      selectedElements: [],
      story: {
        globalStoryStyles: {
          colors: globalColors,
        },
        currentStoryStyles: {
          colors: storyColors,
        },
      },
    },
    actions: {
      updateStory,
    },
  };
  return (
    <StoryContext.Provider value={storyContext}>
      <Background>
        <GlobalStyle />
        {children}
      </Background>
    </StoryContext.Provider>
  );
}

function DesignPanelColorInput({ label, ...props }) {
  return (
    <>
      <Text>{label}</Text>
      <Row>
        <ColorInput {...props} />
      </Row>
    </>
  );
}

function DummyButton({ children }) {
  return (
    <ContextMenuComponents.MenuButton onClick={() => {}}>
      <ContextMenuComponents.MenuIcon>
        {children}
      </ContextMenuComponents.MenuIcon>
    </ContextMenuComponents.MenuButton>
  );
}

function DesignMenuColorInput({ label, width, atStart = false, ...props }) {
  return (
    <DesignMenuSingle>
      <Headline style={{ margin: '40px 0 10px' }}>{label}</Headline>
      <ContextMenuWrapper>
        <ContextMenu
          isInline
          isHorizontal
          isSecondary
          isAlwaysVisible
          disableControlledTabNavigation
          aria-label={label}
        >
          {atStart && (
            <>
              <ColorInputWrapper $width={width}>
                <ColorInput {...props} />
              </ColorInputWrapper>
              <ContextMenuComponents.MenuSeparator />
            </>
          )}
          <DummyButton>
            <Icons.PictureSwap />
          </DummyButton>
          <ContextMenuComponents.MenuSeparator />
          <DummyButton>
            <Icons.Trash />
          </DummyButton>
          <DummyButton>
            <Icons.ColorBucket />
          </DummyButton>
          <DummyButton>
            <Icons.MirrorLeftRight />
          </DummyButton>
          <DummyButton>
            <Icons.MirrorUpDown />
          </DummyButton>
          {!atStart && (
            <>
              <ContextMenuComponents.MenuSeparator />
              <ColorInputWrapper $width={width}>
                <ColorInput {...props} />
              </ColorInputWrapper>
            </>
          )}
          <ContextMenuComponents.MenuSeparator />
          <DummyButton>
            <Icons.Cross />
          </DummyButton>
        </ContextMenu>
      </ContextMenuWrapper>
    </DesignMenuSingle>
  );
}

function DesignPanel({ style, pickerPlacement }) {
  return (
    <Wrapper>
      <DesignPanelWrapper style={style}>
        <DesignPanelColorInput
          label="Without saved colors"
          initialColor={MAGENTA}
          pickerPlacement={pickerPlacement}
        />
        <DesignPanelColorInput
          label="With saved colors"
          initialColor={YELLOW}
          allowsSavedColors
          pickerPlacement={pickerPlacement}
        />
        <DesignPanelColorInput
          label="With dropper"
          initialColor={BLUE}
          hasEyedropper
          pickerPlacement={pickerPlacement}
        />
        <DesignPanelColorInput
          label="Without opacity"
          initialColor={CYAN}
          allowsOpacity={false}
          pickerPlacement={pickerPlacement}
        />
        <DesignPanelColorInput
          label="With gradient"
          initialColor={RED_GREEN}
          allowsGradient
          pickerPlacement={pickerPlacement}
        />
      </DesignPanelWrapper>
    </Wrapper>
  );
}

export function DesignPanelLeft() {
  return (
    <DesignPanel style={{ left: 0 }} pickerPlacement={PLACEMENT.RIGHT_START} />
  );
}

export function DesignPanelRight() {
  return <DesignPanel style={{ right: 0 }} />;
}

export function DesignMenu() {
  return (
    <Wrapper>
      <DesignMenuWrapper>
        <DesignMenuColorInput
          width={216}
          atStart
          label="All options"
          initialColor={RED}
          // Params below are to the color input component
          maxHeight={362}
          pickerPlacement={PLACEMENT.TOP_END}
          isInDesignMenu
          shouldCloseOnSelection
          allowsSavedColors
          allowsSavedColorDeletion={false}
          hasEyedropper
          pickerHasEyedropper={false}
        />
        <DesignMenuColorInput
          width={98}
          atStart
          label="No inputs, with eyedropper"
          initialColor={BLUE}
          // Params below are to the color input component
          maxHeight={362}
          pickerPlacement={PLACEMENT.TOP_END}
          isInDesignMenu
          shouldCloseOnSelection
          allowsSavedColors
          allowsSavedColorDeletion={false}
          hasInputs={false}
          hasEyedropper
          pickerHasEyedropper={false}
        />
        <DesignMenuColorInput
          width={60}
          atStart
          label="No inputs, without eyedropper"
          initialColor={CYAN}
          // Params below are to the color input component
          maxHeight={362}
          pickerPlacement={PLACEMENT.TOP_END}
          hasInputs={false}
          isInDesignMenu
          shouldCloseOnSelection
          allowsSavedColors
          allowsSavedColorDeletion={false}
        />
        <DesignMenuColorInput
          width={60}
          atStart
          label="No inputs, allows gradient"
          initialColor={RED_GREEN}
          // Params below are to the color input component
          maxHeight={362}
          pickerPlacement={PLACEMENT.TOP_END}
          hasInputs={false}
          isInDesignMenu
          shouldCloseOnSelection
          allowsGradient
          allowsSavedColors
          allowsSavedColorDeletion={false}
        />
        <DesignMenuColorInput
          width={60}
          label="No inputs, to the right"
          initialColor={YELLOW}
          // Params below are to the color input component
          maxHeight={362}
          pickerPlacement={PLACEMENT.TOP_START}
          hasInputs={false}
          isInDesignMenu
          shouldCloseOnSelection
          allowsSavedColors
          allowsSavedColorDeletion={false}
        />
      </DesignMenuWrapper>
    </Wrapper>
  );
}


text:
C="""
  This module does NOTHING except load the PAWS terminal and execute the
  main() function found there. All the housekeeping needed to actually get
  ready for your game is handled by the modules in the PAWS folder/package.

  Written By: Roger Plowman
  Written On: 01/19/2008                                                        #
  """
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#********************************************************************************
#                                 Style Guidelines                              #
#                                                                               #
C="""
  To organize PAWS all the files share the same design conventions. The
  files have been organized into sections to make it easier to navigate
  through them with a text editor.

  The major sections are marked by boxes with borders made of ******'s that
  stretch across the entire page. If you search for #*** you can jump from
  section to section. The sections provide an overview of the entire file.

  Within each section you'll find a set of related classes, objects, and
  functions. If you use the Notepad++ text editor, the Alt-0 keystroke will
  fold the file into its smallest, most easily navigated form. Clicking a +
  to the left of a folded section will allow you to unfold only that
  section. Thus you can keep most of the file folded, seeing only the part
  you're actually interested in. This helps tremendously.

  COLOR CODES

  This source code is best read with a color coding editor, preferably
  Notepad++ using 18 point Lucinda Console font, in 1280x1024 resolution
  (large fonts).

  The following colors were used:

  Grey          - Comments (italics)
  Orange        - Quoted Text (bold)
  Bright Blue   - Python and PAWS keywords (bold)
  Green         - Local Variables (bold)
  Purple        - Operators, parentheses, etc.
  Red           - Numbers
  """

from PAWS.Terminal import *     # Imports required code
main()                          # wxPython main loop


text:
layout: docwithnav
title: "Kubernetes Large Cluster"
---
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->

<!-- END MUNGE: UNVERSIONED_WARNING -->

# Kubernetes Large Cluster

## Support

At v1.0, Kubernetes supports clusters up to 100 nodes with 30 pods per node and 1-2 containers per pod.

## Setup

A cluster is a set of nodes (physical or virtual machines) running Kubernetes agents, managed by a "master" (the cluster-level control plane).

Normally the number of nodes in a cluster is controlled by the the value `NUM_MINIONS` in the platform-specific `config-default.sh` file (for example, see [GCE's `config-default.sh`](http://releases.k8s.io/v1.0.6/cluster/gce/config-default.sh)).

Simply changing that value to something very large, however, may cause the setup script to fail for many cloud providers. A GCE deployment, for example, will run in to quota issues and fail to bring the cluster up.

When setting up a large Kubernetes cluster, the following issues must be considered.

### Quota Issues

To avoid running into cloud provider quota issues, when creating a cluster with many nodes, consider:
* Increase the quota for things like CPU, IPs, etc.
  * In [GCE, for example,](https://cloud.google.com/compute/docs/resource-quotas) you'll want to increase the quota for:
    * CPUs
    * VM instances
    * Total persistent disk reserved
    * In-use IP addresses
    * Firewall Rules
    * Forwarding rules
    * Routes
    * Target pools
* Gating the setup script so that it brings up new node VMs in smaller batches with waits in between, because some cloud providers rate limit the creation of VMs.

### Addon Resources

To prevent memory leaks or other resource issues in [cluster addons](https://releases.k8s.io/v1.0.6/cluster/addons) from consuming all the resources available on a node, Kubernetes sets resource limits on addon containers to limit the CPU and Memory resources they can consume (See PR [#10653](https://github.com/GoogleCloudPlatform/kubernetes/pull/10653/files) and [#10778](https://github.com/GoogleCloudPlatform/kubernetes/pull/10778/files)).

For example:

{% highlight yaml %}
{% raw %}
containers:
  - image: gcr.io/google_containers/heapster:v0.15.0
    name: heapster
    resources:
      limits:
        cpu: 100m
        memory: 200Mi
{% endraw %}
{% endhighlight %}

These limits, however, are based on data collected from addons running on 4-node clusters (see [#10335](https://github.com/GoogleCloudPlatform/kubernetes/issues/10335#issuecomment-117861225)). The addons consume a lot more resources when running on large deployment clusters (see [#5880](https://github.com/GoogleCloudPlatform/kubernetes/issues/5880#issuecomment-113984085)). So, if a large cluster is deployed without adjusting these values, the addons may continuously get killed because they keep hitting the limits.

To avoid running into cluster addon resource issues, when creating a cluster with many nodes, consider the following:
* Scale memory and CPU limits for each of the following addons, if used, along with the size of cluster (there is one replica of each handling the entire cluster so memory and CPU usage tends to grow proportionally with size/load on cluster):
  * Heapster ([GCM/GCL backed](http://releases.k8s.io/v1.0.6/cluster/addons/cluster-monitoring/google/heapster-controller.yaml), [InfluxDB backed](http://releases.k8s.io/v1.0.6/cluster/addons/cluster-monitoring/influxdb/heapster-controller.yaml), [InfluxDB/GCL backed](http://releases.k8s.io/v1.0.6/cluster/addons/cluster-monitoring/googleinfluxdb/heapster-controller-combined.yaml), [standalone](http://releases.k8s.io/v1.0.6/cluster/addons/cluster-monitoring/standalone/heapster-controller.yaml))
  * [InfluxDB and Grafana](http://releases.k8s.io/v1.0.6/cluster/addons/cluster-monitoring/influxdb/influxdb-grafana-controller.yaml)
  * [skydns, kube2sky, and dns etcd](http://releases.k8s.io/v1.0.6/cluster/addons/dns/skydns-rc.yaml.in)
  * [Kibana](http://releases.k8s.io/v1.0.6/cluster/addons/fluentd-elasticsearch/kibana-controller.yaml)
* Scale number of replicas for the following addons, if used, along with the size of cluster (there are multiple replicas of each so increasing replicas should help handle increased load, but, since load per replica also increases slightly, also consider increasing CPU/memory limits):
  * [elasticsearch](http://releases.k8s.io/v1.0.6/cluster/addons/fluentd-elasticsearch/es-controller.yaml)
* Increase memory and CPU limits sligthly for each of the following addons, if used, along with the size of cluster (there is one replica per node but CPU/memory usage increases slightly along with cluster load/size as well):
  * [FluentD with ElasticSearch Plugin](http://releases.k8s.io/v1.0.6/cluster/saltbase/salt/fluentd-es/fluentd-es.yaml)
  * [FluentD with GCP Plugin](http://releases.k8s.io/v1.0.6/cluster/saltbase/salt/fluentd-gcp/fluentd-gcp.yaml)

For directions on how to detect if addon containers are hitting resource limits, see the [Troubleshooting section of Compute Resources](../user-guide/compute-resources.html#troubleshooting).

<!-- BEGIN MUNGE: IS_VERSIONED -->
<!-- TAG IS_VERSIONED -->
<!-- END MUNGE: IS_VERSIONED -->

<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/admin/cluster-large.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->


text:
> Revert the previous `file.path` change

Many plugins change the `file.path` somehow. Most commonly the file extension. For example `gulp-babel` changes `.jsx` extensions to `.js` since it compiles JSX. Sometimes that's undesirable though. This plugin makes it easy to revert the path change.

## Install

```
$ npm install --save-dev gulp-revert-path
```

## Usage

```js
const gulp = require('gulp');
const babel = require('gulp-babel');
const revertPath = require('gulp-revert-path');
const rename = require('gulp-rename');

exports.default = () => (
	gulp.src('src/app.jsx')
		.pipe(babel())       // file.path => src/app.js
		.pipe(revertPath())  // file.path => src/app.jsx
		.pipe(gulp.dest('dist'))
);

exports.es2015 = () => (
	gulp.src('src/app.txt')
		.pipe(rename('src/app.jsx'))  // file.path => src/app.jsx
		.pipe(babel())                // file.path => src/app.js
		.pipe(revertPath(2))          // file.path => src/app.txt
		.pipe(gulp.dest('dist'))
);
```

## API

### revertPath(reversions?)

#### reversions

Type: `number`<br>
Default: `1`

Number of times to revert the path.

## Related

- [vinyl-paths](https://github.com/sindresorhus/vinyl-paths) - Get the file paths in a vinyl stream


text:
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;

namespace UnhandledExceptionHandling
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // Process unhandled exception
            var shutdown = false;

            // Process exception
            if (e.Exception is DivideByZeroException)
            {
                // Recoverable - continue processing
                shutdown = false;
            }
            else if (e.Exception is ArgumentNullException)
            {
                // Unrecoverable - end processing
                shutdown = true;
            }

            if (shutdown)
            {
                // If unrecoverable, attempt to save data
                var result =
                    MessageBox.Show("Application must exit:\n\n" + e.Exception.Message + "\n\nSave before exit?", "app",
                        MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (result == MessageBoxResult.Yes)
                {
                    // Save data
                }

                // Add entry to event log
                EventLog.WriteEntry("app", "Unrecoverable Exception: " + e.Exception.Message, EventLogEntryType.Error);

                // Return exit code
                Shutdown(-1);
            }

            // Prevent default unhandled exception processing
            e.Handled = true;
        }
    }
}


text:
"""drop old user and value column

Revision ID: 49bceeb0e61d
Revises: 16c38836d489
Create Date: 2015-08-05 16:32:03.298543

"""

# revision identifiers, used by Alembic.
revision = '49bceeb0e61d'
down_revision = '16c38836d489'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.drop_column('posts', 'user')
    op.drop_column('posts', 'value')

def downgrade():
    op.add_column('posts', sa.Column('user', sa.String(64), nullable=False))
    op.add_column('posts', sa.Column('value', sa.String(64), nullable=False))


text:
[Example project](../../examples/material-ui/)

Material-UI [TextField](https://material-ui.com/api/text-field/) has for long
time caused problems for Reagent users. The problem is that `TextField` wraps the
`input` element inside a component so that Reagent is not able to enable
input cursor fixes, which are required due to [async rendering](http://reagent-project.github.io/news/reagent-is-async.html).

Good news is that Material-UI v1 has a property that can be used to provide
the input component to `TextField`:

```cljs
(ns example.material-ui
  (:require ["material-ui" :as mui]
            [reagent.core :as r]))

(def text-field (r/adapt-react-class mui/TextField))

(def value (r/atom ""))

(def input-component
  (r/reactify-component
    (fn [props]
      [:input (-> props
                  (assoc :ref (:inputRef props))
                  (dissoc :inputRef))])))

(def example []
  [text-field
   {:value @value
    :on-change #(reset! value (.. e -target -value))
    :InputProps {:inputComponent input-component}}])
```

`reactify-component` can be used to convert Reagent component into React component,
which can then be passed into Material-UI. The component should be created once
(i.e. on top level) to ensure it is not unnecessarily redefined, causing the
component to be re-mounted.
For some reason Material-UI uses different name for `ref`, so the `inputRef` property
should be renamed by the input component.

## Wrapping for easy use

Instead of providing `:InputProps :inputComponent` option to every `TextField`,
it is useful to wrap the `TextField` component in a way that the option is added always:

```cljs
(defn text-field [props & children]
  (let [props (-> props
                  (assoc-in [:InputProps :inputComponent] input-component)
                  rtpl/convert-prop-value)]
    (apply r/create-element mui/TextField props (map r/as-element children))))
```

Here `r/create-element` and `reagent.impl.template/convert-prop-value` achieve
the same as what `adapt-react-class` does, but allows modifying the props.

**Check the example project for complete code.** Some additional logic is
required to ensure option like `:multiline` and `:select` work correctly,
as they affect how the `inputComponent` should work.

TODO: `:multiline` `TextField` without `:rows` (i.e. automatic height) doesn't
work, because that requires Material-UI `Input/Textarea`, which doesn't work
with Reagent cursor fix.


text:
package com.avsystem.commons
package redis.commands

import com.avsystem.commons.redis.RedisApi.Batches
import com.avsystem.commons.redis.{CommandsSuite, RedisApi, RedisBatch}
import com.avsystem.commons.serialization.HasApplyUnapplyCodec

case class Event(idx: Int, data: String)
object Event extends HasApplyUnapplyCodec[Event]

trait StreamsApiSuite extends CommandsSuite {

  val api: Batches.StringTyped.WithRecord[Event] = RedisApi.Batches.StringTyped.recordType[Event]

  import api.{XEntry => Entry, _}

  def id(i: Int): XEntryId = XEntryId(0, i.toLong)
  def ids(from: Int, to: Int): Seq[XEntryId] = (from to to).map(id)
  def entry(i: Int): Entry = Entry(id(i), Event(i, s"value$i"))
  def entries(from: Int, to: Int): Seq[Entry] = (from to to).map(entry)

  apiTest("XACK") {
    setup(
      xgroupCreate("key", XGroup("g"), mkstream = true),
      RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))),
      xreadgroupSingle("key", XGroup("g"), XConsumer("c"))
    )
    xack("key", XGroup("g"), id(1)).assertEquals(true)
    xack("key", XGroup("g"), id(1)).assertEquals(false)
    xack("key", XGroup("g"), id(1), id(2), id(3)).assertEquals(2)
    xack("key", XGroup("g"), (1 to 10).map(id)).assertEquals(7)
  }

  apiTest("XADD") {
    xadd("key", Event(42, "fuu")).get
    val lastId = xadd("key", Event(42, "fag")).get
    xlen("key").assertEquals(2)
    xadd("key", Event(42, "lel"), lastId.inc, XMaxlen(1)).assertEquals(lastId.inc)
    xlen("key").assert(_ >= 1)
    val entry = XEntry(lastId.inc.inc, Event(42, "dafuq"))
    xaddEntry("key", entry, XMaxlen(1, approx = false)).assertEquals(lastId.inc.inc)
    xlen("key").assertEquals(1)
  }

  apiTest("XCLAIM") {
    setup(
      xgroupCreate("key", XGroup("g"), mkstream = true),
      RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))),
      xreadgroupSingle("key", XGroup("g"), XConsumer("c1"), count = 5)
    )
    // nonexistent id
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 0, id(0)).assertEquals(Opt.Empty)
    // existing id already claimed by self
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 0, id(1)).assertEquals(Opt(entry(1)))
    // existing id claimed by someone else
    xclaimSingle("key", XGroup("g"), XConsumer("c2"), 0, id(1)).assertEquals(Opt(entry(1)))
    // maxIdleTime not exceeded
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 5000, id(1)).assertEquals(Opt.Empty)
    // force set maxIdleTime and claim again
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 0, id(1), idleMillis = 10000).assertEquals(Opt(entry(1)))
    xclaimSingle("key", XGroup("g"), XConsumer("c2"), 5000, id(1)).assertEquals(Opt(entry(1)))
    // force set msUnixTime and claim again
    xclaimSingle("key", XGroup("g"), XConsumer("c2"), 0, id(1), msUnixTime = 0).assertEquals(Opt(entry(1)))
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 5000, id(1)).assertEquals(Opt(entry(1)))
    // retrycount
    xclaimSingle("key", XGroup("g"), XConsumer("c2"), 0, id(1), retrycount = 42).assertEquals(Opt(entry(1)))
    xpendingEntries("key", XGroup("g"), 1, id(1)).assert(_.headOpt.exists(_.deliveredCount == 42))
    // unclaimed id
    xclaimSingle("key", XGroup("g"), XConsumer("c1"), 0, id(6)).assertEquals(Opt.Empty)
    xclaimSingle("key", XGroup("g"), XConsumer("c2"), 0, id(6), force = true).assertEquals(Opt(entry(6)))
    // multiple ids
    xclaim("key", XGroup("g"), XConsumer("c1"), 0, ids(1, 10)).assertEquals(entries(1, 6))
    xclaimJustid("key", XGroup("g"), XConsumer("c1"), 0, ids(1, 10)).assertEquals(ids(1, 6))
    xclaimJustid("key", XGroup("g"), XConsumer("c1"), 0, ids(1, 10), force = true).assertEquals(ids(1, 10))
  }

  apiTest("XDEL") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xdel("key", id(0)).assertEquals(false)
    xdel("key", id(1)).assertEquals(true)
    xdel("key", id(1), id(2), id(3)).assertEquals(2)
    xdel("key", ids(1, 10)).assertEquals(7)
  }

  apiTest("XGROUP") {
    xgroupCreate("key", XGroup("g1"), mkstream = true).get
    xgroupCreate("key", XGroup("g2"), id(1)).get
    xgroupSetid("key", XGroup("g2"), id(2)).get
    xgroupDestroy("key", XGroup("g1")).assertEquals(true)
    xgroupDestroy("key", XGroup("g3")).assertEquals(false)
    xgroupDelconsumer("key", XGroup("g2"), XConsumer("c")).assertEquals(false)
    xaddEntry("key", entry(3)).get
    xreadgroupSingle("key", XGroup("g2"), XConsumer("c")).get
    xgroupDelconsumer("key", XGroup("g2"), XConsumer("c")).assertEquals(true)
  }

  apiTest("XINFO STREAM") {
    setup(
      xaddEntry("key", entry(1)),
      xgroupCreate("key", XGroup("g"))
    )
    val xsi = xinfoStream("key").get
    assert(xsi.length == 1)
    assert(xsi.groups == 1)
    assert(xsi.firstEntry == entry(1))
    assert(xsi.lastEntry == entry(1))
    assert(xsi.lastGeneratedId == id(1))
  }

  apiTest("XINFO GROUPS") {
    setup(xgroupCreate("key", XGroup("g"), mkstream = true))
    val Seq(xgi) = xinfoGroups("key").get
    assert(xgi.name == XGroup("g"))
    assert(xgi.consumers == 0)
    assert(xgi.pending == 0)
    assert(xgi.lastDeliveredId == id(0))
  }

  apiTest("XINFO CONSUMERS") {
    setup(
      xgroupCreate("key", XGroup("g"), mkstream = true),
      xaddEntry("key", entry(1)),
      xreadgroupSingle("key", XGroup("g"), XConsumer("c"))
    )
    val Seq(xci) = xinfoConsumers("key", XGroup("g")).get
    assert(xci.name == XConsumer("c"))
    assert(xci.pending == 1)
  }

  apiTest("XLEN") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xlen("key").assertEquals(10)
  }

  apiTest("XPENDING") {
    setup(
      xgroupCreate("key", XGroup("g"), mkstream = true),
      RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))),
      xreadgroupSingle("key", XGroup("g"), XConsumer("c"))
    )
    xpending("key", XGroup("g")).assertEquals(XPendingOverview(10, id(1), id(10), Map(XConsumer("c") -> 10)))
    val Seq(xpe) = xpendingEntries("key", XGroup("g"), 1).get
    assert(xpe.id == id(1))
    assert(xpe.consumer == XConsumer("c"))
    assert(xpe.deliveredCount == 1)
    xpendingEntries("key", XGroup("g"), 5, id(3), id(9), XConsumer("c")).map(_.map(_.id)).assertEquals(ids(3, 7))
    xpendingEntries("key", XGroup("g"), 5, id(3), id(9), XConsumer("c2")).assertEquals(Seq.empty)
  }

  apiTest("XRANGE") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xrange("key").assertEquals(entries(1, 10))
    xrange("key", start = id(3)).assertEquals(entries(3, 10))
    xrange("key", end = id(3)).assertEquals(entries(1, 3))
    xrange("key", start = id(3), end = id(7)).assertEquals(entries(3, 7))
    xrange("key", start = id(3), end = id(7), count = 2).assertEquals(entries(3, 4))
  }

  apiTest("XREAD") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xreadSingle("key", Opt.Empty).assertEquals(Seq.empty)
    xreadSingle("key", id(0).opt).assertEquals(entries(1, 10))
    xreadSingle("key", id(5).opt).assertEquals(entries(6, 10))
    xreadSingle("key", id(5).opt, count = 2).assertEquals(entries(6, 7))
    xreadSingle("key", Opt.Empty, blockMillis = 10).assertEquals(Seq.empty)
    xread(List("key" -> id(0).opt)).assertEquals(Map("key" -> entries(1, 10)))
  }

  apiTest("XREADGROUP") {
    setup(
      xgroupCreate("key", XGroup("g"), mkstream = true),
      RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i)))
    )
    xreadgroupSingle("key", XGroup("g"), XConsumer("c"), count = 5).assertEquals(entries(1, 5))
    xreadgroupSingle("key", XGroup("g"), XConsumer("c")).assertEquals(entries(6, 10))
    xreadgroupSingle("key", XGroup("g"), XConsumer("c")).assertEquals(Seq.empty)
    xreadgroupSingle("key", XGroup("g"), XConsumer("c"), id(5)).assertEquals(entries(6, 10))
    xreadgroupSingle("key", XGroup("g"), XConsumer("c"), id(5), count = 10, blockMillis = 1000).assertEquals(entries(6, 10))
    xreadgroupSingle("key", XGroup("g"), XConsumer("c"), blockMillis = 10).assertEquals(Seq.empty)
    xreadgroup(XGroup("g"), XConsumer("c"), List("key" -> id(5).opt)).assertEquals(Map("key" -> entries(6, 10)))
  }

  apiTest("XREVRANGE") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xrevrange("key").assertEquals(entries(1, 10).reverse)
    xrevrange("key", start = id(3)).assertEquals(entries(3, 10).reverse)
    xrevrange("key", end = id(3)).assertEquals(entries(1, 3).reverse)
    xrevrange("key", end = id(7), start = id(3)).assertEquals(entries(3, 7).reverse)
    xrevrange("key", end = id(7), start = id(3), count = 2).assertEquals(entries(6, 7).reverse)
  }

  apiTest("XTRIM") {
    setup(RedisBatch.traverse(1 to 10)(i => xaddEntry("key", entry(i))))
    xtrim("key", 5, approx = false).assertEquals(5)
    xtrim("key", 4).assertEquals(0)
    xtrim("key", XMaxlen(4)).assertEquals(0)
    xtrim("key", XMaxlen(4, approx = false)).assertEquals(1)
  }
}


text:
Dependencies:

- Install Tesseract using Homebrew or MacPorts