text:
package com.vaadin.tests.components.table;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.AbstractOrderedLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.DateField;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HasChildMeasurementHint.ChildMeasurementHint;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;

public class TableChildMeasurementHint extends AbstractTestUI {

    private HorizontalLayout buttonLayout = new HorizontalLayout();
    private HorizontalLayout layout;
    private Table table1, table2, table3;

    @Override
    public void setup(VaadinRequest request) {
        initMain();
    }

    protected void initMain() {
        ((AbstractOrderedLayout) getContent()).setMargin(false);
        layout = new HorizontalLayout();
        layout.setSpacing(true);
        layout.setMargin(false);
        layout.setSizeFull();
        addComponent(buttonLayout);
        addComponent(layout);

        table1 = createTable();
        table1.setSizeFull();
        table1.setChildMeasurementHint(ChildMeasurementHint.MEASURE_ALWAYS);

        table2 = createTable();
        table2.setSizeFull();
        table2.setChildMeasurementHint(ChildMeasurementHint.MEASURE_IF_NEEDED);

        table3 = createTable();
        table3.setSizeFull();
        table3.setChildMeasurementHint(ChildMeasurementHint.MEASURE_NEVER);

        buttonLayout.addComponent(new Button("Show table1",
                new ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        layout.addComponent(table1);
                        table1.focus();
                    }
                }));
        buttonLayout.addComponent(new Button("Show table2",
                new ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        layout.removeComponent(table1);
                        layout.addComponent(table2);
                        table2.focus();
                    }
                }));
        buttonLayout.addComponent(new Button("Show table3",
                new ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        layout.removeComponent(table2);
                        layout.addComponent(table3);
                        table3.focus();
                    }
                }));

    }

    protected Table createTable() {
        Table table = new Table();
        table.setSelectable(true);
        table.setPageLength(39);

        for (int i = 0; i < 5; i++) {
            table.addContainerProperty("First_Name" + i, String.class, null);
            table.addContainerProperty("Last Name" + i, String.class, null);
            table.addContainerProperty("Year" + i, Integer.class, null);
        }

        /* Add a few items in the table. */
        int j = 0;
        for (int i = 0; i < 2; i++) {
            table.addItem(
                    makeRow(new Object[] { "Nicolaus" + i, "Copernicus", 1473 },
                            5), j++);
            table.addItem(
                    makeRow(new Object[] { "Tycho" + i, "Brahe", 1546 }, 5),
                    j++);
            table.addItem(
                    makeRow(new Object[] { "Giordano" + i, "Bruno", 1548 }, 5),
                    j++);
            table.addItem(
                    makeRow(new Object[] { "Galileo" + i, "Galilei", 1564 }, 5),
                    j++);
            table.addItem(
                    makeRow(new Object[] { "Johannes" + i, "Kepler", 1571 }, 5),
                    j++);
            table.addItem(
                    makeRow(new Object[] { "Isaac" + i, "Newton", 1643 }, 5),
                    j++);
        }

        table.addGeneratedColumn("First_Name" + 0, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                ComboBox b = new ComboBox("ComboBox");
                b.setWidthUndefined();
                return b;
            }
        });

        table.addGeneratedColumn("First_Name" + 1, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                GridLayout b = new GridLayout();
                b.addComponents(new Label("l1"), new Button("b"), new Label(
                        "l2"));
                b.setWidthUndefined();
                return b;
            }
        });

        table.addGeneratedColumn("First_Name" + 2, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                Button b = new Button("Button");
                b.setWidthUndefined();
                return b;
            }
        });

        table.addGeneratedColumn("First_Name" + 3, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                TextField b = new TextField("Textfield");
                b.setWidthUndefined();
                return b;
            }
        });

        table.addGeneratedColumn("First_Name" + 4, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                DateField b = new DateField("DateField");
                b.setWidthUndefined();
                return b;
            }
        });

        table.addGeneratedColumn("First_Name" + 5, new Table.ColumnGenerator() {
            @Override
            public Object generateCell(Table components, Object o, Object o2) {
                Label b = new Label("Label");
                b.setWidthUndefined();
                return b;
            }
        });

        return table;
    }

    protected Object[] makeRow(Object[] data, int c) {
        Object[] row = new Object[c * data.length];
        for (int j = 0; j < c; j++) {
            int x = 0;
            for (Object value : data) {
                row[j * data.length + x] = value;
                x++;
            }
        }

        return row;
    }
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.placement;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.resourcemanager.placement.UserGroupMappingPlacementRule.QueueMapping.MappingType;

import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.AutoCreatedLeafQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerContext;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerQueueManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ManagedParentQueue;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.DOT;

public class UserGroupMappingPlacementRule extends PlacementRule {
  private static final Log LOG = LogFactory
      .getLog(UserGroupMappingPlacementRule.class);

  public static final String CURRENT_USER_MAPPING = "%user";

  public static final String PRIMARY_GROUP_MAPPING = "%primary_group";

  private boolean overrideWithQueueMappings = false;
  private List<QueueMapping> mappings = null;
  private Groups groups;

  @Private
  public static class QueueMapping {

    public enum MappingType {

      USER("u"), GROUP("g");
      private final String type;

      private MappingType(String type) {
        this.type = type;
      }

      public String toString() {
        return type;
      }

    };

    MappingType type;
    String source;
    String queue;
    String parentQueue;

    public final static String DELIMITER = ":";

    public QueueMapping(MappingType type, String source, String queue) {
      this.type = type;
      this.source = source;
      this.queue = queue;
      this.parentQueue = null;
    }

    public QueueMapping(MappingType type, String source,
        String queue, String parentQueue) {
      this.type = type;
      this.source = source;
      this.queue = queue;
      this.parentQueue = parentQueue;
    }

    public String getQueue() {
      return queue;
    }

    public String getParentQueue() {
      return parentQueue;
    }

    public boolean hasParentQueue() {
      return parentQueue != null;
    }

    public MappingType getType() {
      return type;
    }

    public String getSource() {
      return source;
    }

    @Override
    public int hashCode() {
      return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
      if (obj instanceof QueueMapping) {
        QueueMapping other = (QueueMapping) obj;
        return (other.type.equals(type) &&
            other.source.equals(source) &&
            other.queue.equals(queue));
      } else {
        return false;
      }
    }

    public String toString() {
      return type.toString() + DELIMITER + source + DELIMITER +
        (parentQueue != null ?
        parentQueue + "." + queue :
        queue);
    }
  }

  public UserGroupMappingPlacementRule(){
    this(false, null, null);
  }

  public UserGroupMappingPlacementRule(boolean overrideWithQueueMappings,
      List<QueueMapping> newMappings, Groups groups) {
    this.mappings = newMappings;
    this.overrideWithQueueMappings = overrideWithQueueMappings;
    this.groups = groups;
  }

  private ApplicationPlacementContext getPlacementForUser(String user)
      throws IOException {
    for (QueueMapping mapping : mappings) {
      if (mapping.type == MappingType.USER) {
        if (mapping.source.equals(CURRENT_USER_MAPPING)) {
          if (mapping.queue.equals(CURRENT_USER_MAPPING)) {
            return getPlacementContext(mapping, user);
          } else if (mapping.queue.equals(PRIMARY_GROUP_MAPPING)) {
            return getPlacementContext(mapping, groups.getGroups(user).get(0));
          } else {
            return getPlacementContext(mapping);
          }
        }
        if (user.equals(mapping.source)) {
          return getPlacementContext(mapping);
        }
      }
      if (mapping.type == MappingType.GROUP) {
        for (String userGroups : groups.getGroups(user)) {
          if (userGroups.equals(mapping.source)) {
            if (mapping.queue.equals(CURRENT_USER_MAPPING)) {
              return getPlacementContext(mapping, user);
            }
            return getPlacementContext(mapping);
          }
        }
      }
    }
    return null;
  }

  @Override
  public ApplicationPlacementContext getPlacementForApp(
      ApplicationSubmissionContext asc, String user)
      throws YarnException {
    String queueName = asc.getQueue();
    ApplicationId applicationId = asc.getApplicationId();
    if (mappings != null && mappings.size() > 0) {
      try {
        ApplicationPlacementContext mappedQueue = getPlacementForUser(user);
        if (mappedQueue != null) {
          // We have a mapping, should we use it?
          if (queueName.equals(YarnConfiguration.DEFAULT_QUEUE_NAME)
              //queueName will be same as mapped queue name in case of recovery
              || queueName.equals(mappedQueue.getQueue())
              || overrideWithQueueMappings) {
            LOG.info("Application " + applicationId + " user " + user
                + " mapping [" + queueName + "] to [" + mappedQueue
                + "] override " + overrideWithQueueMappings);
            return mappedQueue;
          }
        }
      } catch (IOException ioex) {
        String message = "Failed to submit application " + applicationId +
            " submitted by user " + user + " reason: " + ioex.getMessage();
        throw new YarnException(message);
      }
    }
    return null;
  }

  private ApplicationPlacementContext getPlacementContext(
      QueueMapping mapping) {
    return getPlacementContext(mapping, mapping.getQueue());
  }

  private ApplicationPlacementContext getPlacementContext(QueueMapping mapping,
      String leafQueueName) {
    if (!StringUtils.isEmpty(mapping.parentQueue)) {
      return new ApplicationPlacementContext(leafQueueName,
          mapping.getParentQueue());
    } else{
      return new ApplicationPlacementContext(leafQueueName);
    }
  }

  @VisibleForTesting
  @Override
  public boolean initialize(CapacitySchedulerContext schedulerContext)
      throws IOException {
    CapacitySchedulerConfiguration conf = schedulerContext.getConfiguration();
    boolean overrideWithQueueMappings = conf.getOverrideWithQueueMappings();
    LOG.info(
        "Initialized queue mappings, override: " + overrideWithQueueMappings);

    List<QueueMapping> queueMappings = conf.getQueueMappings();

    // Get new user/group mappings
    List<QueueMapping> newMappings = new ArrayList<>();

    CapacitySchedulerQueueManager queueManager =
        schedulerContext.getCapacitySchedulerQueueManager();

    // check if mappings refer to valid queues
    for (QueueMapping mapping : queueMappings) {

      QueuePath queuePath = extractQueuePath(mapping.getQueue());
      if (isStaticQueueMapping(mapping)) {
        //Try getting queue by its leaf queue name
        // without splitting into parent/leaf queues
        CSQueue queue = queueManager.getQueue(mapping.getQueue());
        if (ifQueueDoesNotExist(queue)) {
          //Try getting the queue by extracting leaf and parent queue names
          //Assuming its a potential auto created leaf queue
          queue = queueManager.getQueue(queuePath.getLeafQueue());

          if (ifQueueDoesNotExist(queue)) {
            //if leaf queue does not exist,
            // this could be a potential auto created leaf queue
            //validate if parent queue is specified,
            // then it should exist and
            // be an instance of AutoCreateEnabledParentQueue
            QueueMapping newMapping = validateAndGetAutoCreatedQueueMapping(
                queueManager, mapping, queuePath);
            if (newMapping == null) {
              throw new IOException(
                  "mapping contains invalid or non-leaf queue " + mapping
                      .getQueue());
            }
            newMappings.add(newMapping);
          } else{
            QueueMapping newMapping = validateAndGetQueueMapping(queueManager,
                queue, mapping, queuePath);
            newMappings.add(newMapping);
          }
        } else{
          // if queue exists, validate
          //   if its an instance of leaf queue
          //   if its an instance of auto created leaf queue,
          // then extract parent queue name and update queue mapping
          QueueMapping newMapping = validateAndGetQueueMapping(queueManager,
              queue, mapping, queuePath);
          newMappings.add(newMapping);
        }
      } else{
        //If it is a dynamic queue mapping,
        // we can safely assume leaf queue name does not have '.' in it
        // validate
        // if parent queue is specified, then
        //  parent queue exists and an instance of AutoCreateEnabledParentQueue
        //
        QueueMapping newMapping = validateAndGetAutoCreatedQueueMapping(
            queueManager, mapping, queuePath);
        if (newMapping != null) {
          newMappings.add(newMapping);
        } else{
          newMappings.add(mapping);
        }
      }
    }

    // initialize groups if mappings are present
    if (newMappings.size() > 0) {
      Groups groups = new Groups(conf);
      this.mappings = newMappings;
      this.groups = groups;
      this.overrideWithQueueMappings = overrideWithQueueMappings;
      return true;
    }
    return false;
  }

  private static QueueMapping validateAndGetQueueMapping(
      CapacitySchedulerQueueManager queueManager, CSQueue queue,
      QueueMapping mapping, QueuePath queuePath) throws IOException {
    if (!(queue instanceof LeafQueue)) {
      throw new IOException(
          "mapping contains invalid or non-leaf queue : " + mapping.getQueue());
    }

    if (queue instanceof AutoCreatedLeafQueue && queue
        .getParent() instanceof ManagedParentQueue) {

      QueueMapping newMapping = validateAndGetAutoCreatedQueueMapping(
          queueManager, mapping, queuePath);
      if (newMapping == null) {
        throw new IOException(
            "mapping contains invalid or non-leaf queue " + mapping.getQueue());
      }
      return newMapping;
    }
    return mapping;
  }

  private static boolean ifQueueDoesNotExist(CSQueue queue) {
    return queue == null;
  }

  private static QueueMapping validateAndGetAutoCreatedQueueMapping(
      CapacitySchedulerQueueManager queueManager, QueueMapping mapping,
      QueuePath queuePath) throws IOException {
    if (queuePath.hasParentQueue()) {
      //if parent queue is specified,
      // then it should exist and be an instance of ManagedParentQueue
      validateParentQueue(queueManager.getQueue(queuePath.getParentQueue()),
          queuePath.getParentQueue(), queuePath.getLeafQueue());
      return new QueueMapping(mapping.getType(), mapping.getSource(),
          queuePath.getLeafQueue(), queuePath.getParentQueue());
    }

    return null;
  }

  private static boolean isStaticQueueMapping(QueueMapping mapping) {
    return !mapping.getQueue().contains(
        UserGroupMappingPlacementRule.CURRENT_USER_MAPPING) && !mapping
        .getQueue().contains(
            UserGroupMappingPlacementRule.PRIMARY_GROUP_MAPPING);
  }

  private static class QueuePath {

    public String parentQueue;
    public String leafQueue;

    public QueuePath(final String leafQueue) {
      this.leafQueue = leafQueue;
    }

    public QueuePath(final String parentQueue, final String leafQueue) {
      this.parentQueue = parentQueue;
      this.leafQueue = leafQueue;
    }

    public String getParentQueue() {
      return parentQueue;
    }

    public String getLeafQueue() {
      return leafQueue;
    }

    public boolean hasParentQueue() {
      return parentQueue != null;
    }

    @Override
    public String toString() {
      return parentQueue + DOT + leafQueue;
    }
  }

  private static QueuePath extractQueuePath(String queueName)
      throws IOException {
    int parentQueueNameEndIndex = queueName.lastIndexOf(DOT);

    if (parentQueueNameEndIndex > -1) {
      final String parentQueue = queueName.substring(0, parentQueueNameEndIndex)
          .trim();
      final String leafQueue = queueName.substring(parentQueueNameEndIndex + 1)
          .trim();
      return new QueuePath(parentQueue, leafQueue);
    }

    return new QueuePath(queueName);
  }

  private static void validateParentQueue(CSQueue parentQueue,
      String parentQueueName, String leafQueueName) throws IOException {
    if (parentQueue == null) {
      throw new IOException(
          "mapping contains invalid or non-leaf queue [" + leafQueueName
              + "] and invalid parent queue [" + parentQueueName + "]");
    } else if (!(parentQueue instanceof ManagedParentQueue)) {
      throw new IOException("mapping contains leaf queue [" + leafQueueName
          + "] and invalid parent queue which "
          + "does not have auto creation of leaf queues enabled ["
          + parentQueueName + "]");
    } else if (!parentQueue.getQueueName().equals(parentQueueName)) {
      throw new IOException(
          "mapping contains invalid or non-leaf queue [" + leafQueueName
              + "] and invalid parent queue "
              + "which does not match existing leaf queue's parent : ["
              + parentQueueName + "] does not match [ " + parentQueue
              .getQueueName() + "]");
    }
  }

  @VisibleForTesting
  public List<QueueMapping> getQueueMappings() {
    return mappings;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.organicdesign.fp;

import org.junit.Test;
import org.organicdesign.fp.collections.ImList;
import org.organicdesign.fp.collections.ImMap;
import org.organicdesign.fp.collections.ImSet;
import org.organicdesign.fp.collections.ImSortedMap;
import org.organicdesign.fp.collections.ImSortedSet;
import org.organicdesign.fp.collections.PersistentHashMap;
import org.organicdesign.fp.collections.PersistentHashSet;
import org.organicdesign.fp.collections.PersistentTreeMap;
import org.organicdesign.fp.collections.PersistentTreeSet;
import org.organicdesign.fp.collections.PersistentVector;
import org.organicdesign.fp.function.Fn1;
import org.organicdesign.fp.tuple.Tuple2;
import org.organicdesign.fp.tuple.Tuple3;
import org.organicdesign.fp.xform.Xform;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.organicdesign.fp.StaticImports.*;

public class StaticImportsTest {

    @Test public void mutableMapTest() {
        assertEquals(Collections.emptyMap(), mutableMap());
        assertEquals(Collections.singletonMap(35, "Thirty Five"),
                     mutableMap(tup(35, "Thirty Five")));

        Map<String,Integer> control = new HashMap<>();
        control.put("one", 1);
        control.put("two", 2);
        control.put("three", 3);
        assertEquals(control,
                     mutableMap(tup("one", 1),
                                tup("two", 2),
                                tup("three", 3)));
    }

    @Test public void mutableSetTest() {
        assertEquals(Collections.emptySet(), mutableSet());
        assertEquals(Collections.singleton("Thirty Five"),
                     mutableSet("Thirty Five"));

        Set<Integer> control = new HashSet<>();
        control.add(1);
        control.add(2);
        control.add(3);
        assertEquals(control,
                     mutableSet(1, 2, 3));
    }

    @Test public void mutableVecTest() {
        assertEquals(Collections.emptyList(), mutableVec());
        assertEquals(Collections.singletonList("Thirty Five"),
                     mutableVec("Thirty Five"));

        List<Integer> control = new ArrayList<>();
        control.add(1);
        control.add(2);
        control.add(3);
        assertEquals(control,
                     mutableVec(1, 2, 3));
    }

    @Test (expected = UnsupportedOperationException.class)
    public void instantiationEx() throws Throwable {
        Class<StaticImports> c = StaticImports.class;
        Constructor defCons = c.getDeclaredConstructor();
        defCons.setAccessible(true);
        try {
            // This catches the exception and wraps it in an InvocationTargetException
            defCons.newInstance();
        } catch (InvocationTargetException ite) {
            // Here we throw the original exception.
            throw ite.getTargetException();
        }
    }

    @SuppressWarnings({"NullArgumentToVariableArgMethod", "RedundantArrayCreation", "unchecked"})
    @Test public void testMap() {
        assertEquals(PersistentHashMap.EMPTY, map());
        assertEquals(PersistentHashMap.EMPTY, map((Map.Entry[]) null));
        assertEquals(PersistentHashMap.EMPTY, map(new Map.Entry[0]));
        ImMap<String,Integer> phm = PersistentHashMap.<String,Integer>empty()
                .assoc("Hi", 43);
        assertEquals(phm, map(tup("Hi", 43)));
    }

    @SuppressWarnings({"NullArgumentToVariableArgMethod", "RedundantArrayCreation"})
    @Test public void testSet() {
        assertEquals(PersistentHashSet.EMPTY, set());
        assertEquals(PersistentHashSet.EMPTY, set((Map.Entry[]) null));
        assertEquals(PersistentHashSet.EMPTY, set(new Object[0]));
        ImSet<String> phm = PersistentHashSet.<String>empty()
                .put("Hi");
        assertEquals(phm, set("Hi"));
    }

    @Test public void testSortedMap() {
        ImList<Map.Entry<String,Integer>> ls = PersistentVector.empty();
        ls = ls.append(tup("Hi", 1))
               .append(Tuple2.of("Bye", -99))
               .append(Tuple2.of("hi", 33))
               .append(tup("bye", -9999));
        ImSortedMap<String,Integer> refMap =
                PersistentTreeMap.ofComp(String.CASE_INSENSITIVE_ORDER, ls);
        ImSortedMap<String,Integer> testMap = sortedMap(String.CASE_INSENSITIVE_ORDER, ls);
        assertEquals(refMap, testMap);
        // Because equals is meant to be compatible with an unsorted map, the comparator is not
        // considered.  Check the comparators to see that they are truly identical.
        assertEquals(refMap.comparator(), testMap.comparator());

        // Try using the default comparator.
        refMap = PersistentTreeMap.of(ls);
        testMap = sortedMap(ls);

        assertEquals(refMap, testMap);
        // Because equals is meant to be compatible with an unsorted map, the comparator is not
        // considered.  Check the comparators to see that they are truly identical.
        assertEquals(refMap.comparator(), testMap.comparator());
    }

    @Test public void testSortedSet() {
        ImList<String> ls = PersistentVector.empty();
        ls = ls.append("Hi")
               .append("Bye")
               .append("hi")
               .append("bye");
        ImSortedSet<String> refSet =
                PersistentTreeSet.ofComp(String.CASE_INSENSITIVE_ORDER, ls);
        ImSortedSet<String> testSet = sortedSet(String.CASE_INSENSITIVE_ORDER, ls);
        assertEquals(refSet, testSet);
        // Because equals is meant to be compatible with an unsorted set, the comparator is not
        // considered.  Check the comparators to see that they are truly identical.
        assertEquals(refSet.comparator(), testSet.comparator());

        // Try using the default comparator.
        refSet = PersistentTreeSet.of(ls);
        testSet = sortedSet(ls);

        assertEquals(refSet, testSet);
        // Because equals is meant to be compatible with an unsorted set, the comparator is not
        // considered.  Check the comparators to see that they are truly identical.
        assertEquals(refSet.comparator(), testSet.comparator());
    }

    @Test public void testTup() {
        assertEquals(Tuple2.of("Hello", -32), tup("Hello", -32));
        assertEquals(Tuple3.of("Hello", -32, 9.5), tup("Hello", -32, 9.5));
    }

    @SuppressWarnings({"NullArgumentToVariableArgMethod", "RedundantArrayCreation"})
    @Test public void testVec() {
        assertEquals(PersistentVector.EMPTY, vec());
        assertEquals(PersistentVector.EMPTY, vec((Map.Entry[]) null));
        assertEquals(PersistentVector.EMPTY, vec(new Map.Entry[0]));
        ImList<String> ls = PersistentVector.<String>empty()
                .append("Hi");
        assertEquals(ls, vec("Hi"));

        Random r = new Random();
        boolean showEditable = r.nextBoolean();
        boolean showDeleted = r.nextBoolean();

        // This just shows whether Objects::nonNull generates a warning in your editor.
        vec(showEditable ? tup("showEditable", "1") : null,
            showDeleted ? tup("showDeleted", "1") : null)
                .filter(Objects::nonNull)
                .toImList();
    }

    @Test public void testXform() {
        assertEquals(Xform.of(Arrays.asList(1,2,3)), xform(Arrays.asList(1,2,3)));
    }

    @Test public void xformArrayTest() {
        assertEquals(Collections.emptyList(), xformArray().toImList());
        assertEquals(Collections.singletonList("Thirty Five"),
                     xformArray("Thirty Five").toImList());

        List<Integer> control = new ArrayList<>();
        control.add(1);
        control.add(2);
        control.add(3);
        assertEquals(control,
                     xformArray(1, 2, 3).toImList());
    }

    @Test public void testXformChars() {
        assertEquals(vec('H', 'e', 'l', 'l', 'o'), xformChars("Hello").toImList());
    }
}


text:
Login into the [Azure portal](https://portal.azure.com) to deploy and manage your Azure resources.
First of all, we need a new Resource Group. A resource group is a container that holds related resources for an application.
The resource group could include all of the resources for an application, or only those resources that are logically grouped together. You can decide how you want to allocate resources to resource groups based on what makes the most sense for your organization.

To create an empty resource group, select **New**, **Management**, and **Resource Group**.

![create new resource group](./images/01-resourcegroup-01.png)

Give it a name and location (West Europe), select a subscription and press create.

![create new resource group](./images/01-resourcegroup-02.png)

# 2. Create an [App Service Plan](https://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/)

An App Service plan represents a set of features and capacity that you can share across multiple apps in Azure App Service, including Web Apps, Mobile Apps, Logic Apps or API Apps. These plans support 5 pricing tiers (Free, Shared, Basic, Standard and Premium) where each tier has its own capabilities and capacity. Apps in the same subscription and geographic location can share a plan. All the apps sharing a plan can leverage all the capabilities and features defined by the plan's tier. All apps associated with a given plan run on the resources defined by the plan. For example, if your plan is configured to use two "small" instances in the standard service tier, all apps associated with that plan will run on both instances and will have access to the standard service tier functionality. App Service plan instances on which apps are running on are fully managed and highly available.

To create a new App Service Plan, go to your resource group and click **Add**. Then search for **App Service Plan**, select the item and press create. This ensures that the App Service Plan is automatically added to your resource group.

![create an app service plan from a resource group](./images/02-appserviceplan-03.png)

As an alternative, you could start with the **New** button in the portal navigation bar and set the resource group later.

![create an app service plan](./images/02-appserviceplan-01.png)

Give it a name, a subscription, select the Resource Group created before and a location (West Europe).
Finally, select a pricing tier and click create. For the Trivadis Azure Bootcamp App, the [F1 Free Pricing Tier](https://azure.microsoft.com/en-us/pricing/details/app-service/) fits perfectly.

![create an app service plan](./images/02-appserviceplan-02.png)

# 3. Create a [Web App](https://azure.microsoft.com/en-us/documentation/articles/app-service-web-overview/)

Azure App Service Web Apps is a fully managed platform that enables you to build, deploy and scale enterprise-grade web apps in seconds. Focus on your application code,
and let Azure take care of the infrastructure to scale and securely run it for you.

For our frontend we need to create a new web app by selecting **New**, **Web + Mobile**, then **Web App** (Alternatively, select **Add** in your resource group).

![create web app](./images/03-webapp-01.png)

Give it a name, a subscription, select the Resource Group and the App Service plan created before and click create.

![create web app](./images/03-webapp-02.png)

As soon the application is created, open your Web App in the portal and hit the **browse** button.

 ![create web app](./images/03-webapp-03.png)

You should see the Azure screen that confirms the successful creation of your app.

Alternatively navigate your browser to:  **your app name**.azurewebsites.net.  Ex. ** http://azurebootcamp-web.azurewebsites.net/ **

Congratulations. Your Azure Web App is LIVE!

# 4. Create an [API App](https://azure.microsoft.com/en-us/documentation/articles/app-service-api-apps-why-best-platform/)

An Azure API App is an ASP.NET Web API App that is hosted in Azure and provides a REST-based interface. The interface is specified in a Swagger (http://swagger.io/) document. Swagger is a standardized language used to describe REST APIs (think WSDL for REST).  An API app can take advantage of features offered by Web Apps and Mobile Apps. The reverse is also true: if you use a web app or mobile app to host an API, it can take advantage of API Apps features such as Swagger metadata for client code generation and CORS for cross-domain browser access. The only difference between the three app types (API, web, mobile) is the **name and icon** used for them in the Azure portal.

For our backend we need to create a new api app by selecting **New**, **Web + Mobile**, then **API App**.

![create web app](./images/04-apiapp-01.png)

Give it a name, a subscription, select the Resource Group and the App Service plan created before and press create.

![create web app](./images/04-apiapp-02.png)

# 5. Get the Trivadis Azure Bootcamp sample application

The Azure Bootcamp sample Application consists of an API- and Web-Application. The frontend is built using [AngularJS](https://angularjs.org/), [Angular Material](https://material.angularjs.org)
and [SignalR](http://signalr.net/) with [TypeScript](https://www.typescriptlang.org/), while the backend is just a simple [ASP.NET Web API](http://www.asp.net/web-api).

The sample application uses the following Azure Services:

1. [Storage](https://azure.microsoft.com/en-us/services/storage/)
2. [Web Apps](https://azure.microsoft.com/en-us/services/app-service/web/)
3. [API Apps](https://azure.microsoft.com/en-us/services/app-service/api/)
4. [Azure Active Directory B2C](https://azure.microsoft.com/en-us/services/active-directory-b2c/)

The code for the Azure Bootcamp App [is maintained on GitHub](https://github.com/Trivadis/AzureDeveloperBootcamp).
You can clone the application by executing the following command:

```
git clone --branch lab https://github.com/Trivadis/AzureDeveloperBootcamp
```

Open **Trivadis.AzureBootcamp.sln** solution in Visual Studio, got to [Package Manager Console](https://docs.nuget.org/consume/package-manager-console)
by selecting **View** -> **Other Windows** -> **Package Manager Console** and execute a [NuGet Package Restore](https://docs.nuget.org/consume/package-restore)
by clicking the **Restore**-Button

![nuget package restore](./images/05-vs-01.png)

# 5.1 Run Azure Bootcamp in Visual Studio

 The Trivadis Azure Bootcamp App also runs locally in Visual Studio. To start the app in your local environment, be sure both
 **Trivadis.AzureBootcamp.WebApi** and **Trivadis.AzureBootcamp.WebApp** are selected as startup. Right-Click the **Trivadis.AzureBootcamp Solution**-Node and select **Set StartUp Projects...**

![nuget package restore](./images/05-vs-02.png)

Now press F5.

Note : The first time you start the application,
Visual Studio asks you to install a self-signed SSL Certifcate to use https.
You must accept both messages, otherwise the application won't work properly.

![iis certification](./images/05-iis-01.png)
![iis certification](./images/05-iis-02.png)

The applications should start in two browser Windows. Go to the login screen, press **Login**, enter a name and hit **Login**. You should end up in the chat room.

![start solution](./images/05-vs-03.png)

In order to verify that the API App is running correctly, go to the other browser window and navigate to: https://localhost:44324/api/admin/users. You should receive a json response that contains your user details.

![verify api app](./images/05-vs-04.png)

Now that the apps are running, lets deploy to the cloud!

# 6. Publish Azure Bootcamp API App

First of all, we need to publish our backend **(Trivadis.AzureBootcamp.WebApi)** to azure.
The backend is responsible for the communication between the clients **(Trivadis.AzureBootcamp.WebApp)**.
To publish the project to an API App, simply right-click the **Trivadis.AzureBootcamp.WebApi** project then select **Publish**.

![publish api app](./images/06-publish-01.png)

Select Microsoft Azure App Service and click Next.

![publish api app](./images/06-publish-02.png)

Select your App API created before.

![publish api app](./images/06-publish-03.png)

Click Ok and Next.

![publish api app](./images/06-publish-04.png)

Select the **CloudDebug** Configuration. Finally publish your API App by clicking the **Publish** button.

![publish api app](./images/06-publish-05.png)

When publishing has finished successfully, open a browser and type the URL of your API into addressbar to ensure your endpoint is up and running. Navigate to http://myname.azurewebsites.net/api/admin/users. You should get an empty JSON array as a response.

## 6.1 Publish Azure Bootcamp Web App

Before we can publish the Web App, we must configure our API Endpoint.
In Visual Studio open the file **Web.CloudDebug.config** within the **Trivadis.AzureBootcamp.WebApp** project and
set the value of the **ApiHost** and **ApiRoot** property.

```
  <appSettings>
    <add key="ApiHost" value="https://YOUR-API-APPSERVICE.azurewebsites.net"  xdt:Transform="Replace" xdt:Locator="Match(key)" />
    <add key="ApiRoot" value="https://YOUR-API-APPSERVICE.azurewebsites.net/api/"  xdt:Transform="Replace" xdt:Locator="Match(key)" />
  </appSettings>
```

Now its time to publish the frontend Web App. Repeat all steps described under chapter 6, but this time,
select the **Trivadis.AzureBootcamp.WebApp** Project to publish. Be sure you are using the **CloudDebug** Configuration again.

In the App Service dialog, ensure you have selected the Web App - Service.

![publish web app](./images/06-publish-06.png)

After publishing has succeeded, you shoulb be able to login into Trivadis Azure Bootcamp App, using your Web App's URL. Click on 'Login' and choose a name

![login](./images/06-publish-07.png)

Congratulations, you have successfully completed Lab 1.


text:
<?php

class DB
{

    const CHARSET_TYPE = 'UTF-8';

    private $_config;

    /**
     * The constructor of the class receive an array containing the following indexes:
     *
     * 'host': database the register the emails
     * 'port': the port of the database
     * 'user': the username of the database
     * 'password': the password of the database
     * 'dbname': the name of the database
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $keys1 = array(
            'host',
            'port',
            'user',
            'password',
            'dbname'
        );

        $this->_config = array_fill_keys($keys1, 'value');

        $keys2 = array_keys($config); // the user provided keys
        $diff = array_merge(array_diff_key($keys1, $keys2), array_diff_key($keys2, $keys1));

        if (! empty($diff)) {
            throw new \InvalidArgumentException("The config array in constructor is not complete (see the documentation of the constructor)");
        }

        // If reach here, everything is fine
        $this->_config = $config;
    }

    /**
     *
     * @var \PDO
     */
    protected $_pdoConnection;

    /**
     * Function to create (or retrieve) the current connection to the DB
     *
     * @throws Connection
     * @return \PDO
     */
    protected function getConnection()
    {
        if (empty($this->_pdoConnection)) {
            $result = $this->initConnection();

            if (is_string($result)) {
                throw new Connection($result);
            }

            // If reach here, everything was fine
            $this->_pdoConnection = $result;
        }

        return $this->_pdoConnection;
    }

    public function setConnection(\PDO $conn)
    {
        $this->_pdoConnection = $conn;
    }

    /**
     * Process the emails that are stored in the datasource and send them
     */
    public function getTweets()
    {
        /**
         * TODO: Implement This
         */
        $conn = $this->getConnection();

        $stmt = $conn->query('
			SELECT raw
			FROM tweets
		');

        $data = $stmt->fetch();

        $results = array();

        foreach ($data as $value)
        {
            $results[] = unserialize($value);
        }

        return $results;
    }

    /**
     * Add an email to the queue to be processed by the cron job
     * Returns true on success or false on failure.
     *
     * This function doesn't work in transactional way, that must be implemented
     *
     * The params is replaced in the type text, with the placeholders '__?0__', '__?1__'
     *
     * @param string $email
     * @param int $type
     * @param unknown_type $params
     *
     * @throws \InvalidArgumentException
     *
     * @return bool
     */
    public function saveTweet($tweet)
    {
        // Preconditions
        if (empty($tweet)) {
            throw new \InvalidArgumentException("Error: Empty tweet cannot be saved");
        }

        $conn = $this->getConnection();

        $st = $conn->prepare('
            INSERT INTO tweets (date, texto, username, imageurl, raw)
            VALUES(:date, :texto, :username, :imageurl, :raw)
        ');

        return $st->execute(array(
            ':date' => gmdate('Y-m-d H:i:s', strtotime($tweet->created_at)),
            ':texto' => $tweet->text,
            ':username' => $tweet->user->name,
            ':imageurl' => $tweet->user->profile_image_url,
            ':raw' => serialize($tweet),
        ));
    }

    /**
     * Function to create the (initial) connection to MySQL Database
     *
     * @return void
     */
    protected function initConnection()
    {
        $dsn = 'mysql:host=' . $this->_config['host'] . ';port=' . $this->_config['port'] . ';dbname=' . $this->_config['dbname'];
        $username = $this->_config['user'];
        $password = $this->_config['password'];
        $options = array(
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
        );

        $result = false;

        try {
            $result = new \PDO($dsn, $username, $password, $options);
        } catch (\PDOException $e) {
            $result = $e->getMessage();
        }

        return $result;
    }
}


text:
#pragma once

#include <string>

#include "absl/types/span.h"
#include "tensorflow/compiler/tf2xla/xla_tensor/ir.h"
#include "tensorflow/compiler/xla/xla_client/device.h"

namespace swift_xla {
namespace ir {

class DumpUtil {
 public:
  static std::string ToDot(absl::Span<const Node* const> nodes);

  static std::string PostOrderToDot(absl::Span<const Node* const> post_order,
                                    absl::Span<const Node* const> roots);

  static std::string ToText(absl::Span<const Node* const> nodes);

  static std::string PostOrderToText(absl::Span<const Node* const> post_order,
                                     absl::Span<const Node* const> roots);

  static std::string ToHlo(absl::Span<const Value> values,
                           const Device& device);

  static std::string GetGraphChangeLog(absl::Span<const Node* const> roots);

  static std::string GetAnnotations(absl::Span<const Node* const> nodes);
};

}  // namespace ir
}  // namespace swift_xla


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

if (process.platform === "win32") {
	return setFileEolToCRLF(path.join(__dirname, '..', 'cli', 'index.js'));
}

function setFileEolToCRLF(filepath) {
	crlf.set(filepath, 'CRLF', (err, endingType) => {
		if (err) {
			console.log(`Error converting ${filepath} end of line to CRLF : `, err);
		} else {
			console.log(`${filepath} end of line successfully converted from ${endingType} to CRLF`);
		}
	});
}


text:
module Google
  module Cloud
    module OsConfig
      module V1
        # This API resource represents the available inventory data for a
        # Compute Engine virtual machine (VM) instance at a given point in time.
        #
        # You can use this API resource to determine the inventory data of your VM.
        #
        # For more information, see [Information provided by OS inventory
        # management](https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected).
        # @!attribute [r] name
        #   @return [::String]
        #     Output only. The `Inventory` API resource name.
        #
        #     Format:
        #     `projects/{project_number}/locations/{location}/instances/{instance_id}/inventory`
        # @!attribute [rw] os_info
        #   @return [::Google::Cloud::OsConfig::V1::Inventory::OsInfo]
        #     Base level operating system information for the VM.
        # @!attribute [rw] items
        #   @return [::Google::Protobuf::Map{::String => ::Google::Cloud::OsConfig::V1::Inventory::Item}]
        #     Inventory items related to the VM keyed by an opaque unique identifier for
        #     each inventory item.  The identifier is unique to each distinct and
        #     addressable inventory item and will change, when there is a new package
        #     version.
        # @!attribute [r] update_time
        #   @return [::Google::Protobuf::Timestamp]
        #     Output only. Timestamp of the last reported inventory for the VM.
        class Inventory
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods

          # Operating system information for the VM.
          # @!attribute [rw] hostname
          #   @return [::String]
          #     The VM hostname.
          # @!attribute [rw] long_name
          #   @return [::String]
          #     The operating system long name.
          #     For example 'Debian GNU/Linux 9' or 'Microsoft Window Server 2019
          #     Datacenter'.
          # @!attribute [rw] short_name
          #   @return [::String]
          #     The operating system short name.
          #     For example, 'windows' or 'debian'.
          # @!attribute [rw] version
          #   @return [::String]
          #     The version of the operating system.
          # @!attribute [rw] architecture
          #   @return [::String]
          #     The system architecture of the operating system.
          # @!attribute [rw] kernel_version
          #   @return [::String]
          #     The kernel version of the operating system.
          # @!attribute [rw] kernel_release
          #   @return [::String]
          #     The kernel release of the operating system.
          # @!attribute [rw] osconfig_agent_version
          #   @return [::String]
          #     The current version of the OS Config agent running on the VM.
          class OsInfo
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # A single piece of inventory on a VM.
          # @!attribute [rw] id
          #   @return [::String]
          #     Identifier for this item, unique across items for this VM.
          # @!attribute [rw] origin_type
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::Item::OriginType]
          #     The origin of this inventory item.
          # @!attribute [rw] create_time
          #   @return [::Google::Protobuf::Timestamp]
          #     When this inventory item was first detected.
          # @!attribute [rw] update_time
          #   @return [::Google::Protobuf::Timestamp]
          #     When this inventory item was last modified.
          # @!attribute [rw] type
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::Item::Type]
          #     The specific type of inventory, correlating to its specific details.
          # @!attribute [rw] installed_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::SoftwarePackage]
          #     Software package present on the VM instance.
          # @!attribute [rw] available_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::SoftwarePackage]
          #     Software package available to be installed on the VM instance.
          class Item
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods

            # The origin of a specific inventory item.
            module OriginType
              # Invalid. An origin type must be specified.
              ORIGIN_TYPE_UNSPECIFIED = 0

              # This inventory item was discovered as the result of the agent
              # reporting inventory via the reporting API.
              INVENTORY_REPORT = 1
            end

            # The different types of inventory that are tracked on a VM.
            module Type
              # Invalid. An type must be specified.
              TYPE_UNSPECIFIED = 0

              # This represents a package that is installed on the VM.
              INSTALLED_PACKAGE = 1

              # This represents an update that is available for a package.
              AVAILABLE_PACKAGE = 2
            end
          end

          # Software package information of the operating system.
          # @!attribute [rw] yum_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::VersionedPackage]
          #     Yum package info.
          #     For details about the yum package manager, see
          #     https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-yum.
          # @!attribute [rw] apt_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::VersionedPackage]
          #     Details of an APT package.
          #     For details about the apt package manager, see
          #     https://wiki.debian.org/Apt.
          # @!attribute [rw] zypper_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::VersionedPackage]
          #     Details of a Zypper package.
          #     For details about the Zypper package manager, see
          #     https://en.opensuse.org/SDB:Zypper_manual.
          # @!attribute [rw] googet_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::VersionedPackage]
          #     Details of a Googet package.
          #      For details about the googet package manager, see
          #      https://github.com/google/googet.
          # @!attribute [rw] zypper_patch
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::ZypperPatch]
          #     Details of a Zypper patch.
          #     For details about the Zypper package manager, see
          #     https://en.opensuse.org/SDB:Zypper_manual.
          # @!attribute [rw] wua_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::WindowsUpdatePackage]
          #     Details of a Windows Update package.
          #     See https://docs.microsoft.com/en-us/windows/win32/api/_wua/ for
          #     information about Windows Update.
          # @!attribute [rw] qfe_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::WindowsQuickFixEngineeringPackage]
          #     Details of a Windows Quick Fix engineering package.
          #     See
          #     https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-quickfixengineering
          #     for info in Windows Quick Fix Engineering.
          # @!attribute [rw] cos_package
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::VersionedPackage]
          #     Details of a COS package.
          # @!attribute [rw] windows_application
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::WindowsApplication]
          #     Details of Windows Application.
          class SoftwarePackage
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # Information related to the a standard versioned package.  This includes
          # package info for APT, Yum, Zypper, and Googet package managers.
          # @!attribute [rw] package_name
          #   @return [::String]
          #     The name of the package.
          # @!attribute [rw] architecture
          #   @return [::String]
          #     The system architecture this package is intended for.
          # @!attribute [rw] version
          #   @return [::String]
          #     The version of the package.
          class VersionedPackage
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # Details related to a Zypper Patch.
          # @!attribute [rw] patch_name
          #   @return [::String]
          #     The name of the patch.
          # @!attribute [rw] category
          #   @return [::String]
          #     The category of the patch.
          # @!attribute [rw] severity
          #   @return [::String]
          #     The severity specified for this patch
          # @!attribute [rw] summary
          #   @return [::String]
          #     Any summary information provided about this patch.
          class ZypperPatch
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # Details related to a Windows Update package.
          # Field data and names are taken from Windows Update API IUpdate Interface:
          # https://docs.microsoft.com/en-us/windows/win32/api/_wua/
          # Descriptive fields like title, and description are localized based on
          # the locale of the VM being updated.
          # @!attribute [rw] title
          #   @return [::String]
          #     The localized title of the update package.
          # @!attribute [rw] description
          #   @return [::String]
          #     The localized description of the update package.
          # @!attribute [rw] categories
          #   @return [::Array<::Google::Cloud::OsConfig::V1::Inventory::WindowsUpdatePackage::WindowsUpdateCategory>]
          #     The categories that are associated with this update package.
          # @!attribute [rw] kb_article_ids
          #   @return [::Array<::String>]
          #     A collection of Microsoft Knowledge Base article IDs that are associated
          #     with the update package.
          # @!attribute [rw] support_url
          #   @return [::String]
          #     A hyperlink to the language-specific support information for the update.
          # @!attribute [rw] more_info_urls
          #   @return [::Array<::String>]
          #     A collection of URLs that provide more information about the update
          #     package.
          # @!attribute [rw] update_id
          #   @return [::String]
          #     Gets the identifier of an update package.  Stays the same across
          #     revisions.
          # @!attribute [rw] revision_number
          #   @return [::Integer]
          #     The revision number of this update package.
          # @!attribute [rw] last_deployment_change_time
          #   @return [::Google::Protobuf::Timestamp]
          #     The last published date of the update, in (UTC) date and time.
          class WindowsUpdatePackage
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods

            # Categories specified by the Windows Update.
            # @!attribute [rw] id
            #   @return [::String]
            #     The identifier of the windows update category.
            # @!attribute [rw] name
            #   @return [::String]
            #     The name of the windows update category.
            class WindowsUpdateCategory
              include ::Google::Protobuf::MessageExts
              extend ::Google::Protobuf::MessageExts::ClassMethods
            end
          end

          # Information related to a Quick Fix Engineering package.
          # Fields are taken from Windows QuickFixEngineering Interface and match
          # the source names:
          # https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-quickfixengineering
          # @!attribute [rw] caption
          #   @return [::String]
          #     A short textual description of the QFE update.
          # @!attribute [rw] description
          #   @return [::String]
          #     A textual description of the QFE update.
          # @!attribute [rw] hot_fix_id
          #   @return [::String]
          #     Unique identifier associated with a particular QFE update.
          # @!attribute [rw] install_time
          #   @return [::Google::Protobuf::Timestamp]
          #     Date that the QFE update was installed.  Mapped from installed_on field.
          class WindowsQuickFixEngineeringPackage
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # Contains information about a Windows application that is retrieved from the
          # Windows Registry. For more information about these fields, see:
          # https://docs.microsoft.com/en-us/windows/win32/msi/uninstall-registry-key
          # @!attribute [rw] display_name
          #   @return [::String]
          #     The name of the application or product.
          # @!attribute [rw] display_version
          #   @return [::String]
          #     The version of the product or application in string format.
          # @!attribute [rw] publisher
          #   @return [::String]
          #     The name of the manufacturer for the product or application.
          # @!attribute [rw] install_date
          #   @return [::Google::Type::Date]
          #     The last time this product received service. The value of this property
          #     is replaced each time a patch is applied or removed from the product or
          #     the command-line option is used to repair the product.
          # @!attribute [rw] help_link
          #   @return [::String]
          #     The internet address for technical support.
          class WindowsApplication
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end

          # @!attribute [rw] key
          #   @return [::String]
          # @!attribute [rw] value
          #   @return [::Google::Cloud::OsConfig::V1::Inventory::Item]
          class ItemsEntry
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end
        end

        # A request message for getting inventory data for the specified VM.
        # @!attribute [rw] name
        #   @return [::String]
        #     Required. API resource name for inventory resource.
        #
        #     Format:
        #     `projects/{project}/locations/{location}/instances/{instance}/inventory`
        #
        #     For `{project}`, either `project-number` or `project-id` can be provided.
        #     For `{instance}`, either Compute Engine  `instance-id` or `instance-name`
        #     can be provided.
        # @!attribute [rw] view
        #   @return [::Google::Cloud::OsConfig::V1::InventoryView]
        #     Inventory view indicating what information should be included in the
        #     inventory resource. If unspecified, the default view is BASIC.
        class GetInventoryRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # A request message for listing inventory data for all VMs in the specified
        # location.
        # @!attribute [rw] parent
        #   @return [::String]
        #     Required. The parent resource name.
        #
        #     Format: `projects/{project}/locations/{location}/instances/-`
        #
        #     For `{project}`, either `project-number` or `project-id` can be provided.
        # @!attribute [rw] view
        #   @return [::Google::Cloud::OsConfig::V1::InventoryView]
        #     Inventory view indicating what information should be included in the
        #     inventory resource. If unspecified, the default view is BASIC.
        # @!attribute [rw] page_size
        #   @return [::Integer]
        #     The maximum number of results to return.
        # @!attribute [rw] page_token
        #   @return [::String]
        #     A pagination token returned from a previous call to
        #     `ListInventories` that indicates where this listing
        #     should continue from.
        # @!attribute [rw] filter
        #   @return [::String]
        #     If provided, this field specifies the criteria that must be met by a
        #     `Inventory` API resource to be included in the response.
        class ListInventoriesRequest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # A response message for listing inventory data for all VMs in a specified
        # location.
        # @!attribute [rw] inventories
        #   @return [::Array<::Google::Cloud::OsConfig::V1::Inventory>]
        #     List of inventory objects.
        # @!attribute [rw] next_page_token
        #   @return [::String]
        #     The pagination token to retrieve the next page of inventory objects.
        class ListInventoriesResponse
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end

        # The view for inventory objects.
        module InventoryView
          # The default value.
          # The API defaults to the BASIC view.
          INVENTORY_VIEW_UNSPECIFIED = 0

          # Returns the basic inventory information that includes `os_info`.
          BASIC = 1

          # Returns all fields.
          FULL = 2
        end
      end
    end
  end
end


text:
import React, { Component } from 'react';
import { FormGroup, Input, Label } from 'reactstrap';
import classnames from 'classnames';
import castStringToElement from 'lib/castStringToElement';
import PropTypes from 'prop-types';

class OptionField extends Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);
  }

  /**
   * Fetches the properties for the field
   *
   * @returns {object} properties
   */
  getInputProps() {
    const classes = classnames({
      [this.props.className]: true,
      [this.props.extraClass]: true,
      'form-check': true,
      checked: this.props.value,
      disabled: this.props.readOnly,
      'option-field--disabled': this.props.readOnly || this.props.disabled,
    });

    return {
      id: this.props.id,
      type: this.props.type,
      name: this.props.name,
      disabled: this.props.disabled || this.props.readOnly,
      readOnly: this.props.readOnly,
      className: classes,
      onChange: this.handleChange,
      checked: !!this.props.value,
      value: 1,
    };
  }

  /**
   * React recommends using `onClick`, however react-bootstrap uses `onChange`
   *
   * @param {Event} event
   */
  handleChange(event) {
    if (this.props.readOnly || this.props.disabled) {
      event.preventDefault();
      return;
    }

    let callback = null;
    if (typeof this.props.onChange === 'function') {
      // call onChange for `FormBuilder` and `redux-form` to work
      callback = this.props.onChange;
    } else if (typeof this.props.onClick === 'function') {
      // for other React components which needs compatibility with this component
      callback = this.props.onClick;
    }

    if (callback) {
      callback(event, {
        id: this.props.id,
        value: event.target.checked ? 1 : 0,
      });
    }
  }

  render() {
    const leftTitle = this.props.leftTitle !== null
      ? this.props.leftTitle
      : this.props.title;

    const labelText = this.props.rightTitle !== null
      ? `${leftTitle} ${this.props.rightTitle}`
      : leftTitle;

    return (
      <FormGroup check>
        <Label check>
          <Input {...this.getInputProps()} />
          {castStringToElement('span', labelText)}
        </Label>
      </FormGroup>
    );
  }
}

OptionField.propTypes = {
  type: PropTypes.oneOf(['checkbox', 'radio']),
  leftTitle: PropTypes.any,
  rightTitle: PropTypes.any,
  title: PropTypes.any,
  extraClass: PropTypes.string,
  id: PropTypes.string,
  name: PropTypes.string,
  onChange: PropTypes.func,

  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.bool,
  ]),
  readOnly: PropTypes.bool,
  disabled: PropTypes.bool,
};

OptionField.defaultProps = {
  // React considers "undefined" as an uncontrolled component.
  extraClass: '',
  className: '',
  type: 'radio',
  leftTitle: null,
  rightTitle: null
};

export { OptionField as Component };

export default OptionField;


text:
import { mount } from '@vue/test-utils'
import { ButtonReload } from '@/components/Button'

describe('ButtonReload', () => {
  let wrapper

  beforeEach(() => {
    wrapper = mount(ButtonReload)
  })

  it('should render', () => {
    expect(wrapper.contains('.ButtonReload')).toBeTruthy()
  })

  it('should emit click event', () => {
    wrapper.trigger('click')
    expect(wrapper.emitted('click')).toBeTruthy()
  })
})


text:
ProbPy Package
==============

:mod:`rand_var` Module
----------------------

.. automodule:: ProbPy.rand_var
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`event` Module
-------------------

.. automodule:: ProbPy.event
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`factor` Module
--------------------

.. automodule:: ProbPy.factor
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`bn` Module
----------------

.. automodule:: ProbPy.bn
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`mn` Module
----------------

.. automodule:: ProbPy.mn
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`tmn` Module
-----------------

.. automodule:: ProbPy.tmn
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`inf_theory` Module
------------------------

.. automodule:: ProbPy.inf_theory
    :members:
    :undoc-members:
    :show-inheritance:


text:
package apple.metal;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import apple.metal.struct.MTLSize;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.ConstFloatPtr;
import org.moe.natj.general.ptr.FloatPtr;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * [@interface] MTLRasterizationRateLayerDescriptor
 *

 * Describes the minimum rasterization rate screen space using two piecewise linear functions.
 *

 * The two piecewise linear function (PLF) describe the desired rasterization quality on the horizontal and vertical
 * axis separately.
 * Each quality sample in the PLF is stored in an array as single precision floating point value between 0 (lowest
 * quality) and 1 (highest quality).
 * The first sample in the array describes the quality at the top (vertical) or left (horizontal) edge of screen space.
 * The last sample in the array describes the quality at the bottom (vertical) or right (horizontal) edge of screen
 * space.
 * All other samples are spaced equidistant in screen space.
 * MTLRasterizationRateLayerDescriptor instances will be stored inside a MTLRasterizationRateMapDescriptor which in turn
 * is compiled by MTLDevice into a MTLRasterizationRateMap.
 * Because MTLDevice may not support the requested granularity, the provided samples may be rounded up (towards higher
 * quality) during compilation.
 */
@Generated
@Library("Metal")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MTLRasterizationRateLayerDescriptor extends NSObject implements NSCopying {
    static {
        NatJ.register();
    }

    @Generated
    protected MTLRasterizationRateLayerDescriptor(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native MTLRasterizationRateLayerDescriptor alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native MTLRasterizationRateLayerDescriptor allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Owned
    @Selector("copyWithZone:")
    @MappedReturn(ObjCObjectMapper.class)
    public native Object copyWithZone(VoidPtr zone);

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    /**
     * [@property] horizontal
     *

     * Provide convenient bounds-checked access to the quality samples stored in the descriptor.
     *
     * @return Returns a syntactic sugar helper to get or set sample values on the horizontal axis.
     */
    @Generated
    @Selector("horizontal")
    public native MTLRasterizationRateSampleArray horizontal();

    /**
     * [@property] horizontalSampleStorage
     *

     * Provide direct access to the quality samples stored in the descriptor.
     *

     * The returned pointer points to the first element of an array of sampleCount.width elements.
     *
     * @return Pointer to the (mutable) storage array for samples on the horizontal axis.
     */
    @Generated
    @Selector("horizontalSampleStorage")
    public native FloatPtr horizontalSampleStorage();

    @Generated
    @Selector("init")
    public native MTLRasterizationRateLayerDescriptor init();

    /**
     * initWithSampleCount:
     *

     * Initialize a descriptor for a layer with the given number of quality samples on the horizontal and vertical axis.
     *

     * All values are initialized to zero.
     *
     * @param sampleCount The width and height components are the number of samples on the horizontal and vertical axis
     *                    respectively. The depth component is ignored.
     */
    @Generated
    @Selector("initWithSampleCount:")
    public native MTLRasterizationRateLayerDescriptor initWithSampleCount(@ByValue MTLSize sampleCount);

    /**
     * initWithSampleCount:horizontal:vertical:
     *

     * Initialize a descriptor for a layer with the given number of quality samples on the horizontal and vertical axis.
     *

     * Use initWithSampleCount: to initialize with zeroes instead.
     *
     * @param sampleCount The width and height components are the number of samples on the horizontal and vertical axis
     *                    respectively. The depth component is ignored.
     * @param horizontal  The initial sample values on the horizontal axis. Must point to an array of sampleCount.width
     *                    elements, of which the values will be copied into the MTLRasterizationRateLayerDescriptor.
     * @param vertical    The initial sample values on the vertical axis. Must point to an array of sampleCount.height
     *                    elements, of which the values will be copied into the MTLRasterizationRateLayerDescriptor.
     */
    @Generated
    @Selector("initWithSampleCount:horizontal:vertical:")
    public native MTLRasterizationRateLayerDescriptor initWithSampleCountHorizontalVertical(
            @ByValue MTLSize sampleCount, ConstFloatPtr horizontal, ConstFloatPtr vertical);

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native MTLRasterizationRateLayerDescriptor new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    /**
     * [@property] sampleCount
     *
     * @return The number of quality samples that this descriptor uses to describe its current function, for the
     *         horizontal and vertical axis. The depth component of the returned MTLSize is always 0.
     */
    @Generated
    @Selector("sampleCount")
    @ByValue
    public native MTLSize sampleCount();

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * [@property] vertical
     *

     * Provide convenient bounds-checked access to the quality samples stored in the descriptor.
     *
     * @return Returns a syntactic sugar helper to get or set sample values on the vertical axis.
     */
    @Generated
    @Selector("vertical")
    public native MTLRasterizationRateSampleArray vertical();

    /**
     * [@property] verticalSampleStorage
     *

     * Provide direct access to the quality samples stored in the descriptor.
     *

     * The returned pointer points to the first element of an array of sampleCount.height elements.
     *
     * @return Pointer to the (mutable) storage array for samples on the vertical axis.
     */
    @Generated
    @Selector("verticalSampleStorage")
    public native FloatPtr verticalSampleStorage();

    /**
     * [@property] maxSampleCount
     *
     * @return The maximum number of quality samples that this descriptor can use to describe its function, for the
     *         horizontal and vertical axis, this is the sampleCount that the descriptor was initialized with. The depth
     *         component of the returned MTLSize is always 0.
     */
    @Generated
    @Selector("maxSampleCount")
    @ByValue
    public native MTLSize maxSampleCount();

    /**
     * [@property] sampleCount
     *

     * This declaration adds a setter to the previously (prior to macOS 12.0 and iOS 15.0) read-only property.
     *

     * Setting a value (must be <= maxSampleCount) to allow MTLRasterizationRateLayerDescriptor to be re-used with a
     * different number of samples without having to be recreated.
     */
    @Generated
    @Selector("setSampleCount:")
    public native void setSampleCount(@ByValue MTLSize value);
}


text:
<?php

namespace Sylius\Bundle\CoreBundle\Form\Type\Checkout;

use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class CompleteType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('notes', TextareaType::class, [
            'label' => 'sylius.form.notes',
            'required' => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'sylius_checkout_complete';
    }
}


text:
require 'spec_helper'
describe 'api/v1/movements' do
  let(:auth) { authenticate }

  describe '/' do
    describe '#get' do
      context 'when no movements are found' do
        it 'respond with empty array' do
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(0)
        end
      end

      context 'when 10 movements are found' do
        it 'respond with an array' do
          FactoryGirl.create_list(:movement, 10)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(10)
        end
      end

      context 'when too many movements are found' do
        it 'paginates movements in an array (max size of ten)' do
          FactoryGirl.create_list(:movement, 11)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(response.headers['X-Per-Page'].to_i).to eq(10)
        end
        it 'paginates the array' do
          FactoryGirl.create_list(:movement, 11)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect((response.headers.keys & ['X-Total:',
                                           'X-Total-Pages',
                                           'X-Page',
                                           'X-Per-Page']).all?).to be_true
          expect(response.headers['X-Total-Pages'].to_i).to eq(2)
        end

        it 'allows us to specify movements per page' do
          FactoryGirl.create_list(:movement, 10)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token),
              'per_page' => 2
          expect(response).to be_success
          expect((response.headers.keys & ['X-Total:',
                                           'X-Total-Pages',
                                           'X-Page',
                                           'X-Per-Page']).all?).to be_true
          expect(response.headers['X-Total-Pages'].to_i).to eq(5)
        end

        it 'allows us to navigates pages of movements' do
          FactoryGirl.create_list(:movement, 11)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token),
              'page' => 2
          expect(response).to be_success
          expect((response.headers.keys & ['X-Total:',
                                           'X-Total-Pages',
                                           'X-Page',
                                           'X-Per-Page']).all?).to be_true
          expect(json.length).to eq(1)
        end
      end

      context 'when no open movements are found' do
        it 'respond with empty array' do
          FactoryGirl.create(:movement,
                             privacy: 'closed')
          FactoryGirl.create(:movement,
                             privacy: 'secret')
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(0)
        end
      end

      context 'when open movements are found' do
        it 'respond with an array' do
          FactoryGirl.create(:movement,
                             privacy: 'closed')
          FactoryGirl.create(:movement,
                             privacy: 'secret')
          FactoryGirl.create(:movement)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(1)
        end
      end

      context 'when user is a member of private movements' do
        it 'respond with an array' do
          FactoryGirl.create(:movement,
                             privacy: 'secret',
                             users: [auth[:user]])
          FactoryGirl.create(:movement,
                             privacy: 'closed',
                             users: [auth[:user]])
          FactoryGirl.create(:movement,
                             privacy: 'secret')
          FactoryGirl.create(:movement)
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(3)
        end
      end

      context 'when user is banned from private or closed movements' do
        it 'respond with an array without banned movement' do
          FactoryGirl.create(:movement)
          @movement = FactoryGirl.create(:movement,
                                         privacy: 'closed',
                                         users: [auth[:user]])
          @membership = @movement.memberships.first
          @membership.role = 'banned'
          @membership.save
          get '/api/v1/movements.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
          expect(json.length).to eq(1)
        end
      end
    end

    describe '#post' do
      context 'when params are valid' do
        it 'respond with movement' do
          movement = FactoryGirl.build(:movement).attributes
          movement.delete('id')
          movement.delete('created_at')
          movement.delete('updated_at')
          post '/api/v1/movements',
               'access_token' => auth[:access_token].try(:token),
               'movement' => movement
          # expect(response).to be_success
        end
      end
      context 'when params are invalid' do
        it 'respond with 400'
      end
    end
  end

  describe 'id' do
    describe '#get' do
      context 'when no movement is found' do
        it 'respond with 404' do
          get '/api/v1/movements/0.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(404)
          expect(json['error']).to eq('Couldn\'t find Movement with \'id\'=0')
        end
      end

      context 'when movement is illegally accessed' do
        it 'respond with 403' do
          @movement = FactoryGirl.create(:movement, privacy: 'closed')
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(403)
          expect(json['error']).to eq('Unable to retrieve this movement')
        end
      end

      context 'when open movement is accessed under ban' do
        it 'respond with 403' do
          @movement = FactoryGirl.create(:movement, privacy: 'open')
          @movement.memberships << Membership.new(movement: @movement,
                                                  user: auth[:user],
                                                  role: 'banned')
          @movement.save!
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(403)
          expect(json['error']).to eq('Unable to retrieve this movement')
        end
      end

      context 'when closed movement is accessed under ban' do
        it 'respond with 403' do
          @movement = FactoryGirl.create(:movement, privacy: 'closed')
          @movement.memberships << Membership.new(movement: @movement,
                                                  user: auth[:user],
                                                  role: 'banned')
          @movement.save!
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(403)
          expect(json['error']).to eq('Unable to retrieve this movement')
        end
      end

      context 'when open movement is found' do
        it 'respond with object' do
          @movement = FactoryGirl.create(:movement)
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
        end
      end

      context 'when closed movement is found as a member' do
        it 'respond with object' do
          @movement = FactoryGirl.create(:movement, privacy: 'closed')
          @movement.memberships << Membership.new(movement: @movement,
                                                  user: auth[:user],
                                                  role: 'member')
          @movement.save!
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
        end
      end

      context 'when private movement is found as a member' do
        it 'respond with object' do
          @movement = FactoryGirl.create(:movement, privacy: 'closed')
          @movement.memberships << Membership.new(movement: @movement,
                                                  user: auth[:user],
                                                  role: 'member')
          @movement.save!
          get "/api/v1/movements/#{@movement.id}.json",
              'access_token' => auth[:access_token].try(:token)
          expect(response).to be_success
        end
      end

      context 'when invalid id is provided' do
        it 'respond with an error' do
          get '/api/v1/movements/ejkjndsf.json',
              'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(400)
          expect(json['error']).to eq('id is invalid')
        end
      end

      context 'when invalid type is provided' do
        it 'respond with an error' do
          get '/api/v1/movements/1.json',
              'access_token' => auth[:access_token].try(:token),
              'type' => 'dgkjnfgdkdjfgn'
          expect(response.status).to eq(400)
          expect(json['error']).to eq('type does not have a valid value')
        end
      end

      context 'when invalid id and type is provided' do
        it 'respond with an error' do
          get '/api/v1/movements/kjnfdg.json',
              'access_token' => auth[:access_token].try(:token),
              'type' => 'dgkjnfgdkdjfgn'
          expect(response.status).to eq(400)
          expect(json['error']).to eq('id is invalid'\
                                      ', type does not have a valid value')
        end
      end
    end
    describe '#delete' do
      context 'when movement cannot be found' do
        it 'respond with an error' do
          delete '/api/v1/movements/1.json',
                 'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(404)
          expect(json['error']).to eq("Couldn't find Movement with 'id'=1")
        end
      end
      context 'when movement is deleted with incorrect permissions' do
        it 'respond with an error' do
          movement = FactoryGirl.create(:movement)
          delete "/api/v1/movements/#{movement.id}.json",
                 'access_token' => auth[:access_token].try(:token)
          expect(response.status).to eq(403)
          expect(json['error']).to eq('Unable to delete this movement')
        end
      end
      context 'when one movement is deleted with correct permissions' do
        it 'respond with success' do
          @movement = FactoryGirl.create(:movement)
          @movement.memberships << Membership.new(movement: @movement,
                                                  user: auth[:user],
                                                  role: 'admin')
          @movement.save!
          expect(Membership.first).to be_a_kind_of Membership
          delete "/api/v1/movements/#{@movement.id}.json",
                 'access_token' => auth[:access_token].try(:token)
          expect(Membership.first).to be_nil
          expect(response).to be_success
          expect(response.body).to eq('"success"')
        end
      end
    end

  end
end


text:
name: cljs.test/async?
see also:
---

## Summary

## Details

## Examples