text:
package net.entropysoft.transmorph.signature.formatter;

import static org.junit.Assert.assertEquals;

import java.util.List;
import java.util.Map;

import net.entropysoft.transmorph.signature.TypeSignatureFactory;
import net.entropysoft.transmorph.type.TypeReference;

import org.junit.Test;

public class JavaSyntaxTypeSignatureFormatterTest {

	@Test
	public void testFormatPrimitive() throws Exception {
		JavaSyntaxTypeSignatureFormatter typeSignatureFormatter = new JavaSyntaxTypeSignatureFormatter();

		assertEquals("int", typeSignatureFormatter.format(TypeSignatureFactory
				.getTypeSignature(Integer.TYPE)));
	}

	@Test
	public void testFormatClass() throws Exception {
		JavaSyntaxTypeSignatureFormatter typeSignatureFormatter = new JavaSyntaxTypeSignatureFormatter();

		assertEquals("java.lang.String", typeSignatureFormatter
				.format(TypeSignatureFactory.getTypeSignature(String.class)));

		typeSignatureFormatter.setUseSimpleNames(true);
		assertEquals("String", typeSignatureFormatter
				.format(TypeSignatureFactory.getTypeSignature(String.class)));
	}

	@Test
	public void testFormatArray() throws Exception {
		JavaSyntaxTypeSignatureFormatter typeSignatureFormatter = new JavaSyntaxTypeSignatureFormatter();

		assertEquals("java.lang.String[][]",
				typeSignatureFormatter.format(TypeSignatureFactory
						.getTypeSignature(String[][].class)));
		assertEquals("int[][]", typeSignatureFormatter
				.format(TypeSignatureFactory.getTypeSignature(int[][].class)));

		typeSignatureFormatter.setUseSimpleNames(true);
		assertEquals("String[][]",
				typeSignatureFormatter.format(TypeSignatureFactory
						.getTypeSignature(String[][].class)));

	}

	@Test
	public void testFormatWithGenerics() throws Exception {
		JavaSyntaxTypeSignatureFormatter typeSignatureFormatter = new JavaSyntaxTypeSignatureFormatter();

		assertEquals("java.util.Map<java.lang.String,java.lang.Integer>",
				typeSignatureFormatter.format(TypeSignatureFactory
						.getTypeSignature(Map.class, new Class[] {
								String.class, Integer.class })));
		typeSignatureFormatter.setUseSimpleNames(true);
		assertEquals("Map<String,Integer>", typeSignatureFormatter
				.format(TypeSignatureFactory.getTypeSignature(Map.class,
						new Class[] { String.class, Integer.class })));

		assertEquals("List<? extends Integer>", typeSignatureFormatter
				.format(TypeSignatureFactory.getTypeSignature(
						"Ljava.util.List<+Ljava.lang.Integer;>;", false)));
	}

	@Test
	public void testFormatWildcardType() throws Exception {
		JavaSyntaxTypeSignatureFormatter typeSignatureFormatter = new JavaSyntaxTypeSignatureFormatter();
		TypeReference<List<? extends Number>> typeReference = new TypeReference<List<? extends Number>>() {
		};
		TypeReference<?> wildardTypeRef = typeReference.getTypeArguments()[0];
		assertEquals("? extends java.lang.Number", typeSignatureFormatter.format(TypeSignatureFactory
				.getTypeSignature(wildardTypeRef.getType())));
	}

}

redpajama_set_name: RedPajamaGithub


text: export {default} from './Scrollable';


text:
'use strict';

/**
 * Sign up as new user
**/
angular.module('fahrtenbuchApp')
  .controller('SignupCtrl', function ($scope, Auth, $location, Car, Geocode) {

    $scope.user = {};
    $scope.errors = {};

    Car.getCars()
    .then(function(cars) {
      $scope.cars = cars;
      $scope.car = $scope.cars[0];
    })
    .catch(function(err) {
      $scope.errors.other = err.message;
    });

    $scope.register = function(form) {
      $scope.submitted = true;

      if(form.$valid) {

        // save new user
        Auth.createUser({
          name: $scope.user.name,
          defaultCar: $scope.car._id,
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then( function() {
          // redirect to trip overview
          $location.path('/trip');
        })
        .catch( function(err) {
          err = err.data;
          $scope.errors = {};

          // Update validity of form fields that match the mongoose errors
          angular.forEach(err.errors, function(error, field) {
            form[field].$setValidity('mongoose', false);
            $scope.errors[field] = error.message;
          });
        });
      }
    };

  });


text:
<?xml version="1.0" encoding="UTF-8" ?>
<resources>
    <style name="BaseAppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">
        <item name="android:actionBarSize">56dp</item>
        <item name="android:colorAccent">@color/accent</item>
        <item name="colorControlActivated">@color/accent</item>
        <item name="android:statusBarColor">@color/fallbackStatusBar</item>
        <item name="android:windowBackground">@color/background</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:windowTranslucentStatus">false</item>
        <item name="android:autofilledHighlight">@android:color/transparent</item>
    </style>
</resources>


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.sql.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for ManagedInstanceAdministratorType. */
public final class ManagedInstanceAdministratorType extends ExpandableStringEnum<ManagedInstanceAdministratorType> {
    /** Static value ActiveDirectory for ManagedInstanceAdministratorType. */
    public static final ManagedInstanceAdministratorType ACTIVE_DIRECTORY = fromString("ActiveDirectory");

    /**
     * Creates or finds a ManagedInstanceAdministratorType from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ManagedInstanceAdministratorType.
     */
    @JsonCreator
    public static ManagedInstanceAdministratorType fromString(String name) {
        return fromString(name, ManagedInstanceAdministratorType.class);
    }

    /** @return known ManagedInstanceAdministratorType values. */
    public static Collection<ManagedInstanceAdministratorType> values() {
        return values(ManagedInstanceAdministratorType.class);
    }
}


text:
<?php
//namespace Blog;

class Controller_ViewExtendsClass extends Controller {
    public function action_index() {
         Package::load('mymath');
         $result = \Mymath\View::myFunc();
         echo $result;
    }
}
?>


text:
file(REMOVE_RECURSE
  "qtmarkup_automoc.cpp"
  "testqtmarkup_automoc.cpp"
  "CMakeFiles/ExperimentalCoverage"
)

# Per-language clean rules from dependency scanning.
foreach(lang )
  include(CMakeFiles/ExperimentalCoverage.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="tab_text_normal">#212121</color>
    <color name="text_color1">#999999</color>
</resources>


text:
#include "ListADT.h"
#include <iostream>

using namespace std;

/* *** ODSATag: AList *** */
// Array-based list implementation
/* *** ODSATag: AListVars *** */
class AList : public List {
  ListItemType listArray[MAX_SIZE];  //Array holding list elements
  int listSize;   //Current number of list items
  int curr;   //Position of current element
  /* *** ODSAendTag: AListVars *** */

public:

  //Constructor
  // Create a new list element with maximum size "MAX_SIZE"
  AList() : listSize(0)
{
  //Initial the array
  for (int k = 0; k < MAX_SIZE; k++) listArray[k] = 0;
} //end constructor
/*
bool isEmpty() const
{
  return listSize == 0;
  }*/
  void clear()              // Reinitialize the list
  { listSize = curr = 0; } // Simply reinitialize values

/* *** ODSATag: AListInsert *** */
// Insert "it" at current position
bool insert(const ListItemType& newItem)
{
  if (listSize >= MAX_SIZE) return false;
  for (int i = listSize; i > curr; i--) //Shift elements up
    listArray[i] = listArray[i-1];      //to make room
  listArray[curr] = newItem;
  listSize++;                           //Increment list size
  return true;
}//
/* *** ODSAendTag: AListInsert *** */

/* *** ODSATag: AListAppend *** */
//Append item to list
bool append(const ListItemType& newItem)
{
  if ( listSize >= MAX_SIZE ) return false;
  listArray[listSize++] = newItem;
  return true;
}
/* *** ODSAendTag: AListAppend *** */

/* *** ODSATag: AListRemove *** */
// Remove and return the current element
ListItemType remove()
{
  if( (curr < 0) || (curr >= listSize) )  // No current element
    return 0;
  ListItemType it = listArray[curr];      // Copy the element
  for (int i = curr; i < listSize; i++)   // Shift them down
    listArray[i] = listArray[i+1];
  listSize--;                             // Decrement size
  return it;
}
/* *** ODSAendTag: AListRemove *** */

void moveToStart() { curr = 0; }          // Set to front
void moveToEnd() { curr = listSize; }     // Set to end
void prev() { if (curr != 0) curr--; }    // Move left
void next() { if (curr < listSize) curr++; } // Move right
int length() { return listSize; }         // Return list size
int currPos() { return curr; }            // Return current position

// Set current list position to "pos"
bool moveToPos(int pos) {
  if ((pos < 0) || (pos > listSize)) return false;
  curr = pos;
  return true;
}

// Return true if current position is at end of the list
bool isAtEnd() { return curr == listSize; }

// Return the current element
ListItemType getValue() {
  if ((curr < 0) || (curr >= listSize)) // No current element
    return 0;
  return listArray[curr];
}
/* *** ODSAendTag: AList *** */

};


text:
struct AliHLTTPCClusterMCLabel;
struct AliHLTTPCRawCluster;
namespace o2
{
namespace tpc
{
struct ClusterNativeAccess;
struct CompressedClustersFlat;
class Digit;
class TrackTPC;
namespace constants
{
} // namespace constants
} // namespace tpc
} // namespace o2
#endif

namespace o2
{
class MCCompLabel;
template <typename T>
class BaseCluster;
namespace base
{
template <typename T>
class PropagatorImpl;
class MatLayerCylSet;
} // namespace base
namespace track
{
#ifdef GPUCA_NOCOMPAT
template <typename value_T>
class TrackParametrizationWithError;
using TrackParCov = TrackParametrizationWithError<float>;
#else
class TrackParCov;
#endif
} // namespace track
namespace trd
{
class GeometryFlat;
} // namespace trd
namespace dataformats
{
class TrackTPCITS;
class MatchInfoTOF;
template <class T>
class MCTruthContainer;
template <class T>
class ConstMCTruthContainerView;
} // namespace dataformats
namespace itsmft
{
class CompClusterExt;
class ROFRecord;
class TopologyDictionary;
} // namespace itsmft
namespace its
{
class TrackITS;
} // namespace its
namespace tof
{
class Cluster;
} // namespace tof
namespace tpc
{
class CalibdEdxContainer;
} // namespace tpc
} // namespace o2

namespace GPUCA_NAMESPACE
{
namespace gpu
{
class TPCFastTransform;
struct TPCPadGainCalib;

} // namespace gpu
} // namespace GPUCA_NAMESPACE

namespace GPUCA_NAMESPACE
{
namespace gpu
{
#ifdef GPUCA_NOCOMPAT_ALLOPENCL
#include "utils/bitfield.h"
#define ENUM_CLASS class
#define ENUM_UINT : unsigned int
#define GPUCA_RECO_STEP GPUDataTypes::RecoStep
#else
#define ENUM_CLASS
#define ENUM_UINT
#define GPUCA_RECO_STEP GPUDataTypes
#endif

#if defined(__OPENCL__) && !defined(__OPENCLCPP__)
MEM_CLASS_PRE() // Macro with some template magic for OpenCL 1.2
#endif
class GPUTPCTrack;
class GPUTPCHitId;
class GPUTPCGMMergedTrack;
struct GPUTPCGMMergedTrackHit;
struct GPUTPCGMMergedTrackHitXYZ;
class GPUTRDTrackletWord;
class GPUTRDSpacePoint;
struct GPUTPCMCInfo;
struct GPUTPCMCInfoCol;
struct GPUTPCClusterData;
struct GPUTRDTrackletLabels;
struct GPUTPCDigitsMCInput;
struct GPUSettingsTF;

class GPUDataTypes
{
 public:
  enum ENUM_CLASS GeometryType ENUM_UINT{RESERVED_GEOMETRY = 0, ALIROOT = 1, O2 = 2};
  enum DeviceType ENUM_UINT { INVALID_DEVICE = 0,
                              CPU = 1,
                              CUDA = 2,
                              HIP = 3,
                              OCL = 4,
                              OCL2 = 5 };
  enum ENUM_CLASS GeneralStep { Prepare = 1,
                                QA = 2 };

  enum ENUM_CLASS RecoStep { TPCConversion = 1,
                             TPCSliceTracking = 2,
                             TPCMerging = 4,
                             TPCCompression = 8,
                             TRDTracking = 16,
                             ITSTracking = 32,
                             TPCdEdx = 64,
                             TPCClusterFinding = 128,
                             TPCDecompression = 256,
                             Refit = 512,
                             AllRecoSteps = 0x7FFFFFFF,
                             NoRecoStep = 0 };
  enum ENUM_CLASS InOutType { TPCClusters = 1,
                              TPCSectorTracks = 2,
                              TPCMergedTracks = 4,
                              TPCCompressedClusters = 8,
                              TRDTracklets = 16,
                              TRDTracks = 32,
                              TPCRaw = 64 };

#ifdef GPUCA_NOCOMPAT_ALLOPENCL
  static constexpr const char* const DEVICE_TYPE_NAMES[] = {"INVALID", "CPU", "CUDA", "HIP", "OCL", "OCL2"};
  static constexpr const char* const RECO_STEP_NAMES[] = {"TPC Transformation", "TPC Sector Tracking", "TPC Track Merging and Fit", "TPC Compression", "TRD Tracking", "ITS Tracking", "TPC dEdx Computation", "TPC Cluster Finding", "TPC Decompression", "Global Refit"};
  static constexpr const char* const GENERAL_STEP_NAMES[] = {"Prepare", "QA"};
  typedef bitfield<RecoStep, unsigned int> RecoStepField;
  typedef bitfield<InOutType, unsigned int> InOutTypeField;
  constexpr static int N_RECO_STEPS = sizeof(GPUDataTypes::RECO_STEP_NAMES) / sizeof(GPUDataTypes::RECO_STEP_NAMES[0]);
  constexpr static int N_GENERAL_STEPS = sizeof(GPUDataTypes::GENERAL_STEP_NAMES) / sizeof(GPUDataTypes::GENERAL_STEP_NAMES[0]);
#endif
#ifdef GPUCA_NOCOMPAT
  static constexpr unsigned int NSLICES = 36;
#endif
  static DeviceType GetDeviceType(const char* type);
};

#ifdef GPUCA_NOCOMPAT_ALLOPENCL
struct GPURecoStepConfiguration {
  GPUDataTypes::RecoStepField steps = 0;
  GPUDataTypes::RecoStepField stepsGPUMask = GPUDataTypes::RecoStep::AllRecoSteps;
  GPUDataTypes::InOutTypeField inputs = 0;
  GPUDataTypes::InOutTypeField outputs = 0;
};
#endif

#ifdef GPUCA_NOCOMPAT

template <class T>
struct DefaultPtr {
  typedef T type;
};
template <class T>
struct ConstPtr {
  typedef const T type;
};

template <template <typename T> class S>
struct GPUCalibObjectsTemplate {
  typename S<TPCFastTransform>::type* fastTransform = nullptr;
  typename S<o2::base::MatLayerCylSet>::type* matLUT = nullptr;
  typename S<o2::trd::GeometryFlat>::type* trdGeometry = nullptr;
  typename S<TPCPadGainCalib>::type* tpcPadGain = nullptr;
  typename S<o2::tpc::CalibdEdxContainer>::type* dEdxCalibContainer = nullptr;
  typename S<o2::base::PropagatorImpl<float>>::type* o2Propagator = nullptr;
  typename S<o2::itsmft::TopologyDictionary>::type* itsPatternDict = nullptr;
};
typedef GPUCalibObjectsTemplate<DefaultPtr> GPUCalibObjects; // NOTE: These 2 must have identical layout since they are memcopied
typedef GPUCalibObjectsTemplate<ConstPtr> GPUCalibObjectsConst;

struct GPUTrackingInOutZS {
  static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES;
  static constexpr unsigned int NENDPOINTS = 20;
  struct GPUTrackingInOutZSSlice {
    const void* const* zsPtr[NENDPOINTS];
    const unsigned int* nZSPtr[NENDPOINTS];
    unsigned int count[NENDPOINTS];
  };
  struct GPUTrackingInOutZSCounts {
    unsigned int count[NSLICES][NENDPOINTS] = {};
  };
  struct GPUTrackingInOutZSMeta {
    void* ptr[NSLICES][NENDPOINTS];
    unsigned int n[NSLICES][NENDPOINTS];
  };
  GPUTrackingInOutZSSlice slice[NSLICES];
};

struct GPUTrackingInOutDigits {
  static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES;
  const o2::tpc::Digit* tpcDigits[NSLICES] = {nullptr};
  size_t nTPCDigits[NSLICES] = {0};
  const GPUTPCDigitsMCInput* tpcDigitsMC = nullptr;
};

struct GPUTrackingInOutPointers {
  GPUTrackingInOutPointers() = default;

  // TPC
  static constexpr unsigned int NSLICES = GPUDataTypes::NSLICES;
  const GPUTrackingInOutZS* tpcZS = nullptr;
  const GPUTrackingInOutDigits* tpcPackedDigits = nullptr;
  const GPUTPCClusterData* clusterData[NSLICES] = {nullptr};
  unsigned int nClusterData[NSLICES] = {0};
  const AliHLTTPCRawCluster* rawClusters[NSLICES] = {nullptr};
  unsigned int nRawClusters[NSLICES] = {0};
  const o2::tpc::ClusterNativeAccess* clustersNative = nullptr;
  const GPUTPCTrack* sliceTracks[NSLICES] = {nullptr};
  unsigned int nSliceTracks[NSLICES] = {0};
  const GPUTPCHitId* sliceClusters[NSLICES] = {nullptr};
  unsigned int nSliceClusters[NSLICES] = {0};
  const AliHLTTPCClusterMCLabel* mcLabelsTPC = nullptr;
  unsigned int nMCLabelsTPC = 0;
  const GPUTPCMCInfo* mcInfosTPC = nullptr;
  unsigned int nMCInfosTPC = 0;
  const GPUTPCMCInfoCol* mcInfosTPCCol = nullptr;
  unsigned int nMCInfosTPCCol = 0;
  const GPUTPCGMMergedTrack* mergedTracks = nullptr;
  unsigned int nMergedTracks = 0;
  const GPUTPCGMMergedTrackHit* mergedTrackHits = nullptr;
  const GPUTPCGMMergedTrackHitXYZ* mergedTrackHitsXYZ = nullptr;
  unsigned int nMergedTrackHits = 0;
  const unsigned int* mergedTrackHitAttachment = nullptr;
  const unsigned char* mergedTrackHitStates = nullptr;
  const o2::tpc::TrackTPC* outputTracksTPCO2 = nullptr;
  unsigned int nOutputTracksTPCO2 = 0;
  const unsigned int* outputClusRefsTPCO2 = nullptr;
  unsigned int nOutputClusRefsTPCO2 = 0;
  const o2::MCCompLabel* outputTracksTPCO2MC = nullptr;
  const o2::tpc::CompressedClustersFlat* tpcCompressedClusters = nullptr;

  // TPC links
  int* tpcLinkITS = nullptr;
  int* tpcLinkTRD = nullptr;
  int* tpcLinkTOF = nullptr;
  const o2::track::TrackParCov** globalTracks = nullptr;
  float* globalTrackTimes = nullptr;
  unsigned int nGlobalTracks = 0;

  // TRD
  const GPUTRDTrackletWord* trdTracklets = nullptr;
  const GPUTRDSpacePoint* trdSpacePoints = nullptr;
  unsigned int nTRDTracklets = 0;
  const GPUTRDTrackGPU* trdTracks = nullptr;
  const GPUTRDTrack* trdTracksO2 = nullptr;
  unsigned int nTRDTracks = 0;
  const float* trdTriggerTimes = nullptr;
  const int* trdTrackletIdxFirst = nullptr;
  const char* trdTrigRecMask = nullptr;
  unsigned int nTRDTriggerRecords = 0;
  const GPUTRDTrack* trdTracksITSTPCTRD = nullptr;
  unsigned int nTRDTracksITSTPCTRD = 0;
  const GPUTRDTrack* trdTracksTPCTRD = nullptr;
  unsigned int nTRDTracksTPCTRD = 0;

  // TOF
  const o2::tof::Cluster* tofClusters = nullptr;
  unsigned int nTOFClusters = 0;
  const o2::dataformats::MatchInfoTOF* itstpctofMatches = nullptr;
  unsigned int nITSTPCTOFMatches = 0;
  const o2::dataformats::MatchInfoTOF* itstpctrdtofMatches = nullptr;
  unsigned int nITSTPCTRDTOFMatches = 0;
  const o2::dataformats::MatchInfoTOF* tpctrdtofMatches = nullptr;
  unsigned int nTPCTRDTOFMatches = 0;
  const o2::dataformats::MatchInfoTOF* tpctofMatches = nullptr;
  unsigned int nTPCTOFMatches = 0;

  // ITS
  const o2::itsmft::CompClusterExt* itsCompClusters = nullptr;
  const o2::dataformats::MCTruthContainer<o2::MCCompLabel>* itsClusterMC = nullptr;
  const o2::BaseCluster<float>* itsClusters = nullptr;
  unsigned int nItsClusters = 0;
  const o2::itsmft::ROFRecord* itsClusterROF = nullptr;
  unsigned int nItsClusterROF = 0;
  const o2::its::TrackITS* itsTracks = nullptr;
  const o2::MCCompLabel* itsTrackMC = nullptr;
  unsigned int nItsTracks = 0;
  const int* itsTrackClusIdx = nullptr;
  const o2::itsmft::ROFRecord* itsTrackROF = nullptr;
  unsigned int nItsTrackROF = 0;

  // TPC-ITS
  const o2::dataformats::TrackTPCITS* tracksTPCITSO2 = nullptr;
  unsigned int nTracksTPCITSO2 = 0;

  // Common
  const GPUSettingsTF* settingsTF = nullptr;
};
#else
struct GPUTrackingInOutPointers {
};
struct GPUCalibObjectsConst {
};
#endif

#undef ENUM_CLASS
#undef ENUM_UINT
} // namespace gpu
} // namespace GPUCA_NAMESPACE

#endif


text:
constexpr int TabGroupUnderline::kStrokeThickness;

TabGroupUnderline::TabGroupUnderline(TabGroupViews* tab_group_views,
                                     const tab_groups::TabGroupId& group)
    : tab_group_views_(tab_group_views), group_(group) {}

void TabGroupUnderline::OnPaint(gfx::Canvas* canvas) {
  SkPath path = GetPath();
  cc::PaintFlags flags;
  flags.setAntiAlias(true);
  flags.setColor(tab_group_views_->GetGroupColor());
  flags.setStyle(cc::PaintFlags::kFill_Style);
  canvas->DrawPath(path, flags);
}

void TabGroupUnderline::UpdateBounds(const gfx::Rect& group_bounds) {
  const int start_x = GetStart(group_bounds);
  const int end_x = GetEnd(group_bounds);

  // The width may be zero if the group underline and header are initialized at
  // the same time, as with tab restore. In this case, don't update the bounds
  // and defer to the next paint cycle.
  if (end_x <= start_x)
    return;

  const int y =
      group_bounds.height() - GetLayoutConstant(TABSTRIP_TOOLBAR_OVERLAP);
  SetBounds(start_x, y - kStrokeThickness, end_x - start_x, kStrokeThickness);
}

// static
int TabGroupUnderline::GetStrokeInset() {
  return TabStyle::GetTabOverlap() + kStrokeThickness;
}

int TabGroupUnderline::GetStart(const gfx::Rect& group_bounds) const {
  return group_bounds.x() + GetStrokeInset();
}

int TabGroupUnderline::GetEnd(const gfx::Rect& group_bounds) const {
  const Tab* last_grouped_tab = tab_group_views_->GetLastTabInGroup();
  if (!last_grouped_tab)
    return group_bounds.right() - GetStrokeInset();

  return group_bounds.right() +
         (last_grouped_tab->IsActive() ? kStrokeThickness : -GetStrokeInset());
}

SkPath TabGroupUnderline::GetPath() const {
  SkPath path;

  path.moveTo(0, kStrokeThickness);
  path.arcTo(kStrokeThickness, kStrokeThickness, 0, SkPath::kSmall_ArcSize,
             SkPathDirection::kCW, kStrokeThickness, 0);
  path.lineTo(width() - kStrokeThickness, 0);
  path.arcTo(kStrokeThickness, kStrokeThickness, 0, SkPath::kSmall_ArcSize,
             SkPathDirection::kCW, width(), kStrokeThickness);
  path.close();

  return path;
}

BEGIN_METADATA(TabGroupUnderline, views::View)
END_METADATA


text:
package pl.touk.sputnik.review.locator;

import static org.apache.commons.lang3.StringUtils.substringBeforeLast;

import java.util.List;

import javax.annotation.Nullable;

import lombok.AllArgsConstructor;
import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

@AllArgsConstructor
public abstract class AbstractBuildDirLocator implements BuildDirLocator {

	private final String sourceDir;
	private final String testDir;

	public List<String> getBuildDirs(Review review) {
        return Lists.transform(review.getFiles(), new Function<ReviewFile, String>() {
            @Nullable
            @Override
            public String apply(ReviewFile file) {
                if (file.getReviewFilename().contains(sourceDir)) {
                    return substringBeforeLast(file.getReviewFilename(), sourceDir).concat(getMainBuildDir());
                }
                if (file.getReviewFilename().contains(testDir)) {
                    return substringBeforeLast(file.getReviewFilename(), testDir).concat(getTestBuildDir());
                }
                return file.getSourceDir();
            }
        });
    }

    protected abstract String getMainBuildDir();

    protected abstract String getTestBuildDir();
}


text:
package cluster

import (
	"sort"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestEngineSorter(t *testing.T) {
	engines := []*Engine{{Name: "name1"}, {Name: "name3"}, {Name: "name2"}}

	sort.Sort(EngineSorter(engines))

	assert.Equal(t, engines[0].Name, "name1")
	assert.Equal(t, engines[1].Name, "name2")
	assert.Equal(t, engines[2].Name, "name3")
}


text:
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Untitled-1</title>
    <script src="../public/script/jquery-1.9.1.js"></script>
    <script src="public/script/jquery-ui-1.10.2.custom.min.js"></script>
    <script src="public/script/jquery-ui.drag-multiple.min.js"></script>
    <script src="public/script/migrate/jquery-migrate-1.1.1.min.js"></script>
    <script src="public/script/alsodrag.js"></script>
    <script src="public/script/datasourcejs.js"></script>
    <script src="public/script/elements.js"></script>
    <script src="public/script/index.js"></script>
    <script src="public/script/jquery.contextmenu.r2.js"></script>
    <script src="public/script/colpick.js"></script>
    <link href="style/custom-theme2/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
    <link href="style/style.css" rel="stylesheet" />
    <link href="style/colpick.css" rel="stylesheet" />

</head>
<body style="margin:0">
    {{{body}}}

</body>
</html>


text:
module Azure::DeploymentManager::Mgmt::V2018_09_01_preview
  module Models
    #
    # The parameters for the wait step.
    #
    class WaitStepAttributes

      include MsRestAzure

      # @return [String] The duration in ISO 8601 format of how long the wait
      # should be.
      attr_accessor :duration

      #
      # Mapper for WaitStepAttributes class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'WaitStepAttributes',
          type: {
            name: 'Composite',
            class_name: 'WaitStepAttributes',
            model_properties: {
              duration: {
                client_side_validation: true,
                required: true,
                serialized_name: 'duration',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
How to do git signing
- Create a new GPG key and authorize it through github web
```bash
gpg --full-generate-key
```
Specify a 4096 key
Specify username/email to match GitHub (including name)
```bash
gpg --list-secret-keys --keyid-format=long
```
Using part after the /, export by the following
```bash
gpg --armor --export <key_id>
```
- Specify git to use the signing key
```bash
git config --global user.signingkey <key_id>
```
- Fixing errors:
  - export GPG_TTY=$(tty)


text:
export interface IPdfResult {
  name: string;
  id: string;
  buffer: Buffer;
}


text:
<?php

// clean the temp rows by...   (in seconds)
Configure::write('TempBehavior.options', array('tempTime' => '60'));
?>


text:
from datetime import timedelta

from django.contrib.auth.models import Group
from django.utils import timezone
from django_date_extensions.fields import ApproximateDate

from core.models import Event, User

def test_delete(events):
    assert Event.objects.count() == 4
    event = events[0]
    event.delete()
    assert Event.objects.count() == 3
    event = Event.all_objects.get(pk=event.pk)
    assert event.is_deleted is True

def test_has_stats():
    event = Event()
    assert event.has_stats is False

    event = Event(applicants_count=10)
    assert event.has_stats is False

    event = Event(attendees_count=20)
    assert event.has_stats is False

    event = Event(attendees_count=20, applicants_count=40)
    assert event.has_stats is True

def test_add_default_content(future_event):
    future_event.content.all().delete()
    assert future_event.content.count() == 0
    future_event.add_default_content()
    assert future_event.content.count() == 7

def test_add_default_menu(future_event):
    future_event.menu.all().delete()
    assert future_event.menu.count() == 0
    future_event.add_default_menu()
    assert future_event.menu.count() == 5

def test_invite_organizer_to_team(future_event):
    assert future_event.team.count() == 1
    user = User.objects.create(
        first_name="Alice",
        last_name="Smith",
        is_staff=True,
        is_active=True
    )
    future_event.invite_organizer_to_team(user, is_new_user=True, password="pass")
    assert future_event.team.count() == 2

def test_is_upcoming():
    now = timezone.now()
    now_event = Event(date=ApproximateDate(now.year, now.month, now.day))
    yesterday = now - timedelta(days=1)
    yesterday_event = Event(date=ApproximateDate(
        yesterday.year, yesterday.month, yesterday.day
    ))
    tomorrow = now + timedelta(days=1)
    tomorrow_event = Event(date=ApproximateDate(
        tomorrow.year, tomorrow.month, tomorrow.day
    ))
    assert now_event.is_upcoming()
    assert not yesterday_event.is_upcoming()
    assert tomorrow_event.is_upcoming()

def test_add_to_organizers_group(user):
    assert not Group.objects.filter(name="Organizers").exists()
    assert user.groups.count() == 0
    user.add_to_organizers_group()
    # we don't have Group "Organizers", so no group is added
    assert user.groups.count() == 0

    Group.objects.create(name="Organizers")
    user.add_to_organizers_group()
    assert user.groups.count() == 1

def test_has_organizer_no_organizer(user, future_event):
    future_event.main_organizer = None
    future_event.team.clear()

    assert not future_event.has_organizer(user)

def test_has_organizer_in_team(user, future_event):
    future_event.main_organizer = None
    future_event.team.add(user)

    assert future_event.has_organizer(user)

def test_has_organizer_main_organizer(user, future_event):
    future_event.main_organizer = user
    future_event.team.clear()

    assert future_event.has_organizer(user)


text:
import React from 'react'
import TimeAgo from 'timeago-react'

import Tooltip from '@/widgets/Tooltip'
import DotDivider from '@/widgets/DotDivider'

import {
  Wrapper,
  Contributors,
  Builder,
  Avatar,
  PopoverInfo,
  PopAvatar,
  PopLink,
  PublishInfo,
} from './styles/footer'

const Footer = ({ contributors, author, insertedAt }) => (
  <Wrapper>
    <Contributors>
      {contributors.map((builder) => (
        <Tooltip
          placement="bottom"
          key={builder.htmlUrl}
          content={
            <PopoverInfo>
              <PopAvatar src={builder.avatar} />
              <PopLink
                href={builder.htmlUrl}
                rel="noopener noreferrer"
                target="_blank"
              >
                @{builder.nickname}
              </PopLink>
            </PopoverInfo>
          }
        >
          <Builder>
            <Avatar src={builder.avatar} />
          </Builder>
        </Tooltip>
      ))}
    </Contributors>
    <PublishInfo>
      {author.nickname}
      <DotDivider />
      <TimeAgo datetime={insertedAt} locale="zh_CN" />
    </PublishInfo>
  </Wrapper>
)

export default React.memo(Footer)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated 25-March-2008 15:52:35.7187500 -->
<!-- Generated by MathSBML 2.7.2b -->
<!-- Generated using Mathematica Version 5.2 for Microsoft Windows (June 20, 2005) -->
<sbml xmlns="http://www.sbml.org/sbml/level2/version3"
    level="2"
    version="3">
 <model id="case00272"
     name="case00272"
     metaid="_case00272">
  <listOfFunctionDefinitions>
   <functionDefinition id="calculate"
       name="calculate">
    <math xmlns="http://www.w3.org/1998/Math/MathML">
     <lambda>
      <bvar>
       <ci>x</ci>
      </bvar>
      <bvar>
       <ci>y</ci>
      </bvar>
      <bvar>
       <ci>z</ci>
      </bvar>
      <piecewise>
       <piece>
        <ci>y</ci>
        <apply>
         <geq/>
         <ci>x</ci>
         <cn type="integer">4</cn>
        </apply>
       </piece>
       <otherwise>
        <ci>z</ci>
       </otherwise>
      </piecewise>
     </lambda>
    </math>
   </functionDefinition>
  </listOfFunctionDefinitions>
  <!-- <listOfUnitDefinitions/> -->
  <!-- <listOfCompartmentTypes/> -->
  <!-- <listOfSpeciesTypes/> -->
  <listOfCompartments>
   <compartment id="compartment"
       name="compartment"
       spatialDimensions="3"
       units="volume"
       size="1."/>
  </listOfCompartments>
  <listOfSpecies>
   <species id="S1"
       name="S1"
       compartment="compartment"
       boundaryCondition="false"
       constant="false"
       initialAmount="10"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S2"
       name="S2"
       compartment="compartment"
       boundaryCondition="false"
       constant="false"
       initialAmount="0"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S3"
       name="S3"
       compartment="compartment"
       boundaryCondition="false"
       constant="false"
       initialAmount="10"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S4"
       name="S4"
       compartment="compartment"
       boundaryCondition="false"
       constant="false"
       initialAmount="0"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
  </listOfSpecies>
  <listOfParameters>
   <parameter id="p1"
       name="p1"
       value="1.5"/>
   <parameter id="p2"
       name="p2"
       value="0.05"/>
   <parameter id="k1"
       name="k1"
       value="1."/>
  </listOfParameters>
  <!-- <listOfInitialAssignments/> -->
  <!-- <listOfRules/> -->
  <!-- <listOfConstraints/> -->
  <listOfReactions>
   <reaction id="reaction1"
       name="reaction1"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S1"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S2"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>compartment</ci>
       <ci>k1</ci>
       <ci>S1</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
   <reaction id="reaction2"
       name="reaction2"
       reversible="false"
       fast="false">
    <listOfReactants>
     <speciesReference species="S3"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S4"/>
    </listOfProducts>
    <listOfModifiers>
     <modifierSpeciesReference species="S2"/>
    </listOfModifiers>
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <ci>calculate</ci>
       <ci>S2</ci>
       <ci>p1</ci>
       <ci>p2</ci>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
  </listOfReactions>
  <!-- <listOfEvents/> -->
 </model>
</sbml>


text:
package net.rubygrapefruit.platform.prompts;

import net.rubygrapefruit.platform.terminal.TerminalInput;
import net.rubygrapefruit.platform.terminal.TerminalInputListener;
import net.rubygrapefruit.platform.terminal.TerminalOutput;
import net.rubygrapefruit.platform.terminal.Terminals;

import java.util.List;

class PlainPrompter extends AbstractPrompter {
    private final TerminalOutput output;
    private final TerminalInput input;

    PlainPrompter(Terminals terminals) {
        this.output = terminals.getTerminal(Terminals.Output.Stdout);
        this.input = terminals.getTerminalInput();
    }

    @Override
    boolean isInteractive() {
        return true;
    }

    @Override
    Integer select(String prompt, List<String> options, int defaultOption) {
        output.newline();
        output.bold().write(prompt).write(":").normal().newline();
        for (int i = 0; i < options.size(); i++) {
            if (i == defaultOption) {
                output.foreground(Prompter.SELECTION_COLOR).write(">").defaultForeground().write(" ");
            } else {
                output.write("  ");
            }
            output.write(String.valueOf((i + 1))).write(") ").write(options.get(i));
            if (i == defaultOption) {
                output.foreground(Prompter.SELECTION_COLOR).write(" (default)").defaultForeground();
            }
            output.newline();
        }
        while (true) {
            output.write("Please select an option (1..").write(String.valueOf(options.size())).write(") [").write(String.valueOf(defaultOption + 1)).write("] ");
            CollectingListener listener = new CollectingListener();
            while (listener.result == 0) {
                input.read(listener);
            }
            if (listener.result == 2) {
                return null;
            }
            String result = listener.chars.toString().trim();
            if (result.length() == 0) {
                return defaultOption;
            }
            if (result.length() == 1 && Character.isDigit(result.charAt(0))) {
                char ch = result.charAt(0);
                int index = ch - '0' - 1;
                if (index >= 0 && index < options.size()) {
                    return index;
                }
            }
        }
    }

    @Override
    String enterText(String prompt, String defaultValue) {
        output.newline();
        output.bold().write(prompt).normal();
        output.write(" [").write(defaultValue).write("]: ");
        CollectingListener listener = new CollectingListener();
        while (listener.result == 0) {
            input.read(listener);
        }
        if (listener.result == 2) {
            return null;
        }
        String result = listener.chars.toString().trim();
        if (result.length() == 0) {
            return defaultValue;
        }
        return result;
    }

    @Override
    Boolean askYesNo(String prompt, boolean defaultValue) {
        output.newline();
        while (true) {
            output.bold().write(prompt).normal();
            output.write("(y/n) [").write(defaultValue ? "y" : "n").write("]: ");
            CollectingListener listener = new CollectingListener();
            while (listener.result == 0) {
                input.read(listener);
            }
            if (listener.result == 2) {
                return null;
            }
            String result = listener.chars.toString().trim().toLowerCase();
            if (result.length() == 0) {
                return defaultValue;
            }
            if (result.equals("y") || result.equals("yes")) {
                return true;
            }
            if (result.equals("n") || result.equals("no")) {
                return false;
            }
        }
    }

    private static class CollectingListener implements TerminalInputListener {
        int result = 0;
        final StringBuilder chars = new StringBuilder();

        @Override
        public void character(char ch) {
            chars.append(ch);
        }

        @Override
        public void controlKey(Key key) {
            if (key == Key.Enter) {
                result = 1;
            }
        }

        @Override
        public void endInput() {
            result = 2;
        }
    }
}


text:
<?php
/**
 * A modal search dialog which uses search context to search for and add
 * existing records to a grid field.
 */
class GridFieldAddExistingSearchButton implements
	GridField_HTMLProvider,
	GridField_URLHandler {

	private static $allowed_actions = array(
		'handleSearch'
	);

	protected $title;
	protected $fragment;
	protected $searchList;

	/**
	 * @param string $fragment
	 */
	public function __construct($fragment = 'buttons-before-left') {
		$this->fragment = $fragment;
		$this->title    = _t('GridFieldExtensions.ADDEXISTING', 'Add Existing');
	}

	/**
	 * @return string
	 */
	public function getTitle() {
		return $this->title;
	}

	/**
	 * @param string $title
	 * @return GridFieldAddExistingSearchButton $this
	 */
	public function setTitle($title) {
		$this->title = $title;
		return $this;
	}

	/**
	 * @return string
	 */
	public function getFragment() {
		return $this->fragment;
	}

	/**
	 * @param string $fragment
	 * @return GridFieldAddExistingSearchButton $this
	 */
	public function setFragment($fragment) {
		$this->fragment = $fragment;
		return $this;
	}

	/**
	 * Sets a custom list to use to provide the searchable items.
	 *
	 * @param SS_List $list
	 * @return GridFieldAddExistingSearchButton $this
	 */
	public function setSearchList(SS_List $list) {
		$this->searchList = $list;
		return $this;
	}

	/**
	 * @return SS_List|null
	 */
	public function getSearchList() {
		return $this->searchList;
	}

	public function getHTMLFragments($grid) {
		GridFieldExtensions::include_requirements();

		$data = new ArrayData(array(
			'Title' => $this->getTitle(),
			'Link'  => $grid->Link('add-existing-search')
		));

		return array(
			$this->fragment => $data->renderWith('GridFieldAddExistingSearchButton'),
		);
	}

	public function getURLHandlers($grid) {
		return array(
			'add-existing-search' => 'handleSearch'
		);
	}

	public function handleSearch($grid, $request) {
		return new GridFieldAddExistingSearchHandler($grid, $this);
	}

}


text:
<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');

PatchUtil::db_add_column('apps_shoutbox_messages', 'deleted', 'I1');


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

    var Cell = function (initial) {
      var value = initial;
      var get = function () {
        return value;
      };
      var set = function (v) {
        value = v;
      };
      return {
        get: get,
        set: set
      };
    };

    var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

    var fireVisualBlocks = function (editor, state) {
      editor.fire('VisualBlocks', { state: state });
    };

    var toggleVisualBlocks = function (editor, pluginUrl, enabledState) {
      var dom = editor.dom;
      dom.toggleClass(editor.getBody(), 'mce-visualblocks');
      enabledState.set(!enabledState.get());
      fireVisualBlocks(editor, enabledState.get());
    };

    var register$1 = function (editor, pluginUrl, enabledState) {
      editor.addCommand('mceVisualBlocks', function () {
        toggleVisualBlocks(editor, pluginUrl, enabledState);
      });
    };

    var isEnabledByDefault = function (editor) {
      return editor.getParam('visualblocks_default_state', false, 'boolean');
    };

    var setup = function (editor, pluginUrl, enabledState) {
      editor.on('PreviewFormats AfterPreviewFormats', function (e) {
        if (enabledState.get()) {
          editor.dom.toggleClass(editor.getBody(), 'mce-visualblocks', e.type === 'afterpreviewformats');
        }
      });
      editor.on('init', function () {
        if (isEnabledByDefault(editor)) {
          toggleVisualBlocks(editor, pluginUrl, enabledState);
        }
      });
    };

    var toggleActiveState = function (editor, enabledState) {
      return function (api) {
        api.setActive(enabledState.get());
        var editorEventCallback = function (e) {
          return api.setActive(e.state);
        };
        editor.on('VisualBlocks', editorEventCallback);
        return function () {
          return editor.off('VisualBlocks', editorEventCallback);
        };
      };
    };
    var register = function (editor, enabledState) {
      var onAction = function () {
        return editor.execCommand('mceVisualBlocks');
      };
      editor.ui.registry.addToggleButton('visualblocks', {
        icon: 'visualblocks',
        tooltip: 'Show blocks',
        onAction: onAction,
        onSetup: toggleActiveState(editor, enabledState)
      });
      editor.ui.registry.addToggleMenuItem('visualblocks', {
        text: 'Show blocks',
        icon: 'visualblocks',
        onAction: onAction,
        onSetup: toggleActiveState(editor, enabledState)
      });
    };

    function Plugin () {
      global.add('visualblocks', function (editor, pluginUrl) {
        var enabledState = Cell(false);
        register$1(editor, pluginUrl, enabledState);
        register(editor, enabledState);
        setup(editor, pluginUrl, enabledState);
      });
    }

    Plugin();

}());


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;

namespace Microsoft.VisualStudio.IntegrationTest.Setup
{
    /// <summary>This class causes a crash if an exception is encountered by the editor.</summary>
    [Shared, Export(typeof(IExtensionErrorHandler)), Export(typeof(TestExtensionErrorHandler))]
    public class TestExtensionErrorHandler : IExtensionErrorHandler
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public TestExtensionErrorHandler()
        {
        }

        public void HandleError(object sender, Exception exception)
        {
            if (exception is ArgumentException argumentException
                && argumentException.Message.Contains("SnapshotPoint")
                && argumentException.StackTrace.Contains("Microsoft.VisualStudio.Text.Editor.Implementation.WpfTextView.ValidateBufferPosition"))
            {
                // Known issue https://github.com/dotnet/roslyn/issues/35123
                return;
            }

            if (exception is TaskCanceledException taskCanceledException
                && taskCanceledException.StackTrace.Contains("Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionsSourceProvider.SuggestedActionsSource.GetSuggestedActions"))
            {
                // Workaround for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1070469
                return;
            }

            FatalError.ReportAndPropagate(exception);
        }
    }
}


text:
namespace ash {
namespace phonehub {

FakeMessageSender::FakeMessageSender() = default;
FakeMessageSender::~FakeMessageSender() = default;

void FakeMessageSender::SendCrosState(bool notification_enabled,
                                      bool camera_roll_enabled) {
  cros_states_.push_back(
      std::make_pair(notification_enabled, camera_roll_enabled));
}

void FakeMessageSender::SendUpdateNotificationModeRequest(
    bool do_not_disturb_enabled) {
  update_notification_mode_requests_.push_back(do_not_disturb_enabled);
}

void FakeMessageSender::SendUpdateBatteryModeRequest(
    bool battery_saver_mode_enabled) {
  update_battery_mode_requests_.push_back(battery_saver_mode_enabled);
}

void FakeMessageSender::SendDismissNotificationRequest(
    int64_t notification_id) {
  dismiss_notification_requests_.push_back(notification_id);
}

void FakeMessageSender::SendNotificationInlineReplyRequest(
    int64_t notification_id,
    const std::u16string& reply_text) {
  notification_inline_reply_requests_.push_back(
      std::make_pair(notification_id, reply_text));
}

void FakeMessageSender::SendShowNotificationAccessSetupRequest() {
  show_notification_access_setup_count_++;
}

void FakeMessageSender::SendRingDeviceRequest(bool device_ringing_enabled) {
  ring_device_requests_.push_back(device_ringing_enabled);
}

void FakeMessageSender::SendFetchCameraRollItemsRequest(
    const proto::FetchCameraRollItemsRequest& request) {
  fetch_camera_roll_items_requests_.push_back(request);
}

void FakeMessageSender::SendFetchCameraRollItemDataRequest(
    const proto::FetchCameraRollItemDataRequest& request) {
  fetch_camera_roll_item_data_requests_.push_back(request);
}

void FakeMessageSender::SendInitiateCameraRollItemTransferRequest(
    const proto::InitiateCameraRollItemTransferRequest& request) {
  initiate_camera_roll_item_transfer_requests_.push_back(request);
}

size_t FakeMessageSender::GetCrosStateCallCount() const {
  return cros_states_.size();
}

size_t FakeMessageSender::GetUpdateNotificationModeRequestCallCount() const {
  return update_notification_mode_requests_.size();
}

size_t FakeMessageSender::GetUpdateBatteryModeRequestCallCount() const {
  return update_battery_mode_requests_.size();
}

size_t FakeMessageSender::GetDismissNotificationRequestCallCount() const {
  return dismiss_notification_requests_.size();
}

size_t FakeMessageSender::GetNotificationInlineReplyRequestCallCount() const {
  return notification_inline_reply_requests_.size();
}

size_t FakeMessageSender::GetRingDeviceRequestCallCount() const {
  return ring_device_requests_.size();
}

size_t FakeMessageSender::GetFetchCameraRollItemsRequestCallCount() const {
  return fetch_camera_roll_items_requests_.size();
}

size_t FakeMessageSender::GetFetchCameraRollItemDataRequestCallCount() const {
  return fetch_camera_roll_item_data_requests_.size();
}

size_t FakeMessageSender::GetInitiateCameraRollItemTransferRequestCallCount()
    const {
  return initiate_camera_roll_item_transfer_requests_.size();
}

std::pair<bool, bool> FakeMessageSender::GetRecentCrosState() const {
  return cros_states_.back();
}

bool FakeMessageSender::GetRecentUpdateNotificationModeRequest() const {
  return update_notification_mode_requests_.back();
}

bool FakeMessageSender::GetRecentUpdateBatteryModeRequest() const {
  return update_battery_mode_requests_.back();
}

int64_t FakeMessageSender::GetRecentDismissNotificationRequest() const {
  return dismiss_notification_requests_.back();
}

const std::pair<int64_t, std::u16string>
FakeMessageSender::GetRecentNotificationInlineReplyRequest() const {
  return notification_inline_reply_requests_.back();
}

bool FakeMessageSender::GetRecentRingDeviceRequest() const {
  return ring_device_requests_.back();
}

const proto::FetchCameraRollItemsRequest&
FakeMessageSender::GetRecentFetchCameraRollItemsRequest() const {
  return fetch_camera_roll_items_requests_.back();
}

const proto::FetchCameraRollItemDataRequest&
FakeMessageSender::GetRecentFetchCameraRollItemDataRequest() const {
  return fetch_camera_roll_item_data_requests_.back();
}

const proto::InitiateCameraRollItemTransferRequest&
FakeMessageSender::GetRecentInitiateCameraRollItemTransferRequest() const {
  return initiate_camera_roll_item_transfer_requests_.back();
}

}  // namespace phonehub
}  // namespace ash


text:
from AppKit import NSApp, NSPanel

windows = NSApp.windows()
panels = [window for window in windows if isinstance(window, NSPanel)]

for panel in panels:
    panel.performClose_(None)


text:
package org.apache.isis.viewer.wicket.ui.pages.actionprompt;

import org.apache.wicket.Component;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import org.apache.isis.viewer.wicket.model.models.ActionModel;
import org.apache.isis.viewer.wicket.ui.ComponentType;
import org.apache.isis.viewer.wicket.ui.pages.PageAbstract;

/**
 * Web page representing an action invocation.
 */
@AuthorizeInstantiation("org.apache.isis.viewer.wicket.roles.USER")
public class ActionPromptPage extends PageAbstract {

    private static final long serialVersionUID = 1L;

    /**
     * For use with {@link Component#setResponsePage(org.apache.wicket.Page)}
     */
    public ActionPromptPage(final ActionModel model) {
        super(new PageParameters(), model.getActionMemento().getAction().getName(), ComponentType.ACTION_PROMPT);
        addChildComponents(themeDiv, model);

        if(model.isBookmarkable()) {
            bookmarkPage(model);
        }
        addBookmarkedPages(themeDiv);
    }

    public ActionPromptPage(final PageParameters pageParameters) {
        this(pageParameters, buildModel(pageParameters));
    }

    public ActionPromptPage(final PageParameters pageParameters, final ActionModel model) {
        super(pageParameters, model.getActionMemento().getAction().getName(), ComponentType.ACTION_PROMPT);
        addChildComponents(themeDiv, model);

        // no need to bookmark because the ActionPanel will have done so for us
        addBookmarkedPages(themeDiv);
    }

    private static ActionModel buildModel(final PageParameters pageParameters) {
        return ActionModel.createForPersistent(pageParameters);
    }
}


text:
package glumelogger

import (
	"fmt"
	"git.apache.org/thrift.git/lib/go/thrift"
	"github.com/ceocoder/glumelogger/flume"
	"testing"
	"time"
)

const (
	testHostAndPort = "localhost:51515"
)

type thriftSourceProtocolHandler struct {
	t *testing.T
	//TODO: start the handler with expected event values - fail if writes are different from expected
}

func (ts thriftSourceProtocolHandler) AppendBatch(events []*flume.ThriftFlumeEvent) (flume.Status, error) {
	for _, event := range events {
		fmt.Println(string(event.GetBody()))
		ts.Append(event)
	}
	return flume.Status_OK, nil
}

func (ts thriftSourceProtocolHandler) Append(event *flume.ThriftFlumeEvent) (flume.Status, error) {
	ts.t.Log(string(event.GetBody()))
	return flume.Status_OK, nil
}

// run a test flume agent
func runDummyFlumeAgent(t *testing.T) {
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	protocolFactory := thrift.NewTCompactProtocolFactory()
	transport, _ := thrift.NewTServerSocket("localhost:51515")

	handler := thriftSourceProtocolHandler{t}
	processor := flume.NewThriftSourceProtocolProcessor(handler)
	server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)
	server.Serve()
}

func TestLogToFlumeViaThrift(t *testing.T) {
	go runDummyFlumeAgent(t)

	time.Sleep(1 * time.Millisecond)

	logger := NewGlumeLogger("localhost", 51515, &map[string]string{})
	status, err := logger.Log([]byte("foo"))
	if err != nil {
		t.Errorf("Write failed with %s, %s", status.String(), err)
		t.Fail()
	}
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.IotHub.Models
{
    internal partial class IotHubSkuDescriptionListResult
    {
        internal static IotHubSkuDescriptionListResult DeserializeIotHubSkuDescriptionListResult(JsonElement element)
        {
            Optional<IReadOnlyList<IotHubSkuDescription>> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<IotHubSkuDescription> array = new List<IotHubSkuDescription>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(IotHubSkuDescription.DeserializeIotHubSkuDescription(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new IotHubSkuDescriptionListResult(Optional.ToList(value), nextLink.Value);
        }
    }
}


text:
function _optimumxReinit(addClass){
	return function (assert){

		if(!window.devicePixelRatio){
			assert.ok(true);
			return;
		}
		var done = assert.async();

		this.promise.always(function($){
			var placeholderSrc, $image;
			var unveiled = 0;
			var initTest = function(){
				var success = [
					{
						u: 'data:,img1-5000',
						w: 5000,
						c: 'data:,img1-5000 5000w'
					},
					{
						u: 'data:,img1-50000',
						w: 50000,
						c: 'data:,img1-50000 50000w'
					},
					{
						u: 'data:,img1-500000',
						w: 500000,
						c: 'data:,img1-500000 500000w'
					}
				];
				assert.propEqual(cleanUpDensity($image.prop('_lazyOptimumx').cands), success);
				assert.equal($image.prop('_lazyOptimumx').cSrcset.length, 1);
				assert.equal($image.prop('_lazyOptimumx').cSrcset[0], 'data:,img1-5000 5000w');
				assert.equal($image.attr('srcset'), 'data:,img1-5000 5000w');
			};
			var reinitTest = function(){
				var success = [
					{
						u: 'data:,img2-50',
						w: 50,
						c: 'data:,img2-50 50w'
					},
					{
						u: 'data:,img2-100',
						w: 100,
						c: 'data:,img2-100 100w'
					},
					{
						u: 'data:,img2-500000',
						w: 500000,
						c: 'data:,img2-500000 500000w'
					}
				];
				assert.propEqual(cleanUpDensity($image.prop('_lazyOptimumx').cands), success);
				assert.equal($image.prop('_lazyOptimumx').cSrcset.length, 2, '1');
				assert.equal($image.prop('_lazyOptimumx').cSrcset[0], 'data:,img2-50 50w', '2');
				assert.equal($image.prop('_lazyOptimumx').cSrcset[1], 'data:,img2-100 100w', '3');
				assert.equal($image.attr('srcset'), 'data:,img2-50 50w, data:,img2-100 100w', '4');
			};
			var test = [
				['\ndata:,img1-50000 50000w, \ndata:,img1-5000 5000w, data:,img1-500000 500000w', initTest],
				['\ndata:,img2-100 100w, \ndata:,img2-500000 500000w, \ndata:,img2-50 50w', reinitTest]
			];
			var run = function(){
				if(test.length){
					placeholderSrc = test.shift();
					$image
						.attr('data-srcset', placeholderSrc[0])
						.attr('data-optimumx', '0.6')
					;

					if(addClass){
						$image.addClass('lazyload');
					}
				} else {
					setTimeout(function(){
						ok(unveiled == 2);
						done();
					}, 130);
				}
			};

			$image = $('')
				.appendTo('body')
			;

			$image.on('lazybeforeunveil', function(e){
				unveiled++;
			});

			$image.on('lazybeforeunveil', function(e){
				afterUnveil(function(){
					placeholderSrc[1]();
					setTimeout(run, 20);
				});
			});

			run();
		});
	};
}

$.extend(window.lazyTests, {
	bgsetParentFit: ['lazyloads bgsetParentFit', function(assert){
		var done = assert.async();
		var $iframe = this.$iframe;

		this.promise.always(function($, frameWindow){
			var viewport;
			var $div = $('
')
				.attr({
					'data-bgset': '\ndata:,jo2 400w 800h, \ndata:,jo3 800w 1600h, data:,jo4 1200w 2400h [(max-width: 300px)] | ' +
					'data:,jo5 800h 500w',
					'data-sizes': 'auto',
					'class': 'lazyload',
					'data-optimumx': '0.6'
				})
				.css({
					display: 'block',
					width: 400,
					height: 400,
					backgroundSize: 'contain'
				})
				.appendTo('body')
			;
			var initialTest = function(){
				assert.equal($('source').eq(0).attr('sizes'), '200px');
			};

			var endTest = function(){
				assert.equal($('source').eq(1).attr('sizes'), '250px');
			};
			var viewportTests = [
				['300', initialTest],
				['500', endTest]
			];

			var run = function(){
				if(viewportTests.length){
					viewport = viewportTests.shift();
					$iframe.css('width', viewport[0]);
				} else {
					done();
				}
			};
			run();

			$div.on('lazybeforesizes', function(e){
				afterUnveil(function(){
					viewport[1]();
					run();
				});
			});

		});
	}],
	optimumxPictureResize: ['lazyloads constraints srcset on picture', function(assert){
		var done = assert.async();
		var $iframe = this.$iframe;

		this.promise.always(function($, frameWindow){
			var viewport;
			var $picture = createPicture($, [
				{
					'data-srcset': '\n\ndata:,lazysource150 150w, \ndata:,lazysource100 100w, \ndata:,lazysource280 280w',
					media: '(min-width: 0.5em)'
				},
				{
					'data-srcset': '\ndata:,lazyimg100 100w, \n\ndata:,lazyimg200 200w, \n\ndata:,lazyimg150 150w',
					'data-optimumx': '0.5',
					'data-sizes': 'auto',
					'class': 'lazyload'
				}
			]);
			var $source = $picture.find('source');
			var $image = $picture.find('img');
			var initialTest = function(){
				var haspolyfill = frameWindow.respimage || frameWindow.picturefill || (frameWindow.lazySizes.cfg.rias && frameWindow.lazySizes.pWS) || frameWindow.lazySizes.cfg.pf;
				var nowSrc = window.HTMLPictureElement || !haspolyfill ?
					'' : 'data:,lazysource150';

				assert.equal($source.attr('srcset'), 'data:,lazysource100 100w, data:,lazysource150 150w');

				if(!window.bustedSrcset || !frameWindow.lazySizes.cfg.pf){
					assert.equal($image.attr('srcset') || $image.attr('data-risrcset') || $image.attr('data-pfsrcset'), 'data:,lazyimg100 100w, data:,lazyimg150 150w');
				}
				assert.equal($image.prop('src'), nowSrc, 'jo');
			};

			var endTest = function(){
				var haspolyfill = frameWindow.respimage || frameWindow.picturefill || (frameWindow.lazySizes.cfg.rias && frameWindow.lazySizes.pWS) || frameWindow.lazySizes.cfg.pf;
				var nowSrc = window.HTMLPictureElement || !haspolyfill ?
					'' : 'data:,lazysource280';
				assert.equal($source.attr('srcset'), 'data:,lazysource100 100w, data:,lazysource150 150w, data:,lazysource280 280w');
				if(!window.bustedSrcset || !frameWindow.lazySizes.cfg.pf){
					assert.equal($image.attr('srcset') || $image.attr('data-risrcset') || $image.attr('data-pfsrcset'), 'data:,lazyimg100 100w, data:,lazyimg150 150w, data:,lazyimg200 200w');
				}
				assert.equal($image.prop('src'), nowSrc);
			};
			var viewportTests = [
				['300', initialTest],
				['200', initialTest],
				['500', endTest]
			];

			var run = function(){
				if(viewportTests.length){
					viewport = viewportTests.shift();
					$iframe.css('width', viewport[0]);
				} else {
					done();
				}
			};

			if(!window.devicePixelRatio){
				assert.ok(true);
				done();
				return;
			}
			run();

			$picture.appendTo('body');

			assert.equal($source.attr('srcset'), null);
			assert.equal($image.attr('srcset'), null);

			$image.on('lazybeforesizes', function(e){
				afterUnveil(function(){
					assert.equal($source.attr('src'), null);
					assert.equal($source.attr('data-src'), null);
					viewport[1]();
					run();
				});
			});

		});
	}],
	optimumxRiasPictureResize: ['lazyloads constraints rias generated srcset on picture', function(assert){
		if(!supportsPicture){
			assert.ok(true);
			return;
		}
		var done = assert.async();
		var $iframe = this.$iframe;

		this.promise.always(function($, frameWindow){
			var viewport;
			var $picture = createPicture($, [
				{
					'data-srcset': 'data:,lazysource{width}',
					media: '(min-width: 0.5em)'
				},
				{
					'data-srcset': 'data:,lazyimg{width}',
					'data-optimumx': '0.5',
					'data-sizes': 'auto',
					'data-widths': '[100, 150, 280]',
					'class': 'lazyload'
				}
			]);
			var $source = $picture.find('source');
			var $image = $picture.find('img');
			var initialTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,lazysource150';
				assert.equal($source.attr('srcset'), 'data:,lazysource100 100w, data:,lazysource150 150w');
				assert.equal($image.attr('srcset') || $image.attr('data-risrcset') || $image.attr('data-pfsrcset') || 'data:,lazyimg100 100w, data:,lazyimg150 150w', 'data:,lazyimg100 100w, data:,lazyimg150 150w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var endTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,lazysource280';
				assert.equal($source.attr('srcset'), 'data:,lazysource100 100w, data:,lazysource150 150w, data:,lazysource280 280w');
				assert.equal($image.attr('srcset') || $image.attr('data-risrcset') || $image.attr('data-pfsrcset') || 'data:,lazyimg100 100w, data:,lazyimg150 150w, data:,lazyimg280 280w', 'data:,lazyimg100 100w, data:,lazyimg150 150w, data:,lazyimg280 280w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var viewportTests = [
				['300', initialTest],
				['200', initialTest],
				['500', endTest]
			];
			var run = function(){
				if(viewportTests.length){
					viewport = viewportTests.shift();
					$iframe.css('width', viewport[0]);
				} else {
					done();
				}
			};

			if(!window.devicePixelRatio){
				assert.ok(true);
				done();
				return;
			}
			run();

			$picture.appendTo('body');

			assert.equal($source.attr('srcset'), null);
			assert.equal($image.attr('srcset'), null);

			$image.on('lazybeforesizes', function(e){
				afterUnveil(function(){
					assert.equal($source.attr('src'), null);
					assert.equal($source.attr('data-src'), null);
					viewport[1]();
					run();
				});
			});

		});
	}],
	riasResize: ['lazysizes rias reacts on resize', function(assert){
		var done = assert.async();
		var $iframe = this.$iframe;

		this.promise.always(function($, frameWindow){
			var viewport, $image;
			var initTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,img-small-yo';
				assert.equal($image.attr('srcset') || 'data:,img-1-yo 1w, data:,img-small-yo 500w, data:,img-large-yo 1200w', 'data:,img-1-yo 1w, data:,img-small-yo 500w, data:,img-large-yo 1200w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var largerTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,img-large-yo';
				assert.equal($image.attr('srcset') || 'data:,img-1-yo 1w, data:,img-small-yo 500w, data:,img-large-yo 1200w', 'data:,img-1-yo 1w, data:,img-small-yo 500w, data:,img-large-yo 1200w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var viewportTests = [
				['200', initTest],
				['250', initTest],
				['1200', largerTest],
				['800', largerTest]
			];
			var run = function(){
				if(viewportTests.length){
					viewport = viewportTests.shift();
					$iframe.css('width', viewport[0]);
				} else {
					done();
				}
			};
			run();

			frameWindow.document.addEventListener('lazyriasmodifyoptions', function(e){
				// change available widths and widthmap for .special-widths elements
				e.detail.widthmap = {
					500: 'small',
					1200: 'large'
				};

				//add new custom property with value 'foo'
				e.detail.foo = 'yo';
			});

			$image = $('
' +
			'' +
			'
')
				.appendTo('body')
				.find('img');

			$image.on('lazybeforesizes', function(e){
				afterUnveil(function(){
					viewport[1]();
					run();
				});
			});
		});
	}],
	riasPictureResize: ['lazysizes rias reacts on resize and allows art direction', function(assert){
		var done = assert.async();
		var $iframe = this.$iframe;

		this.promise.always(function($, frameWindow){
			var viewport;
			var initTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,lazysource900';
				assert.equal($image.attr('srcset') || 'data:,lazyimg900 900w, data:,lazyimg1500 1500w', 'data:,lazyimg900 900w, data:,lazyimg1500 1500w');
				assert.equal($source.attr('srcset'), 'data:,lazysource900 900w, data:,lazysource1500 1500w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var largerTest = function(){
				var nowSrc = window.HTMLPictureElement ?
					'' : 'data:,lazyimg1500';
				assert.equal($image.attr('srcset') || 'data:,lazyimg900 900w, data:,lazyimg1500 1500w', 'data:,lazyimg900 900w, data:,lazyimg1500 1500w');
				assert.equal($source.attr('srcset'), 'data:,lazysource900 900w, data:,lazysource1500 1500w');
				assert.equal($image.prop('src'), nowSrc);
			};
			var viewportTests = [
				['300', initTest],
				['400', initTest],
				['1500', largerTest],
				['1220', largerTest],
				['450', initTest]
			];
			var run = function(){
				if(viewportTests.length){
					viewport = viewportTests.shift();
					$iframe.css('width', viewport[0]);
				} else {
					done();
				}
			};
			var $picture = createPicture($, [
				{
					'data-srcset': 'data:,lazysource{width}',
					media: '(max-width: 500px)'
				},
				{
					'data-srcset': 'data:,lazyimg{width}',
					'data-sizes': 'auto',
					'data-widths': '[900, 1500]',
					'class': 'lazyload'
				}
			]);
			var $source = $picture.find('source');
			var $image = $picture.find('img');

			run();

			$picture.appendTo('body');

			$image.on('lazybeforesizes', function(e){
				afterUnveil(function(){
					viewport[1]();
					run();
				});
			});
		});
	}],
	riasReinit: ['lazysizes rias can be re-initialized', function(assert){
		var done = assert.async();

		this.promise.always(function($, frameWindow){
			var placeholderSrc, $image;
			var initTest = function(){
				var success = [
					{
						u: 'data:,img1-1',
						w: 1,
						c: 'data:,img1-1 1w'
					},
					{
						u: 'data:,img1-500',
						w: 500,
						c: 'data:,img1-500 500w'
					},
					{
						u: 'data:,img1-1200',
						w: 1200,
						c: 'data:,img1-1200 1200w'
					}
				];
				assert.propEqual(cleanUpDensity($image.prop('_lazyrias')), success);
				assert.equal($image.attr('srcset') || 'data:,img1-1 1w, data:,img1-500 500w, data:,img1-1200 1200w', 'data:,img1-1 1w, data:,img1-500 500w, data:,img1-1200 1200w');
			};
			var reinitTest = function(){
				var success = [
					{
						u: 'data:,img2-1',
						w: 1,
						c: 'data:,img2-1 1w'
					},
					{
						u: 'data:,img2-500',
						w: 500,
						c: 'data:,img2-500 500w'
					},
					{
						u: 'data:,img2-1200',
						w: 1200,
						c: 'data:,img2-1200 1200w'
					}
				];
				assert.propEqual(cleanUpDensity($image.prop('_lazyrias')), success);
				assert.equal($image.attr('srcset') || 'data:,img2-1 1w, data:,img2-500 500w, data:,img2-1200 1200w', 'data:,img2-1 1w, data:,img2-500 500w, data:,img2-1200 1200w');
			};
			var test = [
				['data:,img1-{width}', initTest],
				['data:,img2-{width}', reinitTest]
			];
			var run = function(){
				if(test.length){
					placeholderSrc = test.shift();

					if(window.isTrident){
						$image.addClass('lazyerror');
					}

					$image
						.attr('data-src', placeholderSrc[0])
						.addClass('lazyload')
					;
				} else {
					done();
				}
			};
			$image = $('');

			$image.on('lazybeforeunveil', function(e){
				afterUnveil(function(){
					placeholderSrc[1]();
					setTimeout(run, 17);
				});
			});

			$image.appendTo('body');

			run();
		});
	}],
	optimumxReinit: ['lazysizes optimumx can be re-initialized', _optimumxReinit(true)],
	optimumxAttrchangeReinit: ['lazysizes optimumx can be re-initialized', _optimumxReinit(false)],
	riasAutoSizes: ['lazysizes rias works with autosizes simple sizes', function(assert){
		var done = assert.async();

		this.promise.always(function($){
			var $image;

			$image = $('')
				.attr('data-src', 'data:,image-{width}')
				.appendTo('body')
			;

			$image.on('lazybeforeunveil', function(e){
				afterUnveil(function(){
					assert.equal($image.prop('currentSrc') || $image.attr('src'), 'data:,image-900');
					done();
				});
			});
		});
	}],
	noscriptImg: ['noscript img', function(assert){
		var done = assert.async();

		this.promise.always(function($, frameWindow){
			var $noscript;

			var errors = 0;
			var onerror = function(){
				errors++;
			};

			$noscript = $('
' +
				'' +
				'' +
				'
')
				.appendTo('body')
			;

			frameWindow.addEventListener('error', onerror);

			$noscript.on('lazybeforeunveil', function(e){
				afterUnveil(function(){
					assert.equal($noscript.find('img').attr('src'), 'data:,img');
					assert.equal(errors, 0);
					frameWindow.removeEventListener('error', onerror);
					done();
				});
			});
		});
	}]
});

QUnit.module( "optimumx", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.simplePicture);
QUnit.test.apply(QUnit, lazyTests.optimumxReinit);

QUnit.module( "optimumx + mini respimg polyfill", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx', 'respimg']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.optimumxPictureResize);

QUnit.module( "optimumx + respimage + respmutation", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx'],
			libs: ['respimage', 'respmutation']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.optimumxPictureResize);

QUnit.module( "optimumx + rias", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx', 'rias']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.optimumxRiasPictureResize);
QUnit.test.apply(QUnit, lazyTests.riasResize);
QUnit.test.apply(QUnit, lazyTests.riasPictureResize);
QUnit.test.apply(QUnit, lazyTests.simplePicture);
QUnit.test.apply(QUnit, lazyTests.riasReinit);
QUnit.test.apply(QUnit, lazyTests.riasAutoSizes);

QUnit.module( "optimumx + rias + respimage", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx', 'rias'],
			libs: ['respimage']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.optimumxPictureResize);
QUnit.test.apply(QUnit, lazyTests.riasResize);
QUnit.test.apply(QUnit, lazyTests.riasPictureResize);
QUnit.test.apply(QUnit, lazyTests.simpleAutoSizesPicture);
QUnit.test.apply(QUnit, lazyTests.riasReinit);
QUnit.test.apply(QUnit, lazyTests.riasAutoSizes);

QUnit.module( "rias", {
	beforeEach: createBeforeEach(
		{
			plugins: ['rias']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.riasResize);
QUnit.test.apply(QUnit, lazyTests.riasPictureResize);
QUnit.test.apply(QUnit, lazyTests.simplePicture);
QUnit.test.apply(QUnit, lazyTests.riasReinit);
QUnit.test.apply(QUnit, lazyTests.riasAutoSizes);

QUnit.module( "rias + respimage", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx', 'rias'],
			libs: ['respimage']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.riasResize);
QUnit.test.apply(QUnit, lazyTests.riasPictureResize);
QUnit.test.apply(QUnit, lazyTests.riasReinit);
QUnit.test.apply(QUnit, lazyTests.riasAutoSizes);

QUnit.module( "mini respimg polyfill", {
	beforeEach: createBeforeEach(
		{
			plugins: ['respimg']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.simplePicture);
QUnit.test.apply(QUnit, lazyTests.simpleAutoSizesPicture);
QUnit.test.apply(QUnit, lazyTests.simpleSrcset);
QUnit.test.apply(QUnit, lazyTests.simpleSrcsetSrc);

QUnit.module( "noscript", {
	beforeEach: createBeforeEach(
		{
			plugins: ['noscript']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.noscriptImg);

QUnit.module( "attrchange + rias", {
	beforeEach: createBeforeEach(
		{
			plugins: ['attrchange', 'rias']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.riasResize);
QUnit.test.apply(QUnit, lazyTests.riasPictureResize);
QUnit.test.apply(QUnit, lazyTests.riasReinit);

QUnit.module( "attrchange + optimumx mix", {
	beforeEach: createBeforeEach(
		{
			plugins: ['attrchange', 'optimumx']
		}
	)
});

QUnit.test.apply(QUnit, lazyTests.optimumxReinit);
QUnit.test.apply(QUnit, lazyTests.optimumxAttrchangeReinit);

QUnit.module( "parentFit + bgset + optimumx", {
	beforeEach: createBeforeEach(
		{
			plugins: ['optimumx', 'parentFit', 'bgset'],
			libs: ['respimage']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.bgsetParentFit);

QUnit.module( "parentFit + bgset + respimg", {
	beforeEach: createBeforeEach(
		{
			plugins: ['parentFit', 'bgset', 'respimg']
		}
	)
});
QUnit.test.apply(QUnit, lazyTests.bgsetParentFit);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>_-Index</title>
<meta name="date" content="2015-03-27">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P Q R S T U V W Z _

_

_PackageAccessAnimation - Class in com.github.sviengine.animation

_PackageAccessAnimation() - Constructor for class com.github.sviengine.animation._PackageAccessAnimation

_PackageAccessBasetype - Class in com.github.sviengine.basetype

_PackageAccessBasetype() - Constructor for class com.github.sviengine.basetype._PackageAccessBasetype

_PackageAccessSlide - Class in com.github.sviengine.slide

_PackageAccessSlide() - Constructor for class com.github.sviengine.slide._PackageAccessSlide

A B C D E F G H I K L M N O P Q R S T U V W Z _

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package one.kii.kiimate.model.core.api;

import lombok.Data;
import lombok.EqualsAndHashCode;
import one.kii.summer.asdf.api.VisitApi;
import one.kii.summer.io.context.ReadContext;
import one.kii.summer.io.exception.BadRequest;
import one.kii.summer.io.exception.NotFound;
import one.kii.summer.io.exception.Panic;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by WangYanJiong on 3/23/17.
 */
public interface VisitIntensionsApi extends VisitApi<VisitIntensionsApi.Receipt, ReadContext, VisitIntensionsApi.Form> {

    String VISIBILITY_PUBLIC = "public";

    Receipt visit(ReadContext context, Form form) throws BadRequest, NotFound, Panic;

    @Data
    class Form {
        String group;
        String name;
        String tree;
        String visibility = VISIBILITY_PUBLIC;
    }

    @Data
    class Receipt {

        private String extId;

        private String ownerId;

        private String group;

        private String name;

        private String tree;

        private List<Intension> intensions;
    }

    @Data
    class Intension {

        private String id;

        private String field;

        private Boolean single;

        private String structure;

        private String refSet;

        private String visibility;

        private Boolean required;
    }

}


text:
// Copyright 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Ben Darnell
// Author: Tamir Duberstein (tamird@gmail.com)

package pgwire

import (
	"bufio"
	"fmt"
	"net"
	"reflect"
	"strconv"

	"github.com/lib/pq/oid"

	"github.com/cockroachdb/cockroach/roachpb"
	"github.com/cockroachdb/cockroach/sql"
	"github.com/cockroachdb/cockroach/sql/parser"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
	"github.com/cockroachdb/cockroach/util/tracing"
)

//go:generate stringer -type=clientMessageType
type clientMessageType byte

//go:generate stringer -type=serverMessageType
type serverMessageType byte

// http://www.postgresql.org/docs/9.4/static/protocol-message-formats.html
const (
	clientMsgSimpleQuery clientMessageType = 'Q'
	clientMsgParse       clientMessageType = 'P'
	clientMsgTerminate   clientMessageType = 'X'
	clientMsgDescribe    clientMessageType = 'D'
	clientMsgSync        clientMessageType = 'S'
	clientMsgClose       clientMessageType = 'C'
	clientMsgBind        clientMessageType = 'B'
	clientMsgExecute     clientMessageType = 'E'

	serverMsgAuth                 serverMessageType = 'R'
	serverMsgCommandComplete      serverMessageType = 'C'
	serverMsgDataRow              serverMessageType = 'D'
	serverMsgErrorResponse        serverMessageType = 'E'
	serverMsgParseComplete        serverMessageType = '1'
	serverMsgReady                serverMessageType = 'Z'
	serverMsgRowDescription       serverMessageType = 'T'
	serverMsgEmptyQuery           serverMessageType = 'I'
	serverMsgParameterDescription serverMessageType = 't'
	serverMsgBindComplete         serverMessageType = '2'
	serverMsgParameterStatus      serverMessageType = 'S'
	serverMsgNoData               serverMessageType = 'n'
)

//go:generate stringer -type=prepareType
type prepareType byte

const (
	prepareStatement prepareType = 'S'
	preparePortal    prepareType = 'P'
)

const (
	authOK int32 = 0
)

// preparedStatement is a SQL statement that has been parsed and the types
// of arguments and results have been determined.
type preparedStatement struct {
	query       string
	inTypes     []oid.Oid
	columns     []sql.ResultColumn
	portalNames map[string]struct{}
}

// preparedPortal is a preparedStatement that has been bound with parameters.
type preparedPortal struct {
	stmt       preparedStatement
	stmtName   string
	params     []parser.Datum
	outFormats []formatCode
}

type v3Conn struct {
	rd       *bufio.Reader
	wr       *bufio.Writer
	opts     opts
	executor *sql.Executor
	readBuf  readBuffer
	writeBuf writeBuffer
	tagBuf   [64]byte
	session  sql.Session

	preparedStatements map[string]preparedStatement
	preparedPortals    map[string]preparedPortal

	// The logic governing these guys is hairy, and is not sufficiently
	// specified in documentation. Consult the sources before you modify:
	// https://github.com/postgres/postgres/blob/master/src/backend/tcop/postgres.c
	doingExtendedQueryMessage, ignoreTillSync bool

	metrics *serverMetrics
}

type opts struct {
	user, database string
}

func makeV3Conn(conn net.Conn, executor *sql.Executor, metrics *serverMetrics) v3Conn {
	return v3Conn{
		rd:                 bufio.NewReader(conn),
		wr:                 bufio.NewWriter(conn),
		executor:           executor,
		writeBuf:           writeBuffer{bytecount: metrics.bytesOutCount},
		preparedStatements: make(map[string]preparedStatement),
		preparedPortals:    make(map[string]preparedPortal),
		metrics:            metrics,
	}
}

func (c *v3Conn) parseOptions(data []byte) error {
	buf := readBuffer{msg: data}
	for {
		key, err := buf.getString()
		if err != nil {
			return util.Errorf("error reading option key: %s", err)
		}
		if len(key) == 0 {
			return nil
		}
		value, err := buf.getString()
		if err != nil {
			return util.Errorf("error reading option value: %s", err)
		}
		switch key {
		case "database":
			c.opts.database = value
		case "user":
			c.opts.user = value
		default:
			if log.V(1) {
				log.Warningf("unrecognized configuration parameter %q", key)
			}
		}
	}
}

func (c *v3Conn) serve(authenticationHook func(string, bool) error) error {
	if authenticationHook != nil {
		if err := authenticationHook(c.opts.user, true /* public */); err != nil {
			return c.sendError(err.Error())
		}
	}
	c.writeBuf.initMsg(serverMsgAuth)
	c.writeBuf.putInt32(authOK)
	if err := c.writeBuf.finishMsg(c.wr); err != nil {
		return err
	}
	for key, value := range map[string]string{
		"client_encoding": "UTF8",
		"DateStyle":       "ISO",
		// The latest version of the docs that was consulted during the development
		// of this package. We specify this version to avoid having to support old
		// code paths which various client tools fall back to if they can't
		// determine that the server is new enough.
		"server_version": "9.5.0",
	} {
		c.writeBuf.initMsg(serverMsgParameterStatus)
		for _, str := range [...]string{key, value} {
			if err := c.writeBuf.writeString(str); err != nil {
				return err
			}
		}
		if err := c.writeBuf.finishMsg(c.wr); err != nil {
			return err
		}
	}
	if err := c.wr.Flush(); err != nil {
		return err
	}

	for {
		if !c.doingExtendedQueryMessage {
			c.writeBuf.initMsg(serverMsgReady)
			var txnStatus byte = 'I'
			if sessionTxn := c.session.Txn; sessionTxn != nil {
				switch sessionTxn.Txn.Status {
				case roachpb.PENDING:
					txnStatus = 'T'
				case roachpb.COMMITTED:
					txnStatus = 'I'
				case roachpb.ABORTED:
					txnStatus = 'E'
				}
			}
			if log.V(2) {
				log.Infof("pgwire: %s: %q", serverMsgReady, txnStatus)
			}
			c.writeBuf.WriteByte(txnStatus)
			if err := c.writeBuf.finishMsg(c.wr); err != nil {
				return err
			}
		}
		// If the buffer is empty (which is the case if ignoring messages),
		// this does nothing.
		if err := c.wr.Flush(); err != nil {
			return err
		}
		typ, n, err := c.readBuf.readTypedMsg(c.rd)
		c.metrics.bytesInCount.Inc(int64(n))
		if err != nil {
			return err
		}
		// When an error occurs handling an extended query message, we have to ignore
		// any messages until we get a sync.
		if c.ignoreTillSync && typ != clientMsgSync {
			if log.V(2) {
				log.Infof("pgwire: ignoring %s till sync", typ)
			}
			continue
		}
		if log.V(2) {
			log.Infof("pgwire: processing %s", typ)
		}
		switch typ {
		case clientMsgSync:
			c.doingExtendedQueryMessage = false
			c.ignoreTillSync = false

		case clientMsgSimpleQuery:
			c.doingExtendedQueryMessage = false
			err = c.handleSimpleQuery(&c.readBuf)

		case clientMsgTerminate:
			return nil

		case clientMsgParse:
			c.doingExtendedQueryMessage = true
			err = c.handleParse(&c.readBuf)

		case clientMsgDescribe:
			c.doingExtendedQueryMessage = true
			err = c.handleDescribe(&c.readBuf)

		case clientMsgClose:
			c.doingExtendedQueryMessage = true
			err = c.handleClose(&c.readBuf)

		case clientMsgBind:
			c.doingExtendedQueryMessage = true
			err = c.handleBind(&c.readBuf)

		case clientMsgExecute:
			c.doingExtendedQueryMessage = true
			err = c.handleExecute(&c.readBuf)

		default:
			err = c.sendError(fmt.Sprintf("unrecognized client message type %s", typ))
		}
		if err != nil {
			return err
		}
	}
}

func (c *v3Conn) handleSimpleQuery(buf *readBuffer) error {
	query, err := buf.getString()
	if err != nil {
		return err
	}

	return c.executeStatements(query, nil, nil, true, 0)
}

func (c *v3Conn) handleParse(buf *readBuffer) error {
	name, err := buf.getString()
	if err != nil {
		return err
	}
	// The unnamed prepared statement can be freely overwritten.
	if name != "" {
		if _, ok := c.preparedStatements[name]; ok {
			return c.sendError(fmt.Sprintf("prepared statement %q already exists", name))
		}
	}
	query, err := buf.getString()
	if err != nil {
		return err
	}
	numParamTypes, err := buf.getInt16()
	if err != nil {
		return err
	}

	inTypeHints := make([]oid.Oid, numParamTypes)
	for i := range inTypeHints {
		typ, err := buf.getInt32()
		if err != nil {
			return err
		}
		inTypeHints[i] = oid.Oid(typ)
	}
	args := make(parser.MapArgs)
	for i, t := range inTypeHints {
		if t == 0 {
			continue
		}
		v, ok := oidToDatum[t]
		if !ok {
			return c.sendError(fmt.Sprintf("unknown oid type: %v", t))
		}
		args[fmt.Sprint(i+1)] = v
	}
	cols, pErr := c.executor.Prepare(c.opts.user, query, c.session, args)
	if pErr != nil {
		return c.sendError(pErr.String())
	}
	pq := preparedStatement{
		query:       query,
		inTypes:     make([]oid.Oid, len(args)),
		portalNames: make(map[string]struct{}),
		columns:     cols,
	}
	copy(pq.inTypes, inTypeHints)
	for k, v := range args {
		i, err := strconv.Atoi(k)
		if err != nil {
			return c.sendError(fmt.Sprintf("non-integer parameter name: %s", k))
		}
		// ValArgs are 1-indexed, pq.inTypes are 0-indexed.
		i--
		if len(pq.inTypes) <= i {
			return c.sendError("internal error: leftover valargs")
		}
		// OID to Datum is not a 1-1 mapping (for example, int4 and int8 both map
		// to DummyInt), so we need to maintain the types sent by the client.
		if pq.inTypes[i] != 0 {
			continue
		}
		id, ok := datumToOid[reflect.TypeOf(v)]
		if !ok {
			return c.sendError(fmt.Sprintf("unknown datum type: %s", v.Type()))
		}
		pq.inTypes[i] = id
	}
	c.preparedStatements[name] = pq
	c.writeBuf.initMsg(serverMsgParseComplete)
	return c.writeBuf.finishMsg(c.wr)
}

func (c *v3Conn) handleDescribe(buf *readBuffer) error {
	typ, err := buf.getPrepareType()
	if err != nil {
		return c.sendError(err.Error())
	}
	name, err := buf.getString()
	if err != nil {
		return err
	}
	switch typ {
	case prepareStatement:
		stmt, ok := c.preparedStatements[name]
		if !ok {
			return c.sendError(fmt.Sprintf("unknown prepared statement %q", name))
		}
		c.writeBuf.initMsg(serverMsgParameterDescription)
		c.writeBuf.putInt16(int16(len(stmt.inTypes)))
		for _, t := range stmt.inTypes {
			c.writeBuf.putInt32(int32(t))
		}
		if err := c.writeBuf.finishMsg(c.wr); err != nil {
			return err
		}

		return c.sendRowDescription(stmt.columns, nil)
	case preparePortal:
		prtl, ok := c.preparedPortals[name]
		if !ok {
			return c.sendError(fmt.Sprintf("unknown portal %q", name))
		}
		stmt, ok := c.preparedStatements[prtl.stmtName]
		if !ok {
			return c.sendError(fmt.Sprintf("unknown prepared statement %q", name))
		}

		return c.sendRowDescription(stmt.columns, prtl.outFormats)
	default:
		return util.Errorf("unknown describe type: %s", typ)
	}
}

func (c *v3Conn) handleClose(buf *readBuffer) error {
	typ, err := buf.getPrepareType()
	if err != nil {
		return c.sendError(err.Error())
	}
	name, err := buf.getString()
	if err != nil {
		return err
	}
	switch typ {
	case prepareStatement:
		if stmt, ok := c.preparedStatements[name]; ok {
			for portalName := range stmt.portalNames {
				delete(c.preparedPortals, portalName)
			}
		}
		delete(c.preparedStatements, name)
	case preparePortal:
		if prtl, ok := c.preparedPortals[name]; ok {
			if stmt, ok := c.preparedStatements[prtl.stmtName]; ok {
				delete(stmt.portalNames, name)
			}
		}
		delete(c.preparedPortals, name)
	default:
		return util.Errorf("unknown close type: %s", typ)
	}
	return nil
}

func (c *v3Conn) handleBind(buf *readBuffer) error {
	portalName, err := buf.getString()
	if err != nil {
		return err
	}
	// The unnamed portal can be freely overwritten.
	if portalName != "" {
		if _, ok := c.preparedPortals[portalName]; ok {
			return c.sendError(fmt.Sprintf("portal %q already exists", portalName))
		}
	}
	statementName, err := buf.getString()
	if err != nil {
		return err
	}
	stmt, ok := c.preparedStatements[statementName]
	if !ok {
		return c.sendError(fmt.Sprintf("unknown prepared statement %q", statementName))
	}
	numParamFormatCodes, err := buf.getInt16()
	if err != nil {
		return err
	}
	numParams := len(stmt.inTypes)
	paramFormatCodes := make([]formatCode, numParams)
	for i := range paramFormatCodes[:numParamFormatCodes] {
		c, err := buf.getInt16()
		if err != nil {
			return err
		}
		paramFormatCodes[i] = formatCode(c)
	}
	if numParamFormatCodes == 1 {
		fmtCode := paramFormatCodes[0]

		for i := range paramFormatCodes {
			paramFormatCodes[i] = fmtCode
		}
	}
	numValues, err := buf.getInt16()
	if err != nil {
		return err
	}
	if int(numValues) != numParams {
		return c.sendError(fmt.Sprintf("expected %d parameters, got %d", numParams, numValues))
	}
	params := make([]parser.Datum, numParams)
	for i, t := range stmt.inTypes {
		plen, err := buf.getInt32()
		if err != nil {
			return err
		}
		if plen == -1 {
			// TODO(mjibson): a NULL parameter, figure out what this should do
			continue
		}
		b, err := buf.getBytes(int(plen))
		if err != nil {
			return err
		}
		d, err := decodeOidDatum(t, paramFormatCodes[i], b)
		if err != nil {
			return c.sendError(fmt.Sprintf("param $%d: %s", i+1, err))
		}
		params[i] = d
	}

	numColumnFormatCodes, err := buf.getInt16()
	if err != nil {
		return err
	}
	numColumns := len(stmt.columns)
	columnFormatCodes := make([]formatCode, numColumns)
	for i := range columnFormatCodes[:numColumnFormatCodes] {
		c, err := buf.getInt16()
		if err != nil {
			return err
		}
		columnFormatCodes[i] = formatCode(c)
	}
	if numColumnFormatCodes == 1 {
		fmtCode := columnFormatCodes[0]

		for i := range columnFormatCodes {
			columnFormatCodes[i] = formatCode(fmtCode)
		}
	}

	stmt.portalNames[portalName] = struct{}{}
	c.preparedPortals[portalName] = preparedPortal{
		stmt:       stmt,
		stmtName:   statementName,
		params:     params,
		outFormats: columnFormatCodes,
	}
	c.writeBuf.initMsg(serverMsgBindComplete)
	return c.writeBuf.finishMsg(c.wr)
}

func (c *v3Conn) handleExecute(buf *readBuffer) error {
	portalName, err := buf.getString()
	if err != nil {
		return err
	}
	portal, ok := c.preparedPortals[portalName]
	if !ok {
		return c.sendError(fmt.Sprintf("unknown portal %q", portalName))
	}
	limit, err := buf.getInt32()
	if err != nil {
		return err
	}

	return c.executeStatements(portal.stmt.query, portal.params, portal.outFormats, false, limit)
}

func (c *v3Conn) executeStatements(stmts string, params []parser.Datum, formatCodes []formatCode, sendDescription bool, limit int32) error {
	tracing.AnnotateTrace()

	c.session.Database = c.opts.database

	resp, _, err := c.executor.ExecuteStatements(c.opts.user, c.session, stmts, params)
	if err != nil {
		return c.sendError(err.Error())
	}

	c.session.Reset()
	c.session = resp.Session

	c.opts.database = c.session.Database
	tracing.AnnotateTrace()
	if resp.Empty {
		// Skip executor and just send EmptyQueryResponse.
		c.writeBuf.initMsg(serverMsgEmptyQuery)
		return c.writeBuf.finishMsg(c.wr)
	}
	return c.sendResponse(resp, formatCodes, sendDescription, limit)
}

func (c *v3Conn) sendCommandComplete(tag []byte) error {
	c.writeBuf.initMsg(serverMsgCommandComplete)
	c.writeBuf.Write(tag)
	c.writeBuf.WriteByte(0)
	return c.writeBuf.finishMsg(c.wr)
}

func (c *v3Conn) sendError(errToSend string) error {
	if c.doingExtendedQueryMessage {
		c.ignoreTillSync = true
	}

	c.writeBuf.initMsg(serverMsgErrorResponse)
	if err := c.writeBuf.WriteByte('S'); err != nil {
		return err
	}
	if err := c.writeBuf.writeString("ERROR"); err != nil {
		return err
	}
	if err := c.writeBuf.WriteByte('C'); err != nil {
		return err
	}
	// "XX000" is "internal error".
	// TODO(bdarnell): map our errors to appropriate postgres error
	// codes as defined in
	// http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
	if err := c.writeBuf.writeString("XX000"); err != nil {
		return err
	}
	if err := c.writeBuf.WriteByte('M'); err != nil {
		return err
	}
	if err := c.writeBuf.writeString(errToSend); err != nil {
		return err
	}
	if err := c.writeBuf.WriteByte(0); err != nil {
		return err
	}
	return c.writeBuf.finishMsg(c.wr)
}

func (c *v3Conn) sendResponse(resp sql.Response, formatCodes []formatCode, sendDescription bool, limit int32) error {
	if len(resp.Results) == 0 {
		return c.sendCommandComplete(nil)
	}
	for _, result := range resp.Results {
		if result.PErr != nil {
			if err := c.sendError(result.PErr.String()); err != nil {
				return err
			}
			break
		}
		if limit != 0 && len(result.Rows) > int(limit) {
			if err := c.sendError(fmt.Sprintf("execute row count limits not supported: %d of %d", limit, len(result.Rows))); err != nil {
				return err
			}
			break
		}

		if result.PGTag == "INSERT" {
			// From the postgres docs (49.5. Message Formats):
			// `INSERT oid rows`... oid is the object ID of the inserted row if
			//	rows is 1 and the target table has OIDs; otherwise oid is 0.
			result.PGTag = "INSERT 0"
		}
		tag := append(c.tagBuf[:0], result.PGTag...)

		switch result.Type {
		case parser.RowsAffected:
			// Send CommandComplete.
			tag = append(tag, ' ')
			tag = strconv.AppendInt(tag, int64(result.RowsAffected), 10)
			if err := c.sendCommandComplete(tag); err != nil {
				return err
			}

		case parser.Rows:
			if sendDescription {
				if err := c.sendRowDescription(result.Columns, formatCodes); err != nil {
					return err
				}
			}

			// Send DataRows.
			for _, row := range result.Rows {
				c.writeBuf.initMsg(serverMsgDataRow)
				c.writeBuf.putInt16(int16(len(row.Values)))
				for i, col := range row.Values {
					fmtCode := formatText
					if formatCodes != nil {
						fmtCode = formatCodes[i]
					}
					switch fmtCode {
					case formatText:
						if err := c.writeBuf.writeTextDatum(col); err != nil {
							return err
						}
					case formatBinary:
						if err := c.writeBuf.writeBinaryDatum(col); err != nil {
							return err
						}
					default:
						return util.Errorf("unsupported format code %s", fmtCode)
					}
				}
				if err := c.writeBuf.finishMsg(c.wr); err != nil {
					return err
				}
			}

			// Send CommandComplete.
			tag = append(tag, ' ')
			tag = appendUint(tag, uint(len(result.Rows)))
			if err := c.sendCommandComplete(tag); err != nil {
				return err
			}

		// Ack messages do not have a corresponding protobuf field, so handle those
		// with a default.
		// This also includes DDLs which want CommandComplete as well.
		default:
			if err := c.sendCommandComplete(tag); err != nil {
				return err
			}
		}
	}

	return nil
}

func (c *v3Conn) sendRowDescription(columns []sql.ResultColumn, formatCodes []formatCode) error {
	if len(columns) == 0 {
		c.writeBuf.initMsg(serverMsgNoData)
		return c.writeBuf.finishMsg(c.wr)
	}

	c.writeBuf.initMsg(serverMsgRowDescription)
	c.writeBuf.putInt16(int16(len(columns)))
	for i, column := range columns {
		if log.V(2) {
			log.Infof("pgwire writing column %s of type: %T", column.Name, column.Typ)
		}
		if err := c.writeBuf.writeString(column.Name); err != nil {
			return err
		}

		typ := typeForDatum(column.Typ)
		c.writeBuf.putInt32(0) // Table OID (optional).
		c.writeBuf.putInt16(0) // Column attribute ID (optional).
		c.writeBuf.putInt32(int32(typ.oid))
		c.writeBuf.putInt16(int16(typ.size))
		c.writeBuf.putInt32(0) // Type modifier (none of our supported types have modifiers).
		if formatCodes == nil {
			c.writeBuf.putInt16(int16(formatText))
		} else {
			c.writeBuf.putInt16(int16(formatCodes[i]))
		}
	}
	return c.writeBuf.finishMsg(c.wr)
}

func appendUint(in []byte, u uint) []byte {
	var buf []byte
	if cap(in)-len(in) >= 10 {
		buf = in[len(in) : len(in)+10]
	} else {
		buf = make([]byte, 10)
	}
	i := len(buf)

	for u >= 10 {
		i--
		q := u / 10
		buf[i] = byte(u - q*10 + '0')
		u = q
	}
	// u < 10
	i--
	buf[i] = byte(u + '0')

	return append(in, buf[i:]...)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dylan.taxtimewithfriends.addDriver">

    <EditText
        android:id="@+id/driverName"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="NAME"
        android:inputType="textPersonName"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <Button
        android:id="@+id/cameraButton"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginTop="114dp"
        android:background="@android:drawable/ic_menu_camera"
        android:backgroundTint="@android:color/background_dark"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/submitButton"
        android:layout_width="350dp"
        android:layout_height="60dp"
        android:layout_marginBottom="16dp"
        android:background="@android:drawable/btn_default"
        android:backgroundTint="@android:color/holo_green_light"
        android:elevation="0dp"
        android:onClick="mainMenuActivity"
        android:text="submit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>