text:
package com.gemstone.gemfire.internal.cache;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.cache.client.internal.ClientMetadataService;
import com.gemstone.gemfire.cache.client.internal.ClientPartitionAdvisor;
import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.cache30.CacheTestCase;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.Locator;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.cache.execute.data.CustId;
import com.gemstone.gemfire.internal.cache.execute.data.OrderId;
import com.gemstone.gemfire.internal.cache.execute.data.ShipmentId;
import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerTestUtil;

import dunit.Host;
import dunit.SerializableRunnable;
import dunit.VM;

public class Bug42010StatsDUnitTest extends CacheTestCase{

  private static final String Region_Name = "42010";

  private VM member0 = null;

  private VM member1 = null;

  private VM member2 = null;

  private VM member3 = null;

  private static Region region = null;

  private static Region customerRegion = null;

  private static Region orderRegion = null;

  private static Region shipmentRegion = null;

  private static Region regionWithResolver = null;

  private static Cache cache = null;

  private static final int locatorPort = 12345;

  private static Locator locator = null;

  private static long metaDataRefreshCount;

  private static long nonSingleHopsCount;

  private static long metaDataRefreshCount_Customer;

  private static long nonSingleHopsCount_Customer;

  private static long metaDataRefreshCount_Order;

  private static long nonSingleHopsCount_Order;

  private static long metaDataRefreshCount_Shipment;

  private static long nonSingleHopsCount_Shipment;

  public Bug42010StatsDUnitTest(String name) {
    super(name);

    // TODO Auto-generated constructor stub
  }

  public void setUp() throws Exception {
    super.setUp();
    Host host = Host.getHost(0);
    member0 = host.getVM(0);
    member1 = host.getVM(1);
    member2 = host.getVM(2);
    member3 = host.getVM(3);
  }

  public void tearDown2() throws Exception {
    try {

      // close the clients first
      member0.invoke(Bug42010StatsDUnitTest.class, "closeCache");
      member1.invoke(Bug42010StatsDUnitTest.class, "closeCache");
      member2.invoke(Bug42010StatsDUnitTest.class, "closeCache");
      member3.invoke(Bug42010StatsDUnitTest.class, "closeCache");
      closeCache();

      super.tearDown2();

      member0 = null;
      member1 = null;
      member2 = null;
      member3 = null;
      cache = null;
      invokeInEveryVM(new SerializableRunnable() { public void run() { cache = null; } });

    }
    finally {
      unregisterAllDataSerializersFromAllVms();
    }
  }

  public static void closeCache() {
    if (cache != null && !cache.isClosed()) {
      cache.close();
      cache.getDistributedSystem().disconnect();
    }
  }

  public void test_clientStats_PR(){
    VM server1 = member0;
    VM server2 = member1;
    VM server3 = member2;
    VM client1 = member3;

    Integer port0 = (Integer)member0.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 113,"No_Colocation"});
    Integer port1 = (Integer)member1.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 113,"No_Colocation"});
    Integer port2 = (Integer)member2.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 113,"No_Colocation"});
     client1.invoke(
        Bug42010StatsDUnitTest.class, "createClient",
        new Object[] {port0, port1, port2,"No_Colocation"});

    createClient(port0, port1, port2, "No_Colocation");

    client1.invoke(
        Bug42010StatsDUnitTest.class, "createPR",
        new Object[] {"FirstClient", "No_Colocation"});
    createPR("SecondClient", "No_Colocation");

    client1.invoke(
        Bug42010StatsDUnitTest.class, "getPR",
        new Object[] {"FirstClient", "No_Colocation"});
    getPR("SecondClient", "No_Colocation");

    client1.invoke(
        Bug42010StatsDUnitTest.class, "updatePR",
        new Object[] {"FirstClient", "No_Colocation"});
  }

  public void test_clientStatsColocation_PR(){
    VM server1 = member0;
    VM server2 = member1;
    VM server3 = member2;
    VM client1 = member3;

    Integer port0 = (Integer)member0.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 4, "Colocation" });
    Integer port1 = (Integer)member1.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 4, "Colocation" });
    Integer port2 = (Integer)member2.invoke(
        Bug42010StatsDUnitTest.class, "createServerForStats",
        new Object[] { 0, 4, "Colocation"});
     client1.invoke(
        Bug42010StatsDUnitTest.class, "createClient",
        new Object[] {port0, port1, port2, "Colocation"});
    createClient(port0, port1, port2, "Colocation");

    client1.invoke(
        Bug42010StatsDUnitTest.class, "createPR",
        new Object[] {"FirstClient", "Colocation"});

    client1.invoke(
        Bug42010StatsDUnitTest.class, "getPR",
        new Object[] {"FirstClient", "Colocation"});
  }

  public static void createClient(int port0, int port1, int port2, String colocation) {
    Properties props = new Properties();
    props = new Properties();
    props.setProperty("mcast-port", "0");
    props.setProperty("locators", "");
    CacheTestCase test = new Bug42010StatsDUnitTest(
        "Bug42010StatsDUnitTest");
    DistributedSystem ds = test.getSystem(props);
    cache = CacheFactory.create(ds);
    assertNotNull(cache);
    CacheServerTestUtil.disableShufflingOfEndpoints();
    Pool p;
    try {
      p = PoolManager.createFactory().addServer("localhost", port0).addServer(
          "localhost", port1).addServer("localhost", port2)
          .setSubscriptionEnabled(false)
          .create(Region_Name);
    }
    finally {
      CacheServerTestUtil.enableShufflingOfEndpoints();
    }
    createRegionInClientCache(p.getName(), colocation);
  }

  public static int createServerForStats(int redundantCopies, int totalNoofBuckets, String colocation) {
    CacheTestCase test = new Bug42010StatsDUnitTest(
        "Bug42010StatsDUnitTest");
    cache = test.getCache();
    CacheServer server = cache.addCacheServer();
    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    server.setPort(port);
    server.setHostnameForClients("localhost");
    try {
      server.start();
    }
    catch (IOException e) {
      fail("Failed to start server ", e);
    }

    if (colocation.equals("No_Colocation")) {
      if(totalNoofBuckets == 0){ //DR
        AttributesFactory attr = new AttributesFactory();
        attr.setScope(Scope.DISTRIBUTED_ACK);
        attr.setDataPolicy(DataPolicy.REPLICATE);
        region = cache.createRegion(Region_Name, attr.create());
        assertNotNull(region);
        getLogWriter().info(
            "Distributed Region " + Region_Name + " created Successfully :"
                + region.toString());
      }else{
      PartitionAttributesFactory paf = new PartitionAttributesFactory();
      paf.setRedundantCopies(redundantCopies).setTotalNumBuckets(
          totalNoofBuckets);
      AttributesFactory attr = new AttributesFactory();
      attr.setPartitionAttributes(paf.create());
      region = cache.createRegion(Region_Name, attr.create());
      assertNotNull(region);
      getLogWriter().info(
          "Partitioned Region " + Region_Name + " created Successfully :"
              + region.toString());
      }
    }
    else {
      PartitionAttributesFactory paf = new PartitionAttributesFactory();
      paf.setRedundantCopies(redundantCopies).setTotalNumBuckets(
          totalNoofBuckets).setPartitionResolver(
          new CustomerIDPartitionResolver("CustomerIDPartitionResolver"));
      AttributesFactory attr = new AttributesFactory();
      attr.setPartitionAttributes(paf.create());
      customerRegion = cache.createRegion("CUSTOMER", attr.create());
      assertNotNull(customerRegion);
      getLogWriter().info(
          "Partitioned Region CUSTOMER created Successfully :"
              + customerRegion.toString());

      paf = new PartitionAttributesFactory();
      paf.setRedundantCopies(redundantCopies).setTotalNumBuckets(
          totalNoofBuckets).setColocatedWith("CUSTOMER").setPartitionResolver(
          new CustomerIDPartitionResolver("CustomerIDPartitionResolver"));
      attr = new AttributesFactory();
      attr.setPartitionAttributes(paf.create());
      orderRegion = cache.createRegion("ORDER", attr.create());
      assertNotNull(orderRegion);
      getLogWriter().info(
          "Partitioned Region ORDER created Successfully :"
              + orderRegion.toString());

      paf = new PartitionAttributesFactory();
      paf.setRedundantCopies(redundantCopies).setTotalNumBuckets(
          totalNoofBuckets).setColocatedWith("ORDER").setPartitionResolver(
          new CustomerIDPartitionResolver("CustomerIDPartitionResolver"));
      attr = new AttributesFactory();
      attr.setPartitionAttributes(paf.create());
      shipmentRegion = cache.createRegion("SHIPMENT", attr.create());
      assertNotNull(shipmentRegion);
      getLogWriter().info(
          "Partitioned Region SHIPMENT created Successfully :"
              + shipmentRegion.toString());
    }
    return port;
  }

  private static void createRegionInClientCache(String poolName, String colocation) {
    if (colocation.equals("No_Colocation")) {
      AttributesFactory factory = new AttributesFactory();
      factory.setPoolName(poolName);
      factory.setDataPolicy(DataPolicy.EMPTY);
      RegionAttributes attrs = factory.create();
      region = cache.createRegion(Region_Name, attrs);
      assertNotNull(region);
      getLogWriter().info(
          "Region " + Region_Name + " created Successfully :" + region.toString());
    }
    else {
      AttributesFactory factory = new AttributesFactory();
      factory.setPoolName(poolName);
      RegionAttributes attrs = factory.create();
      customerRegion = cache.createRegion("CUSTOMER", attrs);
      assertNotNull(customerRegion);
      getLogWriter().info(
          "Partitioned Region CUSTOMER created Successfully :"
              + customerRegion.toString());

      factory = new AttributesFactory();
      factory.setPoolName(poolName);
      attrs = factory.create();
      orderRegion = cache.createRegion("ORDER", attrs);
      assertNotNull(orderRegion);
      getLogWriter().info(
          "Partitioned Region ORDER created Successfully :"
              + orderRegion.toString());

      factory = new AttributesFactory();
      factory.setPoolName(poolName);
      attrs = factory.create();
      shipmentRegion = cache.createRegion("SHIPMENT", attrs);
      assertNotNull(shipmentRegion);
      getLogWriter().info(
          "Partitioned Region SHIPMENT created Successfully :"
              + shipmentRegion.toString());
    }
  }

  public static void createPR(String FromClient,
      String colocation) {
    if (colocation.equals("No_Colocation")) {
      if (FromClient.equals("FirstClient")) {
        for (int i = 0; i < 113; i++) {
          region.create(new Integer(i), "create" + i);
        }
        ClientMetadataService cms = ((GemFireCacheImpl)cache)
            .getClientMetadataService();
        Map<String, ClientPartitionAdvisor> regionMetaData = cms
            .getClientPRMetadata_TEST_ONLY();
        assertEquals(0, regionMetaData.size());

        for (int i = 113; i < 226; i++) {
          region.create(new Integer(i), "create" + i);
        }
        cms = ((GemFireCacheImpl)cache).getClientMetadataService();
        regionMetaData = cms.getClientPRMetadata_TEST_ONLY();
        assertEquals(1, regionMetaData.size());
        assertTrue(regionMetaData.containsKey(region.getFullPath()));
        ClientPartitionAdvisor prMetaData = regionMetaData.get(region
            .getFullPath());
        metaDataRefreshCount = ((LocalRegion)region).getCachePerfStats().getMetaDataRefreshCount();
        nonSingleHopsCount = ((LocalRegion)region).getCachePerfStats().getNonSingleHopsCount();
        assertTrue(metaDataRefreshCount != 0); // hops are not predictable
        assertTrue(nonSingleHopsCount != 0);
      }
      else {
        for (int i = 0; i < 226; i++) {
          region.create(new Integer(i), "create" + i);
        }
        ClientMetadataService cms = ((GemFireCacheImpl)cache)
            .getClientMetadataService();
        Map<String, ClientPartitionAdvisor> regionMetaData = cms
            .getClientPRMetadata_TEST_ONLY();
        assertEquals(1, regionMetaData.size());
        assertTrue(regionMetaData.containsKey(region.getFullPath()));
        ClientPartitionAdvisor prMetaData = regionMetaData.get(region
            .getFullPath());
        metaDataRefreshCount = ((LocalRegion)region).getCachePerfStats().getMetaDataRefreshCount();
        nonSingleHopsCount = ((LocalRegion)region).getCachePerfStats().getNonSingleHopsCount();
        assertTrue(metaDataRefreshCount != 0); // hops are not predictable
        assertTrue(nonSingleHopsCount != 0);
      }
    }
    else {
      for (int i = 0; i <= 20; i++) {
        CustId custid = new CustId(i);
        Customer customer = new Customer("name" + i, "Address" + i);
        customerRegion.put(custid, customer);
        for (int j = 1; j <= 10; j++) {
          int oid = (i * 10) + j;
          OrderId orderId = new OrderId(oid, custid);
          Order order = new Order("OREDR" + oid);
          orderRegion.put(orderId, order);
          for (int k = 1; k <= 10; k++) {
            int sid = (oid * 10) + k;
            ShipmentId shipmentId = new ShipmentId(sid, orderId);
            Shipment shipment = new Shipment("Shipment" + sid);
            shipmentRegion.put(shipmentId, shipment);
          }
        }
      }
      ClientMetadataService cms = ((GemFireCacheImpl)cache)
          .getClientMetadataService();
      Map<String, ClientPartitionAdvisor> regionMetaData = cms
          .getClientPRMetadata_TEST_ONLY();
      assertEquals(3, regionMetaData.size());
      assertTrue(regionMetaData.containsKey(customerRegion.getFullPath()));
      ClientPartitionAdvisor prMetaData_Customer = regionMetaData
          .get(customerRegion.getFullPath());
      metaDataRefreshCount_Customer = ((LocalRegion)customerRegion).getCachePerfStats().getMetaDataRefreshCount();
      nonSingleHopsCount_Customer = ((LocalRegion)customerRegion).getCachePerfStats().getNonSingleHopsCount();
      assertTrue(metaDataRefreshCount_Customer != 0); // hops are not predictable
      assertTrue(nonSingleHopsCount_Customer != 0);

      ClientPartitionAdvisor prMetaData_Order = regionMetaData
          .get(orderRegion.getFullPath());
      metaDataRefreshCount_Order = ((LocalRegion)orderRegion).getCachePerfStats().getMetaDataRefreshCount();
      nonSingleHopsCount_Order = ((LocalRegion)orderRegion).getCachePerfStats().getNonSingleHopsCount();
      assertTrue(metaDataRefreshCount_Order == 0);
      assertTrue(nonSingleHopsCount_Order != 0);

      ClientPartitionAdvisor prMetaData_Shipment = regionMetaData
          .get(shipmentRegion.getFullPath());
      metaDataRefreshCount_Shipment = ((LocalRegion)shipmentRegion).getCachePerfStats().getMetaDataRefreshCount();
      nonSingleHopsCount_Shipment = ((LocalRegion)shipmentRegion).getCachePerfStats().getNonSingleHopsCount();
      assertTrue(metaDataRefreshCount_Shipment == 0);
      assertTrue(nonSingleHopsCount_Shipment != 0);
    }
  }

  public static void getPR(String FromClient,
      String colocation) {
    if (colocation.equals("No_Colocation")) {
      if (FromClient.equals("FirstClient")) {
        for (int i = 0; i < 226; i++) {
          region.get(new Integer(i));
        }
        ClientMetadataService cms = ((GemFireCacheImpl)cache)
            .getClientMetadataService();
        Map<String, ClientPartitionAdvisor> regionMetaData = cms
            .getClientPRMetadata_TEST_ONLY();
        assertEquals(1, regionMetaData.size());
        ClientPartitionAdvisor prMetaData = regionMetaData.get(region
            .getFullPath());
        assertEquals(metaDataRefreshCount , ((LocalRegion)region).getCachePerfStats().getMetaDataRefreshCount());
        assertEquals(nonSingleHopsCount , ((LocalRegion)region).getCachePerfStats().getNonSingleHopsCount());
      }
      else {
        for (int i = 0; i < 226; i++) {
          region.get(new Integer(i));
        }
        ClientMetadataService cms = ((GemFireCacheImpl)cache)
            .getClientMetadataService();
        Map<String, ClientPartitionAdvisor> regionMetaData = cms
            .getClientPRMetadata_TEST_ONLY();
        assertEquals(1, regionMetaData.size());
        ClientPartitionAdvisor prMetaData = regionMetaData.get(region
            .getFullPath());
        assertEquals(metaDataRefreshCount , ((LocalRegion)region).getCachePerfStats().getMetaDataRefreshCount());
        assertEquals(nonSingleHopsCount , ((LocalRegion)region).getCachePerfStats().getNonSingleHopsCount());
      }
    }
    else {
      for (int i = 0; i <= 20; i++) {
        CustId custid = new CustId(i);
        customerRegion.get(custid);
        for (int j = 1; j <= 10; j++) {
          int oid = (i * 10) + j;
          OrderId orderId = new OrderId(oid, custid);
          orderRegion.get(orderId);
          for (int k = 1; k <= 10; k++) {
            int sid = (oid * 10) + k;
            ShipmentId shipmentId = new ShipmentId(sid, orderId);
            shipmentRegion.get(shipmentId);
          }
        }
      }
      ClientMetadataService cms = ((GemFireCacheImpl)cache)
          .getClientMetadataService();
      Map<String, ClientPartitionAdvisor> regionMetaData = cms
          .getClientPRMetadata_TEST_ONLY();
      assertEquals(3, regionMetaData.size());
      assertTrue(regionMetaData.containsKey(customerRegion.getFullPath()));
      ClientPartitionAdvisor prMetaData_Customer = regionMetaData
          .get(customerRegion.getFullPath());
      assertEquals(metaDataRefreshCount_Customer , ((LocalRegion)customerRegion).getCachePerfStats().getMetaDataRefreshCount());
      assertEquals(nonSingleHopsCount_Customer , ((LocalRegion)customerRegion).getCachePerfStats().getNonSingleHopsCount());

      ClientPartitionAdvisor prMetaData_Order = regionMetaData
          .get(orderRegion.getFullPath());
      assertEquals(metaDataRefreshCount_Order , ((LocalRegion)orderRegion).getCachePerfStats().getMetaDataRefreshCount());
      assertEquals(nonSingleHopsCount_Order , ((LocalRegion)orderRegion).getCachePerfStats().getNonSingleHopsCount());

      ClientPartitionAdvisor prMetaData_Shipment = regionMetaData
          .get(shipmentRegion.getFullPath());
      assertEquals(metaDataRefreshCount_Shipment , ((LocalRegion)shipmentRegion).getCachePerfStats().getMetaDataRefreshCount());
      assertEquals(nonSingleHopsCount_Shipment , ((LocalRegion)shipmentRegion).getCachePerfStats().getNonSingleHopsCount());
    }
  }

  public static void updatePR(String FromClient,
      String colocation) {
    if (colocation.equals("No_Colocation")) {
      if (FromClient.equals("FirstClient")) {
        for (int i = 0; i < 226; i++) {
          region.put(new Integer(i), "Update" + i);
        }
        ClientMetadataService cms = ((GemFireCacheImpl)cache)
            .getClientMetadataService();
        Map<String, ClientPartitionAdvisor> regionMetaData = cms
            .getClientPRMetadata_TEST_ONLY();
        assertEquals(1, regionMetaData.size());
        ClientPartitionAdvisor prMetaData = regionMetaData.get(region
            .getFullPath());
        assertEquals(metaDataRefreshCount , ((LocalRegion)region).getCachePerfStats().getMetaDataRefreshCount());
        assertEquals(nonSingleHopsCount , ((LocalRegion)region).getCachePerfStats().getNonSingleHopsCount());
      }
    }
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.authorization.implementation;

import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.Delete;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Post;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.authorization.fluent.OAuth2PermissionGrantsClient;
import com.azure.resourcemanager.authorization.fluent.models.OAuth2PermissionGrantInner;
import com.azure.resourcemanager.authorization.models.GraphErrorException;
import com.azure.resourcemanager.authorization.models.OAuth2PermissionGrantListResult;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in OAuth2PermissionGrantsClient. */
public final class OAuth2PermissionGrantsClientImpl implements OAuth2PermissionGrantsClient {
    private final ClientLogger logger = new ClientLogger(OAuth2PermissionGrantsClientImpl.class);

    /** The proxy service used to perform REST calls. */
    private final OAuth2PermissionGrantsService service;

    /** The service client containing this operation class. */
    private final GraphRbacManagementClientImpl client;

    /**
     * Initializes an instance of OAuth2PermissionGrantsClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    OAuth2PermissionGrantsClientImpl(GraphRbacManagementClientImpl client) {
        this.service =
            RestProxy
                .create(OAuth2PermissionGrantsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for GraphRbacManagementClientOAuth2PermissionGrants to be used by the
     * proxy service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "GraphRbacManagementC")
    private interface OAuth2PermissionGrantsService {
        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("/{tenantID}/oauth2PermissionGrants")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<OAuth2PermissionGrantListResult>> list(
            @HostParam("$host") String endpoint,
            @QueryParam("$filter") String filter,
            @QueryParam("api-version") String apiVersion,
            @PathParam("tenantID") String tenantId,
            Context context);

        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Post("/{tenantID}/oauth2PermissionGrants")
        @ExpectedResponses({201})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<OAuth2PermissionGrantInner>> create(
            @HostParam("$host") String endpoint,
            @QueryParam("api-version") String apiVersion,
            @PathParam("tenantID") String tenantId,
            @BodyParam("application/json") OAuth2PermissionGrantInner body,
            Context context);

        @Headers({"Accept: application/json;q=0.9", "Content-Type: application/json"})
        @Delete("/{tenantID}/oauth2PermissionGrants/{objectId}")
        @ExpectedResponses({204})
        @UnexpectedResponseExceptionType(GraphErrorException.class)
        Mono<Response<Void>> delete(
            @HostParam("$host") String endpoint,
            @PathParam("objectId") String objectId,
            @QueryParam("api-version") String apiVersion,
            @PathParam("tenantID") String tenantId,
            Context context);

        @Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
        @Get("/{tenantID}/{nextLink}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(GraphErrorException.class)
        Mono<Response<OAuth2PermissionGrantListResult>> listNext(
            @HostParam("$host") String endpoint,
            @PathParam(value = "nextLink", encoded = true) String nextLink,
            @QueryParam("api-version") String apiVersion,
            @PathParam("tenantID") String tenantId,
            Context context);
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @param filter This is the Service Principal ObjectId associated with the app.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<OAuth2PermissionGrantInner>> listSinglePageAsync(String filter) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .list(
                            this.client.getEndpoint(),
                            filter,
                            this.client.getApiVersion(),
                            this.client.getTenantId(),
                            context))
            .<PagedResponse<OAuth2PermissionGrantInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().odataNextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @param filter This is the Service Principal ObjectId associated with the app.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<OAuth2PermissionGrantInner>> listSinglePageAsync(String filter, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .list(this.client.getEndpoint(), filter, this.client.getApiVersion(), this.client.getTenantId(), context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().odataNextLink(),
                        null));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @param filter This is the Service Principal ObjectId associated with the app.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<OAuth2PermissionGrantInner> listAsync(String filter) {
        return new PagedFlux<>(() -> listSinglePageAsync(filter), nextLink -> listNextSinglePageAsync(nextLink));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<OAuth2PermissionGrantInner> listAsync() {
        final String filter = null;
        return new PagedFlux<>(() -> listSinglePageAsync(filter), nextLink -> listNextSinglePageAsync(nextLink));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @param filter This is the Service Principal ObjectId associated with the app.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<OAuth2PermissionGrantInner> listAsync(String filter, Context context) {
        return new PagedFlux<>(
            () -> listSinglePageAsync(filter, context), nextLink -> listNextSinglePageAsync(nextLink, context));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @param filter This is the Service Principal ObjectId associated with the app.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<OAuth2PermissionGrantInner> list(String filter, Context context) {
        return new PagedIterable<>(listAsync(filter, context));
    }

    /**
     * Queries OAuth2 permissions grants for the relevant SP ObjectId of an app.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return server response for get oauth2 permissions grants.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<OAuth2PermissionGrantInner> list() {
        final String filter = null;
        return new PagedIterable<>(listAsync(filter));
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @param body The relevant app Service Principal Object Id and the Service Principal Object Id you want to grant.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<OAuth2PermissionGrantInner>> createWithResponseAsync(OAuth2PermissionGrantInner body) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        if (body != null) {
            body.validate();
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .create(
                            this.client.getEndpoint(),
                            this.client.getApiVersion(),
                            this.client.getTenantId(),
                            body,
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @param body The relevant app Service Principal Object Id and the Service Principal Object Id you want to grant.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<OAuth2PermissionGrantInner>> createWithResponseAsync(
        OAuth2PermissionGrantInner body, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        if (body != null) {
            body.validate();
        }
        context = this.client.mergeContext(context);
        return service
            .create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getTenantId(), body, context);
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @param body The relevant app Service Principal Object Id and the Service Principal Object Id you want to grant.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<OAuth2PermissionGrantInner> createAsync(OAuth2PermissionGrantInner body) {
        return createWithResponseAsync(body)
            .flatMap(
                (Response<OAuth2PermissionGrantInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<OAuth2PermissionGrantInner> createAsync() {
        final OAuth2PermissionGrantInner body = null;
        return createWithResponseAsync(body)
            .flatMap(
                (Response<OAuth2PermissionGrantInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public OAuth2PermissionGrantInner create() {
        final OAuth2PermissionGrantInner body = null;
        return createAsync(body).block();
    }

    /**
     * Grants OAuth2 permissions for the relevant resource Ids of an app.
     *
     * @param body The relevant app Service Principal Object Id and the Service Principal Object Id you want to grant.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<OAuth2PermissionGrantInner> createWithResponse(OAuth2PermissionGrantInner body, Context context) {
        return createWithResponseAsync(body, context).block();
    }

    /**
     * Delete a OAuth2 permission grant for the relevant resource Ids of an app.
     *
     * @param objectId The object ID of a permission grant.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Response<Void>> deleteWithResponseAsync(String objectId) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (objectId == null) {
            return Mono.error(new IllegalArgumentException("Parameter objectId is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .delete(
                            this.client.getEndpoint(),
                            objectId,
                            this.client.getApiVersion(),
                            this.client.getTenantId(),
                            context))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Delete a OAuth2 permission grant for the relevant resource Ids of an app.
     *
     * @param objectId The object ID of a permission grant.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<Void>> deleteWithResponseAsync(String objectId, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (objectId == null) {
            return Mono.error(new IllegalArgumentException("Parameter objectId is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .delete(
                this.client.getEndpoint(), objectId, this.client.getApiVersion(), this.client.getTenantId(), context);
    }

    /**
     * Delete a OAuth2 permission grant for the relevant resource Ids of an app.
     *
     * @param objectId The object ID of a permission grant.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the completion.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Mono<Void> deleteAsync(String objectId) {
        return deleteWithResponseAsync(objectId).flatMap((Response<Void> res) -> Mono.empty());
    }

    /**
     * Delete a OAuth2 permission grant for the relevant resource Ids of an app.
     *
     * @param objectId The object ID of a permission grant.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public void delete(String objectId) {
        deleteAsync(objectId).block();
    }

    /**
     * Delete a OAuth2 permission grant for the relevant resource Ids of an app.
     *
     * @param objectId The object ID of a permission grant.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the response.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<Void> deleteWithResponse(String objectId, Context context) {
        return deleteWithResponseAsync(objectId, context).block();
    }

    /**
     * Gets the next page of OAuth2 permission grants.
     *
     * @param nextLink Next link for the list operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the next page of OAuth2 permission grants.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<OAuth2PermissionGrantInner>> listNextSinglePageAsync(String nextLink) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        return FluxUtil
            .withContext(
                context ->
                    service
                        .listNext(
                            this.client.getEndpoint(),
                            nextLink,
                            this.client.getApiVersion(),
                            this.client.getTenantId(),
                            context))
            .<PagedResponse<OAuth2PermissionGrantInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().odataNextLink(),
                        null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Gets the next page of OAuth2 permission grants.
     *
     * @param nextLink Next link for the list operation.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws GraphErrorException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the next page of OAuth2 permission grants.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<OAuth2PermissionGrantInner>> listNextSinglePageAsync(String nextLink, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (nextLink == null) {
            return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
        }
        if (this.client.getTenantId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getTenantId() is required and cannot be null."));
        }
        context = this.client.mergeContext(context);
        return service
            .listNext(
                this.client.getEndpoint(), nextLink, this.client.getApiVersion(), this.client.getTenantId(), context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(),
                        res.getStatusCode(),
                        res.getHeaders(),
                        res.getValue().value(),
                        res.getValue().odataNextLink(),
                        null));
    }
}

redpajama_set_name: RedPajamaGithub


text: MetroWorlds' Developer API


text:
[![CI Status](http://img.shields.io/travis/Logan Sease/SeaseAssist.svg?style=flat)](https://travis-ci.org/Logan Sease/SeaseAssist)
[![Version](https://img.shields.io/cocoapods/v/SeaseAssist.svg?style=flat)](http://cocoapods.org/pods/SeaseAssist)
[![License](https://img.shields.io/cocoapods/l/SeaseAssist.svg?style=flat)](http://cocoapods.org/pods/SeaseAssist)
[![Platform](https://img.shields.io/cocoapods/p/SeaseAssist.svg?style=flat)](http://cocoapods.org/pods/SeaseAssist)

##Summary Info

This library is founded on the basis that commonly performed tasks, which take several lines of code to write should be encompased into simple methods, either using class extensions or services, that can be written in a single line of code. Thus reducing code redundancy and increasing code readibility.

In this package you will find the following:

- A collection of NSDate Helpers
- Button and View helpers to make good looking views easily and handle things like rounding, borders and more
- An Array and Dictionary extension to convert to and from JSON
- AN HTTP Request class to easily send api requests without any non-standard libraries
- A UIImage View extension to load images from a URL and cache the image locally.
- A Validation Helper class for NSString
- String and NSData cryptography Helpers
- NSThread Helpers to easily run blocks on the main and background threads
- A Speech Service for speech to text.
- UIAlertController Helpers to show with actions and text input
- Image Helpers for things like blurring and resizing
- Animation and Motion Effects Helpers
- A View Controller helper that can recursively determine the visible view controller from anywhere in your application
- A new helper that shows text on screen for a short time, like an Android "Toast"
- Network Reachability Helper
- An Event Counter to track the number of times an event has occurred during the life of an app, or daily.
- Blurred Background Helpers, to present a view over another and blur the background.
- Keyboard Helpers to add an action tool bar and hide the keyboard on click
- TextField subclasses for date and value inputs

Enjoy! Please feel free to fork and contribute to this repo!

## Requirements
ios 7+

## Installation

SeaseAssist is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "SeaseAssist"
```

And import the following Header file
```ruby
#import "SeaseAssist.h"
```

This pod will work if your project uses objective-c or Swift.
- For best results with an objective-c Project, add the SeaseAssist.h import into your .pch file and you will not need to import SeaseAssist into each of your classes that references it.
- For Similiar result with Swift, you should NOT include the use_frameworks! in your pod file and add a bridging header that includes the library. If you must use_frameworks!, then you need to include SeaseAssist in any class that uses its functions.
-- add a new header file to yoour project named ProjectName-Bridging-Header.h
-- add '#import <SeaseAssist/SeaseAssist.h>' to your header file
-- in your Target Build settings -> Swift Compiler Code Generation -> Objective-C Bridging Header, add a reference to the newly created file. Should be [ProjectName/ProjectName-Bridging-Header.h]

## Author

Logan Sease, lsease@gmail.com

## License

SeaseAssist is available under the MIT license. See the LICENSE file for more info.

#UI CLASSES

##CleanButton
A modern button with a nice clean rounded border, an empty background and some text

##GlossyButton
A button with a gradient filled background matching the button's Tint Color

##RoundedView
A View with slightly rounded corners and a thin border.

##DatePickerTextField
Create a UITextField with a Date picker instead of a keyboard

##ValuePickerTextField
A UITextField with a PickerView instead of a keyboard

#SERVICES

##EventCounterService
A class to track events throughout the life of the app, or daily events

```objective-c
+(NSUInteger)addCountForEvent:(NSString*)event count:(NSInteger)add;
+(NSUInteger)addCountForEvent:(NSString*)event;
+(void)resetCountForEvent:(NSString*)event;
+(NSUInteger)checkCountForEvent:(NSString*)event;
+(NSUInteger)checkDailyEventCount:(NSString*)dailyEvent;
+(NSUInteger)addDailyEventCount:(NSString*)dailyEvent;
+(NSUInteger)addCountForDailyEvent:(NSString*)dailyEvent count:(NSInteger)count;
```

##Sound Service
A service to play sounds and maintain a queue

```objective-c
+ (id)sharedService;
+(void)playSoundAtPath:(NSString*)path;
+(void)playSoundAtPath:(NSString*)path withVolume:(float)volume;
+(void)addSoundToQueueAtPath:(NSString*)path;
-(void)pauseQueue;
-(void)resumeQueue;
-(BOOL)isPlaying;
```

##SpeechService
Simple Text to Speech with the Siri API
```objective-c
+ (id)sharedService;
+(BOOL)isSpeaking;
-(void)speakText:(NSString*)text;
```

#NETWORKING

##HTTPRequest
A helper class to make http requests asynchronously in one line without the need for any 3rd party frameworks
```objective-c
+(void)jsonRequestToUrl:(NSString*)urlString withMethod:(NSString*)method withHeaders:(NSDictionary*)headers withParams:(NSDictionary*)params withHandler:(void (^)(NSString* response,NSError * error))handler;

+(void)httpRequestToUrl:(NSString*)urlString  withMethod:(NSString*)method withHeaders:(NSDictionary*)headers withParams:(NSDictionary*)params withHandler:(void (^)(NSString* response,NSError * error))handler;

+(NSString*)addParameters:(NSDictionary*)urlParams toUrl:(NSString*)url;
```

##Reachability Helpers
Find our internet connection status.
```objective-c
GCNetworkReachability
+ (BOOL)connected;
```
#CLASS EXTENSIONS

##Json Serialization and Deserialization

###NSDictionary
```objective-c
-(NSString*)toJsonString;
+(NSDictionary*)fromJsonString:(NSString*)json;
```

###NSArray
```objective-c
-(NSString*)toJsonString;
+(NSArray*)fromJsonString:(NSString*)json;
```
##NSDate Helpers
```objective-c
-(NSDate*)beginningOfWeek;
-(NSDate*)endOfWeek;

-(NSDate*)beginningOfMonth;
-(NSDate*)endOfMonth;

-(NSDate*)beginningOfYear;
-(NSDate*)endOfYear;
-(NSDate*)dateWithCurrentYear;

-(NSString*)dateToStringWithFormat:(NSString*)format;

-(NSDate*)dateAtEndOfDay;
-(NSDate*)dateWithoutTime;
-(NSDate*)timeValue;
-(BOOL)isOnBeforeOrToday;
-(BOOL)isToday;
-(BOOL)isBeforeToday;

-(BOOL)isBetween:(NSDate*)startDate and:(NSDate*)endDate;
-(NSDate*)dateByAdvancingMonths:(NSInteger)monthCount;
-(BOOL)isAfterDate:(NSDate*)secondDate;
-(BOOL)isBeforeDate:(NSDate*)secondDate;
```

##NSMutableArray Helpers
```objective-c
- (void)shuffle;
```

##NSString Helpers
```objective-c
-(NSInteger)occurancesOfString:(NSString*)test;
```

##NSString validation
```objective-c
-(BOOL)isValidEmail;
-(BOOL)isDigitOfLength:(NSInteger)length;
```

##Encryption Helpers
###NSData
```objective-c
-(NSData *) aesEncryptedDataWithKey:(NSData *) key;
-(NSString*)toBase64;
```

###NSString
```objective-c
- (NSData *) sha256;
- (NSString *) stringFromMD5;

//secure a string by adding Key Encryption and then Base 64 Encoding it.
- (NSString*)encryptWithKey:(NSString*)key;
```

##NSThread Helpers
Run blocks in the main or background threads with ease
```objective-c
+(void)mainThread:(void (^)())main;
+(void)backgroundThread:(void (^)())background;
+(void)delay:(float)length code:(void (^)())function;
```

##Device Identifiers
Since apple now longer gives access to device level Identifier information, this is another way to get an Identifier based on a hash of the mac address
```objective-c
- (NSString *) uniqueDeviceIdentifier;
- (NSString *) uniqueGlobalDeviceIdentifier;
```
##Alerts

###MBProgressHUD+Singleton
An extension to MBProgressHUD to show a loading dialog singleton without needing to add it to your view or set it up.
```objective-c
+(void)showWithTitle:(NSString*)title;
+(void)hide;
```

###UIAlertController
Show an alert controller with actions and get notified what action was chosen with a single line
```objective-c
+(void)showAlertWithTitle:(NSString*)title andMessage:(NSString*)message from:(UIViewController*)controller;
+(void)showDialogWithTitle:(NSString*)title andMessage:(NSString*)message from:(UIViewController*)controller andActions:(NSArray<NSString*>*)buttonTitles completionHandler:(void (^)(NSInteger selected))handler;
+(void)showTextEntryDialogWithTitle:(NSString*)title andMessage:(NSString*)message andPlaceHolder:(NSString*)holder from:(UIViewController*)controller completionHandler:(void (^)(NSString* text))handler;
```

###UIAlertView
```objective-c
+(void)showWithTitle:(NSString*)title andMessage:(NSString*)message;
```

###UILabel+Message
Show a quick "Toast" on screen for a desired amount of time
```objective-c
+(void)showMessage:(NSString*)message ofSize:(float)fontSize ofColor:(UIColor*)color inView:(UIView*)view forDuration:(float)seconds;
```

##Images

###UIImage Helpers
```objective-c
//Add a gassian Blur of the desired amount of pixels
-(UIImage*)blurredImage:(float)amount;

//Get an image from a file, but filled with a different fill color.
- (UIImage *)imageWithColor:(UIColor *)color;

//Scale an image.
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
```
###UIImageView Helpers
Set an image from a URL and cache the image locally.
```objective-c
-(void)setImageUrl:(NSString*)urlString;
```
Round an image
```objective-c
-(void)round;
-(UIImage*)clippedToCircle;
```

Set an image from URL to a UIImage View with caching and a default
```objective-c
@interface UIImageView (Networking)
-(void)setImageFromUrl:(NSString*)url withDefault:(UIImage*)defaultImage andRounding:(BOOL)round;
```

##Animation

###UIView+Bounce
Make your UI Feel alive and highlight important views by adding a playful bounce
```objective-c
-(void)bounceFrom:(float)from to:(float)to;
-(void)bounceTo:(float)scale;
-(void)bounce:(BOOL)repeat;
-(void)endBounce;
```

###UIView+MotionEffects
Add cool motion effects that give your app depth by moving as you move your device
```objective-c
-(void)addMotionEffectsWithOffset:(float)offset;
-(void)addVerticalMotionEffectsWithOffset:(float)offset;
-(void)resizeFullScreenViewAndAddMotionEffectsWithOffset:(float)offset;
-(void)resizeHorizontallyAndAddMotionEffectsWithOffset:(float)offset;
```

##View Appearance

###UIView+Rounding
```objective-c
//round the corners
-(void)round:(float)cornerRadius withBorderWidth:(float)width andColor:(UIColor*)color;
-(void)round;

//completely circle the view and optionally add a border.
-(void)circleWithColor:(UIColor*)color width:(float)width;
-(void)circle;
```

###UIButton+Helpers
```objective-c
- (void)makeGlossy;
- (void)makeClean;
-(void)setTitle:(NSString*)title;
```

##Application View Hierarchy
Find the top most view controller from anywhere. Searches recursively through navigation, Tab bar and modal view controllers in your app window
###UIViewController+Top
```objective-c
+(UIViewController*)topViewController;
```

##Blurred Backgrounds
###For use with a Covers Current Context Modal Transition
```objective-c
@interface UIViewController (Blur)
-(UIVisualEffectView*)blurBackground;
-(UIVisualEffectView*)blurBackgroundOfTableView:(UITableView*)tableView;
-(UIVisualEffectView*)darkBlurBackground;
-(UIVisualEffectView*)darkBlurBackgroundOfTableView:(UITableView*)tableView;
@end

@interface UITableViewController (Blur)
-(UIVisualEffectView*)blurBackground;
-(UIVisualEffectView*)darkBlurBackground;
@end
```
###To Present and Blur Without a storyboard
```objective-c
@interface UIViewController (Presentation)
+(void)present:(nonnull UIViewController* )newVC on:(nullable UIViewController*)source;
+(void)present:(nonnull UIViewController* )newVC on:(nullable UIViewController*)source withBlur:(float)blurAmount;
```

##Transition Helpers
```objective-c
-(void)addFadeTransition;

```

##UIDevice system version
```objective-c
+(BOOL)versionGreaterThanOrEqual:(NSString*)version;
```

##Keyboard Helpers
```objective-c
UIView
-(void)hideKeyboardOnClick;
-(UIView*)findFirstResponder;
```

```objective-c
UITextField
-(UIToolbar*)addToolbarWithLeftButton:(NSString*)lTitle withSelector:(SEL)lSelector andRightButton:(NSString*)rTitle withSelector:(SEL)rSelector andTarget:(id)target;
```

##Path Helpers on NSFileManager
```objective-c
+(NSString *)myDocumentsPathForFile:(NSString*)fileName;
+(NSString *)tempPathForFile:(NSString*)fileName;
```


text:
#ifndef DBOX_FILE_H
#define DBOX_FILE_H

/* The file begins with a header followed by zero or more messages:

   <dbox message header>
   <LF>
   <message body>
   <metadata>

   Metadata block begins with DBOX_MAGIC_POST, followed by zero or more lines
   in format <key character><value><LF>. The block ends with an empty line.
   Unknown metadata should be ignored, but preserved when copying.

   There should be no duplicates for the current metadata, but future
   extensions may need them so they should be preserved.
*/
#define DBOX_VERSION 2
#define DBOX_MAGIC_PRE "\001\002"
#define DBOX_MAGIC_POST "\n\001\003\n"

/* prefer flock(). fcntl() locking currently breaks if trying to access the
   same file from multiple mail_storages within same process. that's why we
   fallback to dotlocks. */
#ifdef HAVE_FLOCK
#  define DBOX_FILE_LOCK_METHOD_FLOCK
#endif

struct dbox_file;
struct stat;

enum dbox_header_key {
	/* Must be sizeof(struct dbox_message_header) when appending (hex) */
	DBOX_HEADER_MSG_HEADER_SIZE	= 'M',
	/* Creation UNIX timestamp (hex) */
	DBOX_HEADER_CREATE_STAMP	= 'C',

	/* metadata used by old Dovecot versions */
	DBOX_HEADER_OLDV1_APPEND_OFFSET	= 'A'
};

enum dbox_metadata_key {
	/* Globally unique identifier for the message. Preserved when
	   copying. */
	DBOX_METADATA_GUID		= 'G',
	/* POP3 UIDL overriding the default format */
	DBOX_METADATA_POP3_UIDL		= 'P',
	/* Received UNIX timestamp in hex */
	DBOX_METADATA_RECEIVED_TIME	= 'R',
	/* Physical message size in hex. Necessary only if it differs from
	   the dbox_message_header.message_size_hex, for example because the
	   message is compressed. */
	DBOX_METADATA_PHYSICAL_SIZE	= 'Z',
	/* Virtual message size in hex (line feeds counted as CRLF) */
	DBOX_METADATA_VIRTUAL_SIZE	= 'V',
	/* Pointer to external message data. Format is:
	   1*(<start offset> <byte count> <options> <ref>) */
	DBOX_METADATA_EXT_REF		= 'X',
	/* Mailbox name where this message was originally saved to.
	   When rebuild finds a message whose mailbox is unknown, it's
	   placed to this mailbox. */
	DBOX_METADATA_ORIG_MAILBOX	= 'B',

	/* metadata used by old Dovecot versions */
	DBOX_METADATA_OLDV1_EXPUNGED	= 'E',
	DBOX_METADATA_OLDV1_FLAGS	= 'F',
	DBOX_METADATA_OLDV1_KEYWORDS	= 'K',
	DBOX_METADATA_OLDV1_SAVE_TIME	= 'S',
	DBOX_METADATA_OLDV1_SPACE	= ' '
};

enum dbox_message_type {
	/* Normal message */
	DBOX_MESSAGE_TYPE_NORMAL	= 'N'
};

struct dbox_message_header {
	unsigned char magic_pre[2];
	unsigned char type;
	unsigned char space1;
	unsigned char oldv1_uid_hex[8];
	unsigned char space2;
	unsigned char message_size_hex[16];
	/* <space reserved for future extensions, LF is always last> */
	unsigned char save_lf;
};

struct dbox_metadata_header {
	unsigned char magic_post[sizeof(DBOX_MAGIC_POST)-1];
};

struct dbox_file {
	struct dbox_storage *storage;
	int refcount;

	time_t create_time;
	unsigned int file_version;
	unsigned int file_header_size;
	unsigned int msg_header_size;

	const char *cur_path;
	char *primary_path, *alt_path;
	int fd;
	struct istream *input;
#ifdef DBOX_FILE_LOCK_METHOD_FLOCK
	struct file_lock *lock;
#else
	struct dotlock *lock;
#endif

	uoff_t cur_offset;
	uoff_t cur_physical_size;

	/* Metadata for the currently seeked metadata block. */
	pool_t metadata_pool;
	ARRAY(const char *) metadata;
	uoff_t metadata_read_offset;

	unsigned int appending:1;
	unsigned int deleted:1;
	unsigned int corrupted:1;
};

struct dbox_file_append_context {
	struct dbox_file *file;

	uoff_t first_append_offset, last_checkpoint_offset, last_flush_offset;
	struct ostream *output;
};

#define dbox_file_is_open(file) ((file)->fd != -1)
#define dbox_file_is_in_alt(file) ((file)->cur_path == (file)->alt_path)

void dbox_file_init(struct dbox_file *file);
void dbox_file_unref(struct dbox_file **file);

/* Open the file. Returns 1 if ok, 0 if file header is corrupted, -1 if error.
   If file is deleted, deleted_r=TRUE and 1 is returned. */
int dbox_file_open(struct dbox_file *file, bool *deleted_r);
/* Try to open file only from primary path. */
int dbox_file_open_primary(struct dbox_file *file, bool *notfound_r);
/* Close the file handle from the file, but don't free it. */
void dbox_file_close(struct dbox_file *file);

/* fstat() or stat() the file. If file is already deleted, fails with
   errno=ENOENT. */
int dbox_file_stat(struct dbox_file *file, struct stat *st_r);

/* Try to lock the dbox file. Returns 1 if ok, 0 if already locked by someone
   else, -1 if error. */
int dbox_file_try_lock(struct dbox_file *file);
void dbox_file_unlock(struct dbox_file *file);

/* Seek to given offset in file. Returns 1 if ok/expunged, 0 if file/offset is
   corrupted, -1 if I/O error. */
int dbox_file_seek(struct dbox_file *file, uoff_t offset);
/* Start seeking at the beginning of the file. */
void dbox_file_seek_rewind(struct dbox_file *file);
/* Seek to next message after current one. If there are no more messages,
   returns 0 and last_r is set to TRUE. Returns 1 if ok, 0 if file is
   corrupted, -1 if I/O error. */
int dbox_file_seek_next(struct dbox_file *file, uoff_t *offset_r, bool *last_r);

/* Start appending to dbox file */
struct dbox_file_append_context *dbox_file_append_init(struct dbox_file *file);
/* Finish writing appended mails. */
int dbox_file_append_commit(struct dbox_file_append_context **ctx);
/* Truncate appended mails. */
void dbox_file_append_rollback(struct dbox_file_append_context **ctx);
/* Get output stream for appending a new message. Returns 1 if ok, 0 if file
   can't be appended to (old file version or corruption) or -1 if error. */
int dbox_file_get_append_stream(struct dbox_file_append_context *ctx,
				struct ostream **output_r);
/* Call after message has been fully saved. If this isn't done, the writes
   since the last checkpoint are truncated. */
void dbox_file_append_checkpoint(struct dbox_file_append_context *ctx);
/* Flush output buffer. */
int dbox_file_append_flush(struct dbox_file_append_context *ctx);

/* Read current message's metadata. Returns 1 if ok, 0 if metadata is
   corrupted, -1 if I/O error. */
int dbox_file_metadata_read(struct dbox_file *file);
/* Return wanted metadata value, or NULL if not found. */
const char *dbox_file_metadata_get(struct dbox_file *file,
				   enum dbox_metadata_key key);

/* Returns DBOX_METADATA_PHYSICAL_SIZE if set, otherwise physical size from
   header. They differ only for e.g. compressed mails. */
uoff_t dbox_file_get_plaintext_size(struct dbox_file *file);

/* Fix a broken dbox file by rename()ing over it with a fixed file. Everything
   before start_offset is assumed to be valid and is simply copied. The file
   is reopened afterwards. Returns 1 if ok, 0 if the resulting file has no
   mails and was deleted, -1 if I/O error. */
int dbox_file_fix(struct dbox_file *file, uoff_t start_offset);
/* Delete the given dbox file. Returns 1 if deleted, 0 if file wasn't found
   or -1 if error. */
int dbox_file_unlink(struct dbox_file *file);

/* Fill dbox_message_header with given size. */
void dbox_msg_header_fill(struct dbox_message_header *dbox_msg_hdr,
			  uoff_t message_size);

void dbox_file_set_syscall_error(struct dbox_file *file, const char *function);
void dbox_file_set_corrupted(struct dbox_file *file, const char *reason, ...)
	ATTR_FORMAT(2, 3);

/* private: */
const char *dbox_generate_tmp_filename(void);
void dbox_file_free(struct dbox_file *file);
int dbox_file_header_write(struct dbox_file *file, struct ostream *output);
int dbox_file_read_mail_header(struct dbox_file *file, uoff_t *physical_size_r);
int dbox_file_metadata_skip_header(struct dbox_file *file);

#endif


text:
<?php

declare(strict_types=1);

namespace Money\Formatter;

use Money\Currencies;
use Money\Money;
use Money\MoneyFormatter;
use NumberFormatter;

use function assert;
use function str_pad;
use function strlen;
use function substr;

/**
 * Formats a Money object using intl extension.
 */
final class IntlMoneyFormatter implements MoneyFormatter
{
    private NumberFormatter $formatter;

    private Currencies $currencies;

    public function __construct(NumberFormatter $formatter, Currencies $currencies)
    {
        $this->formatter  = $formatter;
        $this->currencies = $currencies;
    }

    public function format(Money $money): string
    {
        $valueBase = $money->getAmount();
        $negative  = $valueBase[0] === '-';

        if ($negative) {
            $valueBase = substr($valueBase, 1);
        }

        $subunit     = $this->currencies->subunitFor($money->getCurrency());
        $valueLength = strlen($valueBase);

        if ($valueLength > $subunit) {
            $formatted     = substr($valueBase, 0, $valueLength - $subunit);
            $decimalDigits = substr($valueBase, $valueLength - $subunit);

            if (strlen($decimalDigits) > 0) {
                $formatted .= '.' . $decimalDigits;
            }
        } else {
            $formatted = '0.' . str_pad('', $subunit - $valueLength, '0') . $valueBase;
        }

        if ($negative) {
            $formatted = '-' . $formatted;
        }

        $formatted = $this->formatter->formatCurrency((float) $formatted, $money->getCurrency()->getCode());

        assert(! empty($formatted));

        return $formatted;
    }
}


text:
<?php

namespace Enzyme\Axiom\Atoms;

interface AtomInterface
{
    /**
     * Get the underlying value associated with this atom.
     *
     * @return mixed
     */
    public function getValue();
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>{{format}} parsing tests</title>

    <link rel="stylesheet" href="../../../css/testsuite.css">
    <link rel="stylesheet" href="../../../prettify.css">

{{format}} parsing tests ‐ change logs

        {{#each description}}

{{this}}

        {{/each}}

Change log:

      {{#each history}}

            {{properties.name}} ‐
            <time class="dt-published" datetime="{{properties.published}}">{{publishedDateString}}</time>
            by {{properties.author}}

      {{/each}}

Contributors:

     {{#each author}}

           {{properties.name}}

     {{/each}}

        All content and code is released into the public domain


text:
namespace SystemDot.MessageRouteInspector.Server.Domain
{
    using System.Collections.Generic;

    public class MessageRouteHierarchy : PublishingEntity
    {
        readonly MessageRoute route;
        readonly MessageRouteId routeId;
        readonly Stack<MessageRouteBranch> hierarchy = new Stack<MessageRouteBranch>();
        int openBranchCount;

        public MessageRouteHierarchy(MessageRoute route, MessageRouteId routeId) : base(route)
        {
            this.route = route;
            this.routeId = routeId;
        }

        public void StartBranch(string messageName, MessageType messageType)
        {
            CompletePreviousBranch();

            openBranchCount++;

            if (hierarchy.Count > 0)
            {
                hierarchy.Pop();
            }

            hierarchy.Push(new MessageRouteBranch(route, routeId, messageName, messageType));
        }

        public void Fail(string failureName)
        {
            StartBranch(failureName, MessageType.Failure);
            CompleteAllBranches();
        }

        void CompletePreviousBranch()
        {
            if (hierarchy.Count > 0)
            {
                CompleteBranch();
            }
        }

        public void EndBranch()
        {
            openBranchCount--;
            hierarchy.Peek().End();

            if (IsComplete())
            {
                CompleteBranch();
            }
        }

        public bool IsComplete()
        {
            return openBranchCount == 0;
        }

        void CompleteBranch()
        {
            hierarchy.Peek().Complete();
        }

        void CompleteAllBranches()
        {
            hierarchy.Peek().Complete(openBranchCount);
            openBranchCount = 0;
        }
    }
}


text:
<?php

namespace backend\models;

use Yii;

use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\behaviors\BlameableBehavior;

/**
 * This is the model class for table "tb_training_schedule_trainer".
 *

 * @property integer $id
 * @property integer $tb_training_schedule_id
 * @property integer $tb_trainer_id
 * @property integer $ref_trainer_type_id
 * @property integer $cost
 * @property integer $hours
 * @property string $reason
 * @property integer $status
 * @property string $created
 * @property integer $createdBy
 * @property string $modified
 * @property integer $modifiedBy
 * @property string $deleted
 * @property integer $deletedBy
 *
 * @property TrainingSchedule $tbTrainingSchedule
 * @property Trainer $tbTrainer
 * @property TrainerType $refTrainerType
 * @property TrainingScheduleTrainerAttendance[] $trainingScheduleTrainerAttendances
 */
class TrainingScheduleTrainer extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tb_training_schedule_trainer';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                        \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created','modified'],
                        \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => 'modified',
                ],
                'value' => new Expression('NOW()'),
            ],
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'attributes' => [
                        \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['createdBy','modifiedBy'],
                        \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => 'modifiedBy',
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['tb_training_schedule_id', 'tb_trainer_id', 'ref_trainer_type_id'], 'required'],
            [['tb_training_schedule_id', 'tb_trainer_id', 'ref_trainer_type_id', 'cost', 'status', 'createdBy', 'modifiedBy', 'deletedBy'], 'integer'],
            [['created', 'modified', 'deleted'], 'safe'],
            [['reason'], 'string', 'max' => 255],
            [['tb_training_schedule_id', 'tb_trainer_id'], 'unique', 'targetAttribute' => ['tb_training_schedule_id', 'tb_trainer_id'], 'message' => 'The combination of Tb Training Schedule ID and Tb Trainer ID has already been taken.']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'tb_training_schedule_id' => 'Tb Training Schedule ID',
            'tb_trainer_id' => 'Tb Trainer ID',
            'ref_trainer_type_id' => 'Ref Trainer Type ID',
            'cost' => 'Cost',
            'hours' => 'Hours',
            'reason' => 'Reason',
            'status' => 'Status',
            'created' => 'Created',
            'createdBy' => 'Created By',
            'modified' => 'Modified',
            'modifiedBy' => 'Modified By',
            'deleted' => 'Deleted',
            'deletedBy' => 'Deleted By',
        ];
    }
	    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTrainingSchedule()
    {
        return $this->hasOne(TrainingSchedule::className(), ['id' => 'tb_training_schedule_id']);
    }
	    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTrainer()
    {
        return $this->hasOne(Trainer::className(), ['id' => 'tb_trainer_id']);
    }
	    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTrainerType()
    {
        return $this->hasOne(TrainerType::className(), ['id' => 'ref_trainer_type_id']);
    }
	    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTrainingScheduleTrainerAttendances()
    {
        return $this->hasMany(TrainingScheduleTrainerAttendance::className(), ['tb_training_schedule_trainer_id' => 'id']);
    }
}


text:
/*
Package util provides utility functions used by other packages.
*/
package util

import (
	"errors"
	"io"
	"os"
	"os/exec"
	"strings"
)

// ErrDetached is returned if it looks like a Git repo is in a
// detached state.
var ErrGitDetached = errors.New("Your repo looks like it is in a detached state")

// Cmd creates an exec.Cmd to run in the given directory.
func Cmd(dir string, command string) *exec.Cmd {
	parts := strings.Split(command, " ")
	cmd := exec.Command(parts[0], parts[1:]...)
	cmd.Dir = dir
	return cmd
}

// CopyFile copies the contents of one file to another file. If the
// dst file already exists, its contents will be replaced.
func CopyFile(src, dst string) (err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return
	}
	defer func() {
		closeError := dstFile.Close()
		if err == nil {
			err = closeError
		}
	}()

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		// TODO: Not sure how to add test coverage for this line
		return
	}
	err = dstFile.Sync()
	return
}

// GitBranch returns the current git branch for the given directory
func GitBranch(dir string) (branch string, err error) {
	cmd := Cmd(dir, "git rev-parse --abbrev-ref HEAD")
	out, err := cmd.Output()
	if err != nil {
		return
	}
	branch = strings.TrimSpace(string(out))
	if branch == "HEAD" {
		err = ErrGitDetached
	}
	return
}

// RunAll runs all the given commands in the given directory, and
// returns a list of CmdOutputs.
func RunAll(dir string, commands ...string) ([]*CmdOutput, error) {
	return RunAllLog(NilLogger, dir, commands...)
}

// RunAllLog is the same as RunAll but it logs commands as they are run.
func RunAllLog(log Logger, dir string, commands ...string) ([]*CmdOutput, error) {
	outputs := make([]*CmdOutput, len(commands))
	var i int
	var command string
	var bytes []byte
	var err error
	for i, command = range commands {
		command = strings.TrimSpace(command)
		log.Println("$ " + command)
		bytes, err = Cmd(dir, command).Output()
		out := string(bytes)
		log.Debugln(out)
		outputs[i] = &CmdOutput{command, strings.TrimSpace(out), err}
		if err != nil {
			break
		}
	}
	if len(outputs) > 0 {
		return outputs[0 : i+1], err
	}
	return outputs, err
}

// CmdOutput represents the output of a bash command.
type CmdOutput struct {
	Cmd    string
	Output string
	Err    error
}