text:
package com.google.cloud.dataproc.v1;

import static com.google.cloud.dataproc.v1.AutoscalingPolicyServiceClient.ListAutoscalingPoliciesPagedResponse;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.common.collect.Lists;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@Generated("by gapic-generator-java")
public class AutoscalingPolicyServiceClientTest {
  private static MockAutoscalingPolicyService mockAutoscalingPolicyService;
  private static MockServiceHelper mockServiceHelper;
  private LocalChannelProvider channelProvider;
  private AutoscalingPolicyServiceClient client;

  @BeforeClass
  public static void startStaticServer() {
    mockAutoscalingPolicyService = new MockAutoscalingPolicyService();
    mockServiceHelper =
        new MockServiceHelper(
            UUID.randomUUID().toString(),
            Arrays.<MockGrpcService>asList(mockAutoscalingPolicyService));
    mockServiceHelper.start();
  }

  @AfterClass
  public static void stopServer() {
    mockServiceHelper.stop();
  }

  @Before
  public void setUp() throws IOException {
    mockServiceHelper.reset();
    channelProvider = mockServiceHelper.createChannelProvider();
    AutoscalingPolicyServiceSettings settings =
        AutoscalingPolicyServiceSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(NoCredentialsProvider.create())
            .build();
    client = AutoscalingPolicyServiceClient.create(settings);
  }

  @After
  public void tearDown() throws Exception {
    client.close();
  }

  @Test
  public void createAutoscalingPolicyTest() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
    AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();

    AutoscalingPolicy actualResponse = client.createAutoscalingPolicy(parent, policy);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAutoscalingPolicyRequest actualRequest =
        ((CreateAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertEquals(policy, actualRequest.getPolicy());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void createAutoscalingPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
      AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();
      client.createAutoscalingPolicy(parent, policy);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void createAutoscalingPolicyTest2() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    RegionName parent = RegionName.of("[PROJECT]", "[REGION]");
    AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();

    AutoscalingPolicy actualResponse = client.createAutoscalingPolicy(parent, policy);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAutoscalingPolicyRequest actualRequest =
        ((CreateAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertEquals(policy, actualRequest.getPolicy());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void createAutoscalingPolicyExceptionTest2() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      RegionName parent = RegionName.of("[PROJECT]", "[REGION]");
      AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();
      client.createAutoscalingPolicy(parent, policy);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void createAutoscalingPolicyTest3() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    String parent = "parent-995424086";
    AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();

    AutoscalingPolicy actualResponse = client.createAutoscalingPolicy(parent, policy);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateAutoscalingPolicyRequest actualRequest =
        ((CreateAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(parent, actualRequest.getParent());
    Assert.assertEquals(policy, actualRequest.getPolicy());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void createAutoscalingPolicyExceptionTest3() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      String parent = "parent-995424086";
      AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();
      client.createAutoscalingPolicy(parent, policy);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void updateAutoscalingPolicyTest() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();

    AutoscalingPolicy actualResponse = client.updateAutoscalingPolicy(policy);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    UpdateAutoscalingPolicyRequest actualRequest =
        ((UpdateAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(policy, actualRequest.getPolicy());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void updateAutoscalingPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      AutoscalingPolicy policy = AutoscalingPolicy.newBuilder().build();
      client.updateAutoscalingPolicy(policy);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void getAutoscalingPolicyTest() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    AutoscalingPolicyName name =
        AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
            "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]");

    AutoscalingPolicy actualResponse = client.getAutoscalingPolicy(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetAutoscalingPolicyRequest actualRequest =
        ((GetAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(name.toString(), actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void getAutoscalingPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      AutoscalingPolicyName name =
          AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
              "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]");
      client.getAutoscalingPolicy(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void getAutoscalingPolicyTest2() throws Exception {
    AutoscalingPolicy expectedResponse =
        AutoscalingPolicy.newBuilder()
            .setId("id3355")
            .setName(
                AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
                        "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]")
                    .toString())
            .setWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .setSecondaryWorkerConfig(InstanceGroupAutoscalingPolicyConfig.newBuilder().build())
            .putAllLabels(new HashMap<String, String>())
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    String name = "name3373707";

    AutoscalingPolicy actualResponse = client.getAutoscalingPolicy(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetAutoscalingPolicyRequest actualRequest =
        ((GetAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void getAutoscalingPolicyExceptionTest2() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      String name = "name3373707";
      client.getAutoscalingPolicy(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void listAutoscalingPoliciesTest() throws Exception {
    AutoscalingPolicy responsesElement = AutoscalingPolicy.newBuilder().build();
    ListAutoscalingPoliciesResponse expectedResponse =
        ListAutoscalingPoliciesResponse.newBuilder()
            .setNextPageToken("")
            .addAllPolicies(Arrays.asList(responsesElement))
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");

    ListAutoscalingPoliciesPagedResponse pagedListResponse = client.listAutoscalingPolicies(parent);

    List<AutoscalingPolicy> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getPoliciesList().get(0), resources.get(0));

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ListAutoscalingPoliciesRequest actualRequest =
        ((ListAutoscalingPoliciesRequest) actualRequests.get(0));

    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void listAutoscalingPoliciesExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
      client.listAutoscalingPolicies(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void listAutoscalingPoliciesTest2() throws Exception {
    AutoscalingPolicy responsesElement = AutoscalingPolicy.newBuilder().build();
    ListAutoscalingPoliciesResponse expectedResponse =
        ListAutoscalingPoliciesResponse.newBuilder()
            .setNextPageToken("")
            .addAllPolicies(Arrays.asList(responsesElement))
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    RegionName parent = RegionName.of("[PROJECT]", "[REGION]");

    ListAutoscalingPoliciesPagedResponse pagedListResponse = client.listAutoscalingPolicies(parent);

    List<AutoscalingPolicy> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getPoliciesList().get(0), resources.get(0));

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ListAutoscalingPoliciesRequest actualRequest =
        ((ListAutoscalingPoliciesRequest) actualRequests.get(0));

    Assert.assertEquals(parent.toString(), actualRequest.getParent());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void listAutoscalingPoliciesExceptionTest2() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      RegionName parent = RegionName.of("[PROJECT]", "[REGION]");
      client.listAutoscalingPolicies(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void listAutoscalingPoliciesTest3() throws Exception {
    AutoscalingPolicy responsesElement = AutoscalingPolicy.newBuilder().build();
    ListAutoscalingPoliciesResponse expectedResponse =
        ListAutoscalingPoliciesResponse.newBuilder()
            .setNextPageToken("")
            .addAllPolicies(Arrays.asList(responsesElement))
            .build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    String parent = "parent-995424086";

    ListAutoscalingPoliciesPagedResponse pagedListResponse = client.listAutoscalingPolicies(parent);

    List<AutoscalingPolicy> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getPoliciesList().get(0), resources.get(0));

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ListAutoscalingPoliciesRequest actualRequest =
        ((ListAutoscalingPoliciesRequest) actualRequests.get(0));

    Assert.assertEquals(parent, actualRequest.getParent());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void listAutoscalingPoliciesExceptionTest3() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      String parent = "parent-995424086";
      client.listAutoscalingPolicies(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void deleteAutoscalingPolicyTest() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    AutoscalingPolicyName name =
        AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
            "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]");

    client.deleteAutoscalingPolicy(name);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    DeleteAutoscalingPolicyRequest actualRequest =
        ((DeleteAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(name.toString(), actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void deleteAutoscalingPolicyExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      AutoscalingPolicyName name =
          AutoscalingPolicyName.ofProjectLocationAutoscalingPolicyName(
              "[PROJECT]", "[LOCATION]", "[AUTOSCALING_POLICY]");
      client.deleteAutoscalingPolicy(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void deleteAutoscalingPolicyTest2() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    mockAutoscalingPolicyService.addResponse(expectedResponse);

    String name = "name3373707";

    client.deleteAutoscalingPolicy(name);

    List<AbstractMessage> actualRequests = mockAutoscalingPolicyService.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    DeleteAutoscalingPolicyRequest actualRequest =
        ((DeleteAutoscalingPolicyRequest) actualRequests.get(0));

    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void deleteAutoscalingPolicyExceptionTest2() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockAutoscalingPolicyService.addException(exception);

    try {
      String name = "name3373707";
      client.deleteAutoscalingPolicy(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }
}


text:
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TemplateHaskell       #-}
module Stack.Upgrade (upgrade) where

import           Control.Monad               (when)
import           Control.Monad.Catch
import           Control.Monad.IO.Class
import           Control.Monad.Logger
import           Control.Monad.Reader        (MonadReader, asks)
import           Control.Monad.Trans.Control
import           Data.Foldable               (forM_)
import qualified Data.Map                    as Map
import           Data.Maybe                  (isNothing)
import           Data.Monoid.Extra
import qualified Data.Monoid
import qualified Data.Text as T
import           Lens.Micro                  (set)
import           Network.HTTP.Client.Conduit (HasHttpManager)
import           Path
import           Path.IO
import qualified Paths_stack as Paths
import           Stack.Build
import           Stack.Config
import           Stack.Fetch
import           Stack.PackageIndex
import           Stack.Setup
import           Stack.Types
import           Stack.Types.Internal
import           Stack.Types.StackT
import           System.Process              (readProcess)
import           System.Process.Run

upgrade :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, MonadLogger m, HasTerminal env, HasReExec env, HasLogLevel env, MonadBaseControl IO m)
        => Maybe String -- ^ git repository to use
        -> Maybe AbstractResolver
        -> Maybe String -- ^ git hash at time of building, if known
        -> m ()
upgrade gitRepo mresolver builtHash =
  withSystemTempDir "stack-upgrade" $ \tmp -> do
    menv <- getMinimalEnvOverride
    mdir <- case gitRepo of
      Just repo -> do
        remote <- liftIO $ readProcess "git" ["ls-remote", repo, "master"] []
        let latestCommit = head . words $ remote
        when (isNothing builtHash) $
            $logWarn $ "Information about the commit this version of stack was "
                    <> "built from is not available due to how it was built. "
                    <> "Will continue by assuming an upgrade is needed "
                    <> "because we have no information to the contrary."
        if builtHash == Just latestCommit
            then do
                $logInfo "Already up-to-date, no upgrade required"
                return Nothing
            else do
                $logInfo "Cloning stack"
                -- NOTE: "--recursive" was added after v1.0.0 (and before the
                -- next release).  This means that we can't use submodules in
                -- the stack repo until we're comfortable with "stack upgrade
                -- --git" not working for earlier versions.
                let args = [ "clone", repo , "stack", "--depth", "1", "--recursive"]
                runCmd (Cmd (Just tmp) "git" menv args) Nothing
                return $ Just $ tmp </> $(mkRelDir "stack")
      Nothing -> do
        updateAllIndices menv
        caches <- getPackageCaches
        let latest = Map.fromListWith max
                   $ map toTuple
                   $ Map.keys

                   -- Mistaken upload to Hackage, just ignore it
                   $ Map.delete (PackageIdentifier
                        $(mkPackageName "stack")
                        $(mkVersion "9.9.9"))

                     caches
        case Map.lookup $(mkPackageName "stack") latest of
            Nothing -> error "No stack found in package indices"
            Just version | version <= fromCabalVersion Paths.version -> do
                $logInfo "Already at latest version, no upgrade required"
                return Nothing
            Just version -> do
                let ident = PackageIdentifier $(mkPackageName "stack") version
                paths <- unpackPackageIdents menv tmp Nothing
                    -- accept latest cabal revision by not supplying a Git SHA
                    $ Map.singleton ident Nothing
                case Map.lookup ident paths of
                    Nothing -> error "Stack.Upgrade.upgrade: invariant violated, unpacked directory not found"
                    Just path -> return $ Just path

    config <- asks getConfig
    forM_ mdir $ \dir -> do
        bconfig <- runInnerStackLoggingT $ do
            lc <- loadConfig
                (configConfigMonoid config <> Data.Monoid.mempty
                    { configMonoidInstallGHC = First (Just True)
                    })
                mresolver
                (Just $ dir </> $(mkRelFile "stack.yaml"))
            lcLoadBuildConfig lc Nothing
        envConfig1 <- runInnerStackT bconfig $ setupEnv $ Just $
            "Try rerunning with --install-ghc to install the correct GHC into " <>
            T.pack (toFilePath (configLocalPrograms config))
        runInnerStackT (set (envConfigBuildOpts.buildOptsInstallExes) True envConfig1) $
            build (const $ return ()) Nothing defaultBuildOptsCLI
                { boptsCLITargets = ["stack"]
                }

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.jbpm</groupId>
    <artifactId>jbpm-case-mgmt</artifactId>
    <version>7.5.0-SNAPSHOT</version>
  </parent>
  <artifactId>jbpm-case-mgmt-api</artifactId>

  <name>jBPM :: Case Management API</name>
  <description>jBPM Case Management API</description>

   <dependencies>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-internal</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jbpm</groupId>
      <artifactId>jbpm-services-api</artifactId>
    </dependency>
  </dependencies>
</project>


text:
#ifndef PPAPI_THUNK_PPB_BROWSER_FONT_SINGLETON_API_H_
#define PPAPI_THUNK_PPB_BROWSER_FONT_SINGLETON_API_H_

#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/shared_impl/singleton_resource_id.h"

namespace ppapi {
namespace thunk {

class PPB_BrowserFont_Singleton_API {
 public:
  virtual ~PPB_BrowserFont_Singleton_API() {}

  virtual PP_Var GetFontFamilies(PP_Instance instance) = 0;

  static const SingletonResourceID kSingletonResourceID =
      BROWSER_FONT_SINGLETON_ID;
};

}  // namespace thunk
}  // namespace ppapi

#endif  // PPAPI_THUNK_PPB_BROWSER_FONT_SINGLETON_API_H_


text:
namespace TheCollection.Domain.Tea {
    using System.ComponentModel.DataAnnotations;
    using Newtonsoft.Json;

    public class Dashboard<T> {
        public Dashboard(string id, string userId, DashBoardTypes dashBoardType, T data) {
            Id = id;
            UserId = userId;
            DashboardType = dashBoardType;
            Data = data;
        }

        [Key]
        [JsonProperty(PropertyName = "id")]
        public string Id { get; }

        [JsonProperty(PropertyName = "userid")]
        public string UserId { get; }

        [JsonProperty(PropertyName = "dashboardtype")]
        public DashBoardTypes DashboardType { get; }

        [JsonProperty(PropertyName = "data")]
        public T Data { get; }
    }
}


text:
#ifndef SU_VECTOR_H
/** Defined when <sofia-sip/su_vector.h> has been included. */
#define SU_VECTOR_H

/**@file sofia-sip/su_vector.h
 * @brief Vector interface
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 *
 * @date Created: Fri Sep 27 14:31:15 2002 ppessi
 */

#ifndef SU_ALLOC_H
#include <sofia-sip/su_alloc.h>
#endif

SOFIA_BEGIN_DECLS

typedef struct su_vector_s su_vector_t;
typedef void (* su_free_func_t) (void *data);

/** Create a vector. */
SU_DLL su_vector_t *su_vector_create(su_home_t *home, su_free_func_t free_f)
     __attribute__((__malloc__));

/** Destroy a vector. */
SU_DLL void su_vector_destroy(su_vector_t *);

/** Insert an item to vector. */
SU_DLL int su_vector_insert(su_vector_t *vector, usize_t index, void *item);

SU_DLL int su_vector_remove(su_vector_t *vector, usize_t index);

/** Append a item to vector. */
SU_DLL int su_vector_append(su_vector_t *, void *item);

/** Get a numbered item from vector. */
SU_DLL void *su_vector_item(su_vector_t const *, usize_t i);

/** Get number of items in vector. */
SU_DLL usize_t su_vector_len(su_vector_t const *l);

SU_DLL int su_vector_empty(su_vector_t *vector);
SU_DLL int su_vector_is_empty(su_vector_t const *vector);

#if SU_HAVE_INLINE
su_inline
su_home_t *su_vector_home(su_vector_t *s)
{
  return (su_home_t *)s;
}
#else
#define su_vector_home(s) ((su_home_t *)(s))
#endif

/** Get an array of pointers from the vector. */
SU_DLL void **su_vector_get_array(su_vector_t *)
     __attribute__((__malloc__));

/** Free the array */
SU_DLL void su_vector_free_array(su_vector_t *, void *array[]);

SOFIA_END_DECLS

#endif /* !defined SU_VECTOR_H */


text:
#import "FBIntegrationTestCase.h"
#import "FBMathUtils.h"
#import "XCElementSnapshot+FBHitpoint.h"
#import "XCUIElement.h"
#import "XCUIElement+FBUtilities.h"

@interface XCElementSnapshotHitPoint : FBIntegrationTestCase
@end

@implementation XCElementSnapshotHitPoint

- (void)testAccessibilityActivationPoint
{
  [self launchApplication];
  [self goToAttributesPage];
  XCUIElement *element = self.testedApplication.buttons[@"not_accessible"];
  XCTAssertTrue(FBPointFuzzyEqualToPoint(element.fb_lastSnapshot.fb_hitPoint, CGPointMake(200, 220), 0.1));
}

@end


text:
/* ************************************************************************* */
/* elina_scalar.h: scalars */
/* ************************************************************************* */

#ifndef _ELINA_SCALAR_H_
#define _ELINA_SCALAR_H_

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "gmp.h"
#include "mpfr.h"

#include "elina_config.h"

#ifdef __cplusplus
extern "C" {
#endif

/* ********************************************************************** */
/* I. Datatypes  */
/* ********************************************************************** */

typedef enum elina_scalar_discr_t {
  ELINA_SCALAR_DOUBLE, /* double-precision floating-point number */
  ELINA_SCALAR_MPQ,    /* GMP arbitrary precision rational */
  ELINA_SCALAR_MPFR,   /* MPFR floating-point number */
} elina_scalar_discr_t;

typedef struct elina_scalar_t {
  elina_scalar_discr_t discr;
  union {
    double dbl;
    mpq_ptr mpq; /* +infty coded by 1/0, -infty coded by -1/0 */
    mpfr_ptr mpfr;
  } val;
} elina_scalar_t;

/* ********************************************************************** */
/* II. Operations  */
/* ********************************************************************** */

/* ====================================================================== */
/* Basics */
/* ====================================================================== */

elina_scalar_t* elina_scalar_alloc(void);
  /* Allocates a scalar, of default type DOUBLE (the most economical) */
void elina_scalar_free(elina_scalar_t* scalar);
  /* Free a scalar */
void elina_scalar_reinit(elina_scalar_t* scalar, elina_scalar_discr_t d);
  /* Change the type of an already allocated scalar
     (mainly for internal use */

void elina_scalar_print(elina_scalar_t* a);
void elina_scalar_fprint(FILE* stream, elina_scalar_t* a);
  /* Printing */

extern int elina_scalar_print_prec;
  /* Number of significant digits to print for floating-point numbers.
     Defaults to 20.
   */

void elina_scalar_swap(elina_scalar_t* a, elina_scalar_t* b);
  /* Exchange */

/* ====================================================================== */
/* Assignments */
/* ====================================================================== */

void elina_scalar_set(elina_scalar_t* scalar, elina_scalar_t* scalar2);
  /* Assignment */
void elina_scalar_set_mpq(elina_scalar_t* scalar, mpq_t mpq);
void elina_scalar_set_int(elina_scalar_t* scalar, long int i);
void elina_scalar_set_frac(elina_scalar_t* scalar, long int i, unsigned long int j);
  /* Change the type of scalar to MPQ and initialize it resp. with
     - mpq
     - integer i
     - rational i/j, assuming j!=0
  */
void elina_scalar_set_double(elina_scalar_t* scalar, double k);
  /* Change the type of scalar to DOUBLE and initialize it with k. */
void elina_scalar_set_mpfr(elina_scalar_t* scalar, mpfr_t mpfr);
  /* Change the type of scalar to MPFR and initialize it with mpfr.
     The precision of the scalar is changed to match that of mpfr. */
void elina_scalar_set_infty(elina_scalar_t* scalar, int sgn);
  /* Assignment to sgn*infty. Keep the type of the scalar.
     If sgn == 0, set to zero. */

/* ====================================================================== */
/* Combined allocation and assignment */
/* ====================================================================== */

elina_scalar_t* elina_scalar_alloc_set(elina_scalar_t* scalar2);
elina_scalar_t* elina_scalar_alloc_set_mpq(mpq_t mpq);
  /* Allocate an MPQ scalar and initialize it with mpq */
elina_scalar_t* elina_scalar_alloc_set_double(double k);
  /* Allocate an DOUBLE scalar and initialize it with k. */
elina_scalar_t* elina_scalar_alloc_set_mpfr(mpfr_t mpfr);
  /* Allocate an MPFR scalar and initialize it with mpfr.
     The precisio of the scalar matches that of mpfr. */

/* ====================================================================== */
/* Conversions */
/* ====================================================================== */

/* For the two next functions, the returned value is zero if conversion is
   exact, positive if the result is greater, negative if it is lower. */

int elina_mpq_set_scalar(mpq_t mpq, elina_scalar_t* scalar, mp_rnd_t round);
  /* Assign mpq with the value of scalar,
     possibly converting from another type.
     Currently, round is not needed, as the conversion is exact */
int elina_double_set_scalar(double* k, elina_scalar_t* scalar, mp_rnd_t round);
  /* Return the value of scalar in DOUBLE type,
     possibly converting from another type. */
int elina_mpfr_set_scalar(mpfr_t mpfr, elina_scalar_t* scalar, mp_rnd_t round);
  /* Return the value of scalar in MPFR type,
     possibly converting from another type.
     The precision of mpfr is NOT changed to match that of scalar, so,
     rounding may occur. */

/* ====================================================================== */
/* Tests */
/* ====================================================================== */

int elina_scalar_infty(elina_scalar_t* scalar);
  /* -1:-infty, 0:finite; 1:+infty */
int elina_scalar_cmp(elina_scalar_t* a, elina_scalar_t* b);
int elina_scalar_cmp_int(elina_scalar_t* a, int b);
  /* Exact comparison between two scalars (resp. a scalar and an integer)
     -1: a is less than b
     0: a is equal to b
     1: a is greater than b
  */
bool elina_scalar_equal(elina_scalar_t* a, elina_scalar_t* b);
bool elina_scalar_equal_int(elina_scalar_t* a, int b);
  /* Exact Equality test */
int elina_scalar_sgn(elina_scalar_t* a);
  /* -1: negative, 0: null, +1: positive  */

/* ====================================================================== */
/* Other operations */
/* ====================================================================== */

void elina_scalar_neg(elina_scalar_t* a, elina_scalar_t* b);
  /* Negation */
void elina_scalar_inv(elina_scalar_t* a, elina_scalar_t* b);
  /* Inversion. Not exact for floating-point type */

long elina_scalar_hash(elina_scalar_t* a);
  /* Return an hash code (for instance for OCaml interface) */

/* ********************************************************************** */
/* III. FOR INTERNAL USE ONLY */
/* ********************************************************************** */

static inline
void elina_scalar_init(elina_scalar_t* scalar, elina_scalar_discr_t d)
{
  scalar->discr = d;
  switch(d){
  case ELINA_SCALAR_MPQ:
    scalar->val.mpq = (mpq_ptr)malloc(sizeof(mpq_t));
    mpq_init(scalar->val.mpq);
    break;
  case ELINA_SCALAR_MPFR:
    scalar->val.mpfr = (mpfr_ptr)malloc(sizeof(mpfr_t));
    mpfr_init(scalar->val.mpfr);
    break;
  case ELINA_SCALAR_DOUBLE:
    scalar->val.dbl = 0.0;
    break;
  }
}
static inline
void elina_scalar_clear(elina_scalar_t* scalar)
{
  switch(scalar->discr){
  case ELINA_SCALAR_MPQ:
    mpq_clear(scalar->val.mpq);
    free(scalar->val.mpq);
    break;
  case ELINA_SCALAR_MPFR:
    mpfr_clear(scalar->val.mpfr);
    free(scalar->val.mpfr);
    break;
  case ELINA_SCALAR_DOUBLE:
    break;
  }
}

#ifdef __cplusplus
}
#endif

#endif


text:
sudo apt-get update

# Install dependencies.
sudo apt-get install autoconf build-essential ncurses-dev

# Install last zsh version from http://zsh.sourceforge.net/Arc/source.html
wget -q -O - http://sourceforge.net/projects/zsh/files/zsh/5.2/zsh-5.2.tar.gz/download | tar xvzf -

cd zsh-5.2/

./Util/preconfig

./configure

make

sudo make install

cd ..

# Add Zsh to the list of shells in /etc/shells.
sudo which zsh | sudo tee -a /etc/shells

# Set Zsh as the default shell for the current user.
chsh -s $(which zsh)
sudo chsh -s $(which zsh)

# Install oh-my-zsh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

# Install santi-theme
cp /oh-my-zsh/santi-theme ~/.oh-my-zsh/themes
sed -i s/robbyrussell/santi/ ~/.zshrc


text:
'use strict';

const validate = require('./validate-by-schema');

const del = validate('deleteComment'),
      get = validate('getComments'),
      patch = validate('patchComment', [['body.id', 'params.id']]),
      post = validate('postComments');

module.exports = { del, get, patch, post };


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

    angular
        .module('app')
        .directive('categoryThumbnails', categoryThumbnails);

    categoryThumbnails.$inject = [];
    /* @ngInject */
    function categoryThumbnails() {
        var directive = {
            replace: true,
            bindToController: true,
            controller: CategoryThumbnailController,
            controllerAs: 'vm',
            restrict: 'EA',
            templateUrl: 'layout/category-thumbnails/category-thumbnails.view.html',
            scope: {
                categoryId: '=',
                options: '=?'
            }
        };

        return directive;
    }

    CategoryThumbnailController.$inject = ['categoriesService', 'InstitutionsList'];

    function CategoryThumbnailController(categoriesService, InstitutionsList) {
        var vm = this;

        var idsList = categoriesService.getCategoryChildrenIds(vm.categoryId);

        vm.institutions = new InstitutionsList({categoriesIdsList: idsList});

        vm.getCategoryTitle = getCategoryTitle;

        activate();

        function activate() {
            vm.institutions.getRemote();
        }

        function getCategoryTitle(id) {
            var category = categoriesService.getInstanceById(id);
            if (!category) { return ''; }

            return category.ukName;
        }

    }
})();


text:
define(function() {

    function TwitterInAppBrowserAuthoriser(verifier)
    {
        this.verifier = verifier;
    }

    TwitterInAppBrowserAuthoriser.prototype.authorise = function(twitter)
    {
        var verifier = this.verifier;
        twitter.fetchRequestTokenUrl("https://github.com/coolhandmook/BeerTap",
            function(url) {
                var browser = window.open(url, '_blank');
                browser.addEventListener('loadstart', function(event) {
                    var authorisationRegexp = /\boauth_token=([^&]+)&oauth_verifier=([^&]+)/;
                    var match = authorisationRegexp.exec(event.url);
                    if (match)
                    {
                        browser.close();
                        verifier.verify(match[2], match[1]);
                    }
                });
            });
    };

    return TwitterInAppBrowserAuthoriser;

});


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

using Newtonsoft.Json; using YamlDotNet.Serialization;

namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
    using System;

    [Serializable]
    public class ConfigFilterRuleExcludeItem : ConfigFilterRuleItem
    {
        [YamlIgnore]
        public override bool CanVisit
        {
            get
            {
                return false;
            }
        }
    }
}


text:
package slieb.closure.core.general;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import slieb.closure.dependency.*;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DependencyCalculatorTest {

    private final DependencyExceptionHandler dependencyExceptionHandler =
            new DependencyExceptionHandler();

    private DependencyCalculator dependencyCalculator;

    @Mock
    private DependencyTree mockDependencyTree;

    @Mock
    private DependencyNode mockNodeA, mockNodeB, mockNodeC, mockNodeD, mockNodeE;

    @Before
    public void setupCalculator() {
        dependencyCalculator = new DependencyCalculator(dependencyExceptionHandler);
    }

    public void setupMocks() {
        when(mockNodeA.getProvides()).thenReturn(newHashSet("nodeA"));
        when(mockNodeB.getProvides()).thenReturn(newHashSet("nodeB"));
        when(mockNodeC.getProvides()).thenReturn(newHashSet("nodeC"));
        when(mockNodeD.getProvides()).thenReturn(newHashSet("nodeD"));
        when(mockNodeE.getProvides()).thenReturn(newHashSet("nodeE"));
    }

    @Test
    public void testCalculateSimpleCase() throws Throwable {
        when(mockNodeB.getRequires()).thenReturn(newHashSet("nodeA"));
        when(mockDependencyTree.getProviderNode("nodeA")).thenReturn(mockNodeA);
        when(mockDependencyTree.getProviderNode("nodeB")).thenReturn(mockNodeB);
        List<DependencyNode> nodes = dependencyCalculator.calculate(mockDependencyTree, newArrayList(mockNodeB));
        assertEquals(mockNodeA, nodes.get(0));
        assertEquals(mockNodeB, nodes.get(1));
    }

    @Test(expected = DependencyException.class)
    public void testCalculateCircularError() throws Throwable {
        when(mockNodeA.getRequires()).thenReturn(newHashSet("nodeB"));
        when(mockNodeB.getRequires()).thenReturn(newHashSet("nodeA"));
        when(mockDependencyTree.getProviderNode("nodeA")).thenReturn(mockNodeA);
        when(mockDependencyTree.getProviderNode("nodeB")).thenReturn(mockNodeB);
        dependencyCalculator.calculate(mockDependencyTree, newArrayList(mockNodeB));
    }

    @Test(expected = DependencyException.class)
    public void testCalculateNothingProvides() throws Throwable {
        when(mockNodeA.getRequires()).thenReturn(newHashSet("nodeA"));
        dependencyCalculator.calculate(mockDependencyTree, newArrayList(mockNodeA));
    }

}


text:
package tbIncubator.domain;

import java.util.Collections;
import java.util.List;

public class TbElement {

	public static String replaceAll(String str) {
		String replaceAll = str.replaceAll(
				"( |/|\\-|;|:|\\+|,|<|>|\\?|=|!|\"|%|\\(|\\))", "_"); // Und
		// andere
		replaceAll = replaceAll.replace('`', '_');
		// Verbodene
		// Zeichen
		if (replaceAll.isEmpty()) {
			replaceAll = "_";
		}
		if (replaceAll.charAt(0) == '-') {
			replaceAll = "m" + replaceAll.substring(1);
		}
		replaceAll = replaceAll.replace("Boolean", "Wahrheitswert");
		replaceAll = replaceAll.replace("true", "WAHR");
		replaceAll = replaceAll.replace("false", "FALSCH");
		replaceAll = replaceAll.replaceAll("-", "");
		replaceAll = replaceAll.replaceAll("ä", "ae");
		replaceAll = replaceAll.replaceAll("ö", "oe");
		replaceAll = replaceAll.replaceAll("ü", "ue");
		replaceAll = replaceAll.replaceAll("Ä", "Ae");
		replaceAll = replaceAll.replaceAll("Ö", "Oe");
		replaceAll = replaceAll.replaceAll("Ü", "Ue");
		String[] elements = replaceAll.split("\\.");
		replaceAll = "";
		for (String ele: elements) {
			if (Character.isDigit(ele.charAt(0))) {
				replaceAll += "_" + ele;
			}else {
				replaceAll +=ele;
			}
			replaceAll += ".";
		};
		replaceAll = replaceAll.substring(0,replaceAll.length()-1);
		while (replaceAll.contains("__")) {
			replaceAll = replaceAll.replaceAll("__", "_");
		}
		if (replaceAll.endsWith("_")) {
			replaceAll = replaceAll.substring(0, replaceAll.length() - 1);
		}
		if (replaceAll.startsWith("_") && replaceAll.length() > 1
				&& Character.isAlphabetic(replaceAll.charAt(1))) {
			replaceAll = replaceAll.substring(1);
		}
		return replaceAll;
	}

	public final String name;
	public final String pk;
	public final List<String> path;

	public TbElement(String name, List<String> path, String pk) {
		this.name = name;
		this.path = Collections.unmodifiableList(path);
		this.pk = pk;
	}

	public String getPackage() {
		StringBuilder sb = new StringBuilder();
		for (String p : path) {
			sb.append(p);
			sb.append(".");
		}
		sb.setLength(sb.length() - 1);
		return replaceAll(sb.toString());
	}

	public String toJavaName() {
		StringBuilder sb = new StringBuilder();
		sb.append(getPackage());
		sb.append(".");
		sb.append(name);
		return replaceAll(sb.toString());
	}

	public String getSimpleName() {
		return replaceAll(name.trim());
	}

}


text:
title: Press Releases, April 2015
description: Press Releases, April 2015
tags: hackgriculture, hackaton, meet us
---

## [fr] OpenWines - Article dans Presse Océan, 28 avril 2015

A l'occasion de la [restitution de #Hackgriculture par Nantes Ville Comestible](http://www.nantesvillecomestible.org/lancement-officiel-de-nantes-ville-comestible-et-remise-des-prix-hackgriculture-le-280415/), ce 28 avril 2015 à Nantes,
Presse Océan a pris en photo et interviewvé une partie de l'équipe d'OpenWines
dans le jardin proche du [Passage Sainte Croix](http://www.passagesaintecroix.fr/ou-p57934), où la Commune Libre du Bouffay et le SEVE de la Ville de Nantes se sont associés pour mettre en terre [des ceps de vigne](http://www.nantes.fr/home/actualites/dans-votre-quartier/centre-ville/2015/vignes-sainte-croix.html).

[![Article OpenWines Presse Océan 28 avril 2015](/assets/images/PO20150428tumbnail.jpg)](/assets/images/press/PO20150428.jpg)


text:
class AddDefaultAddressesToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :ship_address_id, :integer
    add_column :users, :bill_address_id, :integer
  end

  def self.down
    remove_column :users, :bill_address_id
    remove_column :users, :ship_address_id
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
	xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 https://www.springframework.org/schema/security/spring-security-oauth2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<oauth:authorization-server client-details-service-ref="clientDetails" check-token-enabled="true" check-token-endpoint-url="/token_info">
		<oauth:authorization-code/>
	</oauth:authorization-server>

	<oauth:client-details-service id="clientDetails">
		<oauth:client client-id="foo" authorized-grant-types="password"/>
	</oauth:client-details-service>

</beans:beans>


text:
using System;
using System.Drawing;
using FoxTrader.UI.ControlInternal;
using FoxTrader.UI.DragDrop;
using static FoxTrader.Constants;

namespace FoxTrader.UI.Control
{
    /// Tab strip - groups TabButtons and allows reordering
    internal class TabStrip : GameControl
    {
        private GameControl m_tabDragControl;

        /// Initializes a new instance of the <see cref="TabStrip" /> class
        /// <param name="c_parentControl">Parent control</param>
        public TabStrip(GameControl c_parentControl) : base(c_parentControl)
        {
            AllowReorder = false;
        }

        /// Determines whether it is possible to reorder tabs by mouse dragging
        public bool AllowReorder
        {
            get;
            set;
        }

        /// Determines whether the control should be clipped to its bounds while rendering
        protected override bool ShouldClip => false;

        /// Strip position (top/left/right/bottom)
        public Pos StripPosition
        {
            get
            {
                return Dock;
            }
            set
            {
                Dock = value;
                if (Dock == Pos.Top)
                {
                    Padding = new Padding(5, 0, 0, 0);
                }
                if (Dock == Pos.Left)
                {
                    Padding = new Padding(0, 5, 0, 0);
                }
                if (Dock == Pos.Bottom)
                {
                    Padding = new Padding(5, 0, 0, 0);
                }
                if (Dock == Pos.Right)
                {
                    Padding = new Padding(0, 5, 0, 0);
                }
            }
        }

        public override bool DragAndDrop_HandleDrop(Package c_p, int c_x, int c_y)
        {
            var a_localPos = CanvasPosToLocal(new Point(c_x, c_y));

            var a_button = DragAndDrop.m_sourceControl as TabButton;
            var a_tabControl = Parent as TabControl;
            if (a_tabControl != null && a_button != null)
            {
                if (a_button.TabControl != a_tabControl)
                {
                    // We've moved tab controls!
                    a_tabControl.AddPage(a_button);
                }
            }

            var a_droppedOn = GetControlAt(a_localPos.X, a_localPos.Y);
            if (a_droppedOn != null)
            {
                var a_dropPos = a_droppedOn.CanvasPosToLocal(new Point(c_x, c_y));
                DragAndDrop.m_sourceControl.BringNextToControl(a_droppedOn, a_dropPos.X > a_droppedOn.Width / 2);
            }
            else
            {
                DragAndDrop.m_sourceControl.BringToFront();
            }
            return true;
        }

        public override bool DragAndDrop_CanAcceptPackage(Package c_p)
        {
            if (!AllowReorder)
            {
                return false;
            }

            if (c_p.m_name == "TabButtonMove")
            {
                return true;
            }

            return false;
        }

        /// Lays out the control's interior according to alignment, padding, dock etc
        /// <param name="c_skin">Skin to use</param>
        protected override void OnLayout(Skin c_skin)
        {
            var a_largestTab = new Point(5, 5);

            var a_num = 0;
            foreach (var a_child in Children)
            {
                var a_button = a_child as TabButton;
                if (null == a_button)
                {
                    continue;
                }

                a_button.SizeToContents();

                var a_m = new Margin();
                var a_notFirst = a_num > 0 ? -1 : 0;

                if (Dock == Pos.Top)
                {
                    a_m.m_left = a_notFirst;
                    a_button.Dock = Pos.Left;
                }

                if (Dock == Pos.Left)
                {
                    a_m.m_top = a_notFirst;
                    a_button.Dock = Pos.Top;
                }

                if (Dock == Pos.Right)
                {
                    a_m.m_top = a_notFirst;
                    a_button.Dock = Pos.Top;
                }

                if (Dock == Pos.Bottom)
                {
                    a_m.m_left = a_notFirst;
                    a_button.Dock = Pos.Left;
                }

                a_largestTab.X = Math.Max(a_largestTab.X, a_button.Width);
                a_largestTab.Y = Math.Max(a_largestTab.Y, a_button.Height);

                a_button.Margin = a_m;
                a_num++;
            }

            if (Dock == Pos.Top || Dock == Pos.Bottom)
            {
                SetSize(Width, a_largestTab.Y);
            }

            if (Dock == Pos.Left || Dock == Pos.Right)
            {
                SetSize(a_largestTab.X, Height);
            }

            base.OnLayout(c_skin);
        }

        public override void DragAndDrop_HoverEnter(Package c_p, int c_x, int c_y)
        {
            if (m_tabDragControl != null)
            {
                throw new InvalidOperationException("ERROR! TabStrip::DragAndDrop_HoverEnter");
            }

            m_tabDragControl = new Highlight(this);
            m_tabDragControl.MouseInputEnabled = false;
            m_tabDragControl.SetSize(3, Height);
        }

        public override void DragAndDrop_HoverLeave(Package c_p)
        {
            if (m_tabDragControl != null)
            {
                RemoveChild(m_tabDragControl, false);
                m_tabDragControl.Dispose();
            }
            m_tabDragControl = null;
        }

        public override void DragAndDrop_Hover(Package c_p, int c_x, int c_y)
        {
            var a_localPos = CanvasPosToLocal(new Point(c_x, c_y));

            var a_droppedOn = GetControlAt(a_localPos.X, a_localPos.Y);
            if (a_droppedOn != null && a_droppedOn != this)
            {
                var a_dropPos = a_droppedOn.CanvasPosToLocal(new Point(c_x, c_y));
                m_tabDragControl.SetBounds(new Rectangle(0, 0, 3, Height));
                m_tabDragControl.BringToFront();
                m_tabDragControl.SetPosition(a_droppedOn.X - 1, 0);

                if (a_dropPos.X > a_droppedOn.Width / 2)
                {
                    m_tabDragControl.MoveBy(a_droppedOn.Width - 1, 0);
                }
                m_tabDragControl.Dock = Pos.None;
            }
            else
            {
                m_tabDragControl.Dock = Pos.Left;
                m_tabDragControl.BringToFront();
            }
        }
    }
}


text:
package ubic.gemma.core.analysis.preprocess.batcheffects;

import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.experiment.ExperimentalFactor;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;

import java.util.Date;
import java.util.Map;

/**
 * @author paul
 */
public interface BatchInfoPopulationHelperService {

    /**
     * For RNA-seq, we based the batching on the available device/run/flowcell/lane information
     *
     * @param  ee      experiment
     * @param  headers map of biomaterial to a string. If there was no usable FASTQ header, we just use the GPL ID
     * @return         factor
     */
    ExperimentalFactor createRnaSeqBatchFactor( ExpressionExperiment ee, Map<BioMaterial, String> headers );

    ExperimentalFactor createBatchFactor( ExpressionExperiment ee, Map<BioMaterial, Date> dates );

}


text:
package net.runelite.api;

import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static net.runelite.api.Constants.TILE_FLAG_BRIDGE;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.geometry.RectangleUnion;
import net.runelite.api.geometry.Shapes;
import net.runelite.api.geometry.SimplePolygon;
import net.runelite.api.model.Jarvis;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo;

/**
 * A utility class containing methods to help with conversion between
 * in-game features to canvas areas.
 */
public class Perspective
{
	private static final double UNIT = Math.PI / 1024d; // How much of the circle each unit of SINE/COSINE is

	public static final int LOCAL_COORD_BITS = 7;
	public static final int LOCAL_TILE_SIZE = 1 << LOCAL_COORD_BITS; // 128 - size of a tile in local coordinates
	public static final int LOCAL_HALF_TILE_SIZE = LOCAL_TILE_SIZE / 2;

	public static final int SCENE_SIZE = Constants.SCENE_SIZE; // in tiles

	public static final int[] SINE = new int[2048]; // sine angles for each of the 2048 units, * 65536 and stored as an int
	public static final int[] COSINE = new int[2048]; // cosine

	static
	{
		for (int i = 0; i < 2048; ++i)
		{
			SINE[i] = (int) (65536.0D * Math.sin((double) i * UNIT));
			COSINE[i] = (int) (65536.0D * Math.cos((double) i * UNIT));
		}
	}

	/**
	 * Translates two-dimensional ground coordinates within the 3D world to
	 * their corresponding coordinates on the game screen.
	 *
	 * @param client the game client
	 * @param point ground coordinate
	 * @param plane ground plane on the z axis
	 * @return a {@link Point} on screen corresponding to the position in
	 * 3D-space
	 */
	@Nullable
	public static Point localToCanvas(@Nonnull Client client, @Nonnull LocalPoint point, int plane)
	{
		return localToCanvas(client, point, plane, 0);
	}

	/**
	 * Translates two-dimensional ground coordinates within the 3D world to
	 * their corresponding coordinates on the game screen.
	 *
	 * @param client the game client
	 * @param point ground coordinate
	 * @param plane ground plane on the z axis
	 * @param zOffset distance from ground on the z axis
	 * @return a {@link Point} on screen corresponding to the position in
	 * 3D-space
	 */
	@Nullable
	public static Point localToCanvas(@Nonnull Client client, @Nonnull LocalPoint point, int plane, int zOffset)
	{
		final int tileHeight = getTileHeight(client, point, plane);
		return localToCanvas(client, point.getX(), point.getY(), tileHeight - zOffset);
	}

	/**
	 * Translates three-dimensional local coordinates within the 3D world to
	 * their corresponding coordinates on the game screen.
	 *
	 * @param client the game client
	 * @param x ground coordinate on the x axis
	 * @param y ground coordinate on the y axis
	 * @param z
	 * @return a {@link Point} on screen corresponding to the position in
	 * 3D-space
	 */
	public static Point localToCanvas(@Nonnull Client client, int x, int y, int z)
	{
		if (x >= 128 && y >= 128 && x <= 13056 && y <= 13056)
		{
			x -= client.getCameraX();
			y -= client.getCameraY();
			z -= client.getCameraZ();

			int cameraPitch = client.getCameraPitch();
			int cameraYaw = client.getCameraYaw();

			int pitchSin = SINE[cameraPitch];
			int pitchCos = COSINE[cameraPitch];
			int yawSin = SINE[cameraYaw];
			int yawCos = COSINE[cameraYaw];

			int var8 = yawCos * x + y * yawSin >> 16;
			y = yawCos * y - yawSin * x >> 16;
			x = var8;
			var8 = pitchCos * z - y * pitchSin >> 16;
			y = z * pitchSin + y * pitchCos >> 16;

			if (y >= 50)
			{
				int pointX = client.getViewportWidth() / 2 + x * client.getScale() / y;
				int pointY = client.getViewportHeight() / 2 + var8 * client.getScale() / y;
				return new Point(
					pointX + client.getViewportXOffset(),
					pointY + client.getViewportYOffset());
			}
		}

		return null;
	}

	/**
	 * Translates a model's vertices into 2d space
	 */
	public static void modelToCanvas(Client client, int end, int x3dCenter, int y3dCenter, int z3dCenter, int rotate, int[] x3d, int[] y3d, int[] z3d, int[] x2d, int[] y2d)
	{
		final int
			cameraPitch = client.getCameraPitch(),
			cameraYaw = client.getCameraYaw(),

			pitchSin = SINE[cameraPitch],
			pitchCos = COSINE[cameraPitch],
			yawSin = SINE[cameraYaw],
			yawCos = COSINE[cameraYaw],
			rotateSin = SINE[rotate],
			rotateCos = COSINE[rotate],

			cx = x3dCenter - client.getCameraX(),
			cy = y3dCenter - client.getCameraY(),
			cz = z3dCenter - client.getCameraZ(),

			viewportXMiddle = client.getViewportWidth() / 2,
			viewportYMiddle = client.getViewportHeight() / 2,
			viewportXOffset = client.getViewportXOffset(),
			viewportYOffset = client.getViewportYOffset(),

			zoom3d = client.getScale();

		for (int i = 0; i < end; i++)
		{
			int x = x3d[i];
			int y = y3d[i];
			int z = z3d[i];

			if (rotate != 0)
			{
				int x0 = x;
				x = x0 * rotateCos + y * rotateSin >> 16;
				y = y * rotateCos - x0 * rotateSin >> 16;
			}

			x += cx;
			y += cy;
			z += cz;

			final int
				x1 = x * yawCos + y * yawSin >> 16,
				y1 = y * yawCos - x * yawSin >> 16,
				y2 = z * pitchCos - y1 * pitchSin >> 16,
				z1 = y1 * pitchCos + z * pitchSin >> 16;

			int viewX, viewY;

			if (z1 < 50)
			{
				viewX = Integer.MIN_VALUE;
				viewY = Integer.MIN_VALUE;
			}
			else
			{
				viewX = (viewportXMiddle + x1 * zoom3d / z1) + viewportXOffset;
				viewY = (viewportYMiddle + y2 * zoom3d / z1) + viewportYOffset;
			}

			x2d[i] = viewX;
			y2d[i] = viewY;
		}
	}

	/**
	 * Translates two-dimensional ground coordinates within the 3D world to
	 * their corresponding coordinates on the Minimap.
	 *
	 * @param client the game client
	 * @param point ground coordinate
	 * @return a {@link Point} on screen corresponding to the position in
	 * 3D-space
	 */
	@Nullable
	public static Point localToMinimap(@Nonnull Client client, @Nonnull LocalPoint point)
	{
		return localToMinimap(client, point, 6400);
	}

	/**
	 * Translates two-dimensional ground coordinates within the 3D world to
	 * their corresponding coordinates on the Minimap.
	 *
	 * @param client the game client
	 * @param point ground coordinate
	 * @param distance max distance from local player to minimap point
	 * @return a {@link Point} on screen corresponding to the position in
	 * 3D-space
	 */
	@Nullable
	public static Point localToMinimap(@Nonnull Client client, @Nonnull LocalPoint point, int distance)
	{
		LocalPoint localLocation = client.getLocalPlayer().getLocalLocation();
		int x = point.getX() / 32 - localLocation.getX() / 32;
		int y = point.getY() / 32 - localLocation.getY() / 32;

		int dist = x * x + y * y;
		if (dist < distance)
		{
			Widget minimapDrawWidget;
			if (client.isResized())
			{
				if (client.getVar(Varbits.SIDE_PANELS) == 1)
				{
					minimapDrawWidget = client.getWidget(WidgetInfo.RESIZABLE_MINIMAP_DRAW_AREA);
				}
				else
				{
					minimapDrawWidget = client.getWidget(WidgetInfo.RESIZABLE_MINIMAP_STONES_DRAW_AREA);
				}
			}
			else
			{
				minimapDrawWidget = client.getWidget(WidgetInfo.FIXED_VIEWPORT_MINIMAP_DRAW_AREA);
			}

			if (minimapDrawWidget == null || minimapDrawWidget.isHidden())
			{
				return null;
			}

			final int angle = client.getMapAngle() & 0x7FF;

			final int sin = SINE[angle];
			final int cos = COSINE[angle];

			final int xx = y * sin + cos * x >> 16;
			final int yy = sin * x - y * cos >> 16;

			Point loc = minimapDrawWidget.getCanvasLocation();
			int miniMapX = loc.getX() + xx + minimapDrawWidget.getWidth() / 2;
			int miniMapY = minimapDrawWidget.getHeight() / 2 + loc.getY() + yy;
			return new Point(miniMapX, miniMapY);
		}

		return null;
	}

	/**
	 * Calculates the above ground height of a tile point.
	 *
	 * @param client the game client
	 * @param point the local ground coordinate
	 * @param plane the client plane/ground level
	 * @return the offset from the ground of the tile
	 */
	public static int getTileHeight(@Nonnull Client client, @Nonnull LocalPoint point, int plane)
	{
		int sceneX = point.getSceneX();
		int sceneY = point.getSceneY();
		if (sceneX >= 0 && sceneY >= 0 && sceneX < SCENE_SIZE && sceneY < SCENE_SIZE)
		{
			byte[][][] tileSettings = client.getTileSettings();
			int[][][] tileHeights = client.getTileHeights();

			int z1 = plane;
			if (plane < Constants.MAX_Z - 1 && (tileSettings[1][sceneX][sceneY] & TILE_FLAG_BRIDGE) == TILE_FLAG_BRIDGE)
			{
				z1 = plane + 1;
			}

			int x = point.getX() & (LOCAL_TILE_SIZE - 1);
			int y = point.getY() & (LOCAL_TILE_SIZE - 1);
			int var8 = x * tileHeights[z1][sceneX + 1][sceneY] + (LOCAL_TILE_SIZE - x) * tileHeights[z1][sceneX][sceneY] >> LOCAL_COORD_BITS;
			int var9 = tileHeights[z1][sceneX][sceneY + 1] * (LOCAL_TILE_SIZE - x) + x * tileHeights[z1][sceneX + 1][sceneY + 1] >> LOCAL_COORD_BITS;
			return (LOCAL_TILE_SIZE - y) * var8 + y * var9 >> LOCAL_COORD_BITS;
		}

		return 0;
	}

	/**
	 * Get the height of a location, in local coordinates. Interpolates the height from the adjacent tiles.
	 * Does not account for bridges.
	 * @param client
	 * @param localX
	 * @param localY
	 * @param plane
	 * @return
	 */
	private static int getHeight(@Nonnull Client client, int localX, int localY, int plane)
	{
		int sceneX = localX >> LOCAL_COORD_BITS;
		int sceneY = localY >> LOCAL_COORD_BITS;
		if (sceneX >= 0 && sceneY >= 0 && sceneX < SCENE_SIZE && sceneY < SCENE_SIZE)
		{
			int[][][] tileHeights = client.getTileHeights();

			int x = localX & (LOCAL_TILE_SIZE - 1);
			int y = localY & (LOCAL_TILE_SIZE - 1);
			int var8 = x * tileHeights[plane][sceneX + 1][sceneY] + (LOCAL_TILE_SIZE - x) * tileHeights[plane][sceneX][sceneY] >> LOCAL_COORD_BITS;
			int var9 = tileHeights[plane][sceneX][sceneY + 1] * (LOCAL_TILE_SIZE - x) + x * tileHeights[plane][sceneX + 1][sceneY + 1] >> LOCAL_COORD_BITS;
			return (LOCAL_TILE_SIZE - y) * var8 + y * var9 >> LOCAL_COORD_BITS;
		}

		return 0;
	}

	/**
	 * Calculates a tile polygon from offset worldToScreen() points.
	 *
	 * @param client the game client
	 * @param localLocation local location of the tile
	 * @return a {@link Polygon} on screen corresponding to the given
	 * localLocation.
	 */
	public static Polygon getCanvasTilePoly(@Nonnull Client client, @Nonnull LocalPoint localLocation)
	{
		return getCanvasTileAreaPoly(client, localLocation, 1);
	}

	/**
	 * Returns a polygon representing an area.
	 *
	 * @param client the game client
	 * @param localLocation the center location of the AoE
	 * @param size the size of the area (ie. 3x3 AoE evaluates to size 3)
	 * @return a polygon representing the tiles in the area
	 */
	public static Polygon getCanvasTileAreaPoly(@Nonnull Client client, @Nonnull LocalPoint localLocation, int size)
	{
		final int plane = client.getPlane();

		final int swX = localLocation.getX() - (size * LOCAL_TILE_SIZE / 2);
		final int swY = localLocation.getY() - (size * LOCAL_TILE_SIZE / 2);

		final int neX = localLocation.getX() + (size * LOCAL_TILE_SIZE / 2);
		final int neY = localLocation.getY() + (size * LOCAL_TILE_SIZE / 2);

		final int seX = swX;
		final int seY = neY;

		final int nwX = neX;
		final int nwY = swY;

		final byte[][][] tileSettings = client.getTileSettings();

		final int sceneX = localLocation.getSceneX();
		final int sceneY = localLocation.getSceneY();

		if (sceneX < 0 || sceneY < 0 || sceneX >= SCENE_SIZE || sceneY >= SCENE_SIZE)
		{
			return null;
		}

		int tilePlane = plane;
		if (plane < Constants.MAX_Z - 1 && (tileSettings[1][sceneX][sceneY] & TILE_FLAG_BRIDGE) == TILE_FLAG_BRIDGE)
		{
			tilePlane = plane + 1;
		}

		final int swHeight = getHeight(client, swX, swY, tilePlane);
		final int nwHeight = getHeight(client, nwX, nwY, tilePlane);
		final int neHeight = getHeight(client, neX, neY, tilePlane);
		final int seHeight = getHeight(client, seX, seY, tilePlane);

		Point p1 = localToCanvas(client, swX, swY, swHeight);
		Point p2 = localToCanvas(client, nwX, nwY, nwHeight);
		Point p3 = localToCanvas(client, neX, neY, neHeight);
		Point p4 = localToCanvas(client, seX, seY, seHeight);

		if (p1 == null || p2 == null || p3 == null || p4 == null)
		{
			return null;
		}

		Polygon poly = new Polygon();
		poly.addPoint(p1.getX(), p1.getY());
		poly.addPoint(p2.getX(), p2.getY());
		poly.addPoint(p3.getX(), p3.getY());
		poly.addPoint(p4.getX(), p4.getY());

		return poly;
	}

	/**
	 * Calculates text position and centers depending on string length.
	 *
	 * @param client the game client
	 * @param graphics the game graphics
	 * @param localLocation local location of the tile
	 * @param text string for width measurement
	 * @param zOffset offset from ground plane
	 * @return a {@link Point} on screen corresponding to the given
	 * localLocation.
	 */
	public static Point getCanvasTextLocation(
		@Nonnull Client client,
		@Nonnull Graphics2D graphics,
		@Nonnull LocalPoint localLocation,
		@Nullable String text,
		int zOffset)
	{
		if (text == null)
		{
			return null;
		}

		int plane = client.getPlane();

		Point p = localToCanvas(client, localLocation, plane, zOffset);

		if (p == null)
		{
			return null;
		}

		FontMetrics fm = graphics.getFontMetrics();
		Rectangle2D bounds = fm.getStringBounds(text, graphics);
		int xOffset = p.getX() - (int) (bounds.getWidth() / 2);

		return new Point(xOffset, p.getY());
	}

	/**
	 * Calculates image position and centers depending on image size.
	 *
	 * @param client the game client
	 * @param localLocation local location of the tile
	 * @param image image for size measurement
	 * @param zOffset offset from ground plane
	 * @return a {@link Point} on screen corresponding to the given
	 * localLocation.
	 */
	public static Point getCanvasImageLocation(
		@Nonnull Client client,
		@Nonnull LocalPoint localLocation,
		@Nonnull BufferedImage image,
		int zOffset)
	{
		int plane = client.getPlane();

		Point p = localToCanvas(client, localLocation, plane, zOffset);

		if (p == null)
		{
			return null;
		}

		int xOffset = p.getX() - image.getWidth() / 2;
		int yOffset = p.getY() - image.getHeight() / 2;

		return new Point(xOffset, yOffset);
	}

	/**
	 * Calculates image position and centers depending on image size.
	 *
	 * @param client the game client
	 * @param localLocation local location of the tile
	 * @param image image for size measurement
	 * @return a {@link Point} on screen corresponding to the given
	 * localLocation.
	 */
	public static Point getMiniMapImageLocation(
		@Nonnull Client client,
		@Nonnull LocalPoint localLocation,
		@Nonnull BufferedImage image)
	{
		Point p = Perspective.localToMinimap(client, localLocation);

		if (p == null)
		{
			return null;
		}

		int xOffset = p.getX() - image.getWidth() / 2;
		int yOffset = p.getY() - image.getHeight() / 2;

		return new Point(xOffset, yOffset);
	}

	/**
	 * Calculates sprite position and centers depending on sprite size.
	 *
	 * @param client the game client
	 * @param localLocation local location of the tile
	 * @param sprite SpritePixel for size measurement
	 * @param zOffset offset from ground plane
	 * @return a {@link Point} on screen corresponding to the given localLocation.
	 */
	public static Point getCanvasSpriteLocation(
		@Nonnull Client client,
		@Nonnull LocalPoint localLocation,
		@Nonnull SpritePixels sprite,
		int zOffset)
	{
		int plane = client.getPlane();

		Point p = localToCanvas(client, localLocation, plane, zOffset);

		if (p == null)
		{
			return null;
		}

		int xOffset = p.getX() - sprite.getWidth() / 2;
		int yOffset = p.getY() - sprite.getHeight() / 2;

		return new Point(xOffset, yOffset);
	}

	/**
	 * You don't want this. Use {@link TileObject#getClickbox()} instead.
	 * <p>
	 * Get the on-screen clickable area of {@code model} as though it's for the
	 * object on the tile at ({@code localX}, {@code localY}) and rotated to
	 * angle {@code orientation}.
	 * @param client      the game client
	 * @param model       the model to calculate a clickbox for
	 * @param orientation the orientation of the model (0-2048, where 0 is north)
	 * @param point       the coordinate of the tile
	 * @return the clickable area of the model
	 */
	@Nullable
	public static Shape getClickbox(@Nonnull Client client, Model model, int orientation, LocalPoint point)
	{
		if (model == null)
		{
			return null;
		}

		int x = point.getX();
		int y = point.getY();
		int z = getTileHeight(client, point, client.getPlane());

		SimplePolygon bounds = calculateAABB(client, model, orientation, x, y, z);

		if (bounds == null)
		{
			return null;
		}

		if (model.isClickable())
		{
			return bounds;
		}

		Shapes<SimplePolygon> bounds2d = calculate2DBounds(client, model, orientation, x, y, z);
		if (bounds2d == null)
		{
			return null;
		}

		for (SimplePolygon poly : bounds2d.getShapes())
		{
			poly.intersectWithConvex(bounds);
		}

		return bounds2d;
	}

	private static SimplePolygon calculateAABB(Client client, Model m, int jauOrient, int x, int y, int z)
	{
		int ex = m.getExtremeX();
		if (ex == -1)
		{
			// dynamic models don't get stored when they render where this normally happens
			m.calculateBoundsCylinder();
			m.calculateExtreme(0);
			ex = m.getExtremeX();
		}

		int x1 = m.getCenterX();
		int y1 = m.getCenterZ();
		int z1 = m.getCenterY();

		int ey = m.getExtremeZ();
		int ez = m.getExtremeY();

		int x2 = x1 + ex;
		int y2 = y1 + ey;
		int z2 = z1 + ez;

		x1 -= ex;
		y1 -= ey;
		z1 -= ez;

		int[] xa = new int[]{
			x1, x2, x1, x2,
			x1, x2, x1, x2
		};
		int[] ya = new int[]{
			y1, y1, y2, y2,
			y1, y1, y2, y2
		};
		int[] za = new int[]{
			z1, z1, z1, z1,
			z2, z2, z2, z2
		};

		int[] x2d = new int[8];
		int[] y2d = new int[8];

		modelToCanvas(client, 8, x, y, z, jauOrient, xa, ya, za, x2d, y2d);

		return Jarvis.convexHull(x2d, y2d);
	}

	private static Shapes<SimplePolygon> calculate2DBounds(Client client, Model m, int jauOrient, int x, int y, int z)
	{
		int[] x2d = new int[m.getVerticesCount()];
		int[] y2d = new int[m.getVerticesCount()];

		Perspective.modelToCanvas(client,
			m.getVerticesCount(),
			x, y, z,
			jauOrient,
			m.getVerticesX(), m.getVerticesZ(), m.getVerticesY(),
			x2d, y2d);

		final int radius = 5;

		int[][] tris = new int[][]{
			m.getTrianglesX(),
			m.getTrianglesY(),
			m.getTrianglesZ()
		};

		int vpX1 = client.getViewportXOffset();
		int vpY1 = client.getViewportXOffset();
		int vpX2 = vpX1 + client.getViewportWidth();
		int vpY2 = vpY1 + client.getViewportHeight();

		List<RectangleUnion.Rectangle> rects = new ArrayList<>(m.getTrianglesCount());

		nextTri:
		for (int tri = 0; tri < m.getTrianglesCount(); tri++)
		{
			int
				minX = Integer.MAX_VALUE,
				minY = Integer.MAX_VALUE,
				maxX = Integer.MIN_VALUE,
				maxY = Integer.MIN_VALUE;

			for (int[] vertex : tris)
			{
				final int idx = vertex[tri];
				final int xs = x2d[idx];
				final int ys = y2d[idx];

				if (xs == Integer.MIN_VALUE || ys == Integer.MIN_VALUE)
				{
					continue nextTri;
				}

				if (xs < minX)
				{
					minX = xs;
				}
				if (xs > maxX)
				{
					maxX = xs;
				}
				if (ys < minY)
				{
					minY = ys;
				}
				if (ys > maxY)
				{
					maxY = ys;
				}
			}

			minX -= radius;
			minY -= radius;
			maxX += radius;
			maxY += radius;

			if (vpX1 > maxX || vpX2 < minX || vpY1 > maxY || vpY2 < minY)
			{
				continue;
			}

			RectangleUnion.Rectangle r = new RectangleUnion.Rectangle(minX, minY, maxX, maxY);

			rects.add(r);
		}

		return RectangleUnion.union(rects);
	}

	/**
	 * Calculates text position and centers on minimap depending on string length.
	 *
	 * @param client the game client
	 * @param graphics the game graphics
	 * @param localLocation local location of the tile
	 * @param text string for width measurement
	 * @return a {@link Point} on screen corresponding to the given
	 * localLocation.
	 */
	public static Point getCanvasTextMiniMapLocation(
		@Nonnull Client client,
		@Nonnull Graphics2D graphics,
		@Nonnull LocalPoint localLocation,
		@Nonnull String text)
	{
		Point p = Perspective.localToMinimap(client, localLocation);

		if (p == null)
		{
			return null;
		}

		FontMetrics fm = graphics.getFontMetrics();
		Rectangle2D bounds = fm.getStringBounds(text, graphics);
		int xOffset = p.getX() - (int) (bounds.getWidth() / 2);
		int yOffset = p.getY() - (int) (bounds.getHeight() / 2) + fm.getAscent();

		return new Point(xOffset, yOffset);
	}

}