text:
<!doctype html>

  <title>Aaqib Saeed</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="preload" as="image" href="assets/misc/overview_sg.gif">
  <link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet' type='text/css'>
  <meta name="theme-color" content="#1a4067" />

  <meta property="og:title" content="Aaqib Saeed" />
  <meta property="og:type" content="article" />
  <meta property="og:description" content="Machine Learning Researcher" />
  <meta property="og:image" content="" />
  <meta property="og:url" content="https://aqibsaeed.github.io/" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="Aaqib Saeed" />
  <meta name="twitter:description" content="" />
  <meta property="og:site_name" content="" />
  <meta name="twitter:image" content="" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css">
  <link rel="stylesheet" href="/style.css">

Aaqib Saeed

Research Scientist @ Philips Research

  Self-Supervised Learning, Human-Centric AI, Sensing, Audio, & On-device ML

I'm a Research Scientist in AI at Philips Research (Healthcare), the Netherlands. My research interests span Machine Learning, Self-Supervision, Federated Learning, Audio, On-device ML, and applications to understand and improve Personal Health.

I received my Ph.D. cum laude from Eindhoven University of Technology in the Interconnected Resource-aware Intelligent Systems (IRIS) group, where I worked with Johan Lukkien and Tanir Ozcelebi. I have also collaborated with researchers while working at Google Brain and the University of Cambridge. Prior to this, I completed MSc. cum laude in Computer Science (specializing in Data Science and Smart Services) at the University of Twente.

        Twitter

        Scholar

        GitHub

        LinkedIn

	Email:qrmenso@tcaiopamlbedia.o unscramble

Active Learning of Non-semantic Speech Tasks with Pretrained Models

	  PDF
	  Code
	  BibTex

Harlin Lee, Aaqib Saeed, Andrea L. Bertozzi

      Pretraining neural networks with massive unlabeled datasets has become popular as it equips the deep models with a better prior to solve downstream tasks. However, this approach generally assumes that for downstream tasks, we have access to annotated data of sufficient size.
      In this work, we propose ALOE, a novel system for improving the data- and label-efficiency of non-semantic speech tasks with active learning. ALOE uses pre-trained models in conjunction with active learning to label data incrementally and learns classifiers for downstream tasks, thereby mitigating the need to acquire labeled data beforehand.

On Out-of-Distribution Detection for Audio with Deep Nearest Neighbors

	  Project Page
	  PDF
	  BibTex

Zaharah Bukhsh, Aaqib Saeed

      Out-of-distribution (OOD) detection is concerned with identifying data points that do not belong to the same distribution as the model's training data. For the safe deployment of predictive models in a real-world environment, it is critical to avoid making confident predictions on OOD inputs as it can lead to potentially dangerous consequences.

      However, OOD detection remains largely an under-explored area in the audio (and speech) domain. This is despite the fact that audio is a central modality for many tasks, such as speaker diarization, spoken language identification, and sound event detection. To address this, we propose to leverage feature-space of the model with deep k-nearest neighbors to detect OOD samples.

Automatic Sleep Scoring from Large-scale Multi-channel Pediatric EEG

	  Project Page
	  PDF
	  Code
	  BibTex

Harlin Lee, Aaqib Saeed @ Learning from Time Series for Health - Workshop at NeurIPS 2022

      Sleep is essential to the health of infants, children, and adolescents, and sleep scoring is the initiative to accurately diagnose and treat potentially life-threatening conditions. Here, we present the first automated sleep scoring results on a recent large-scale pediatric sleep study dataset collected during standard clinical care.

      We develop a transformer-based model that learns to classify five sleep stages from millions of multi-channel electroencephalogram (EEG) sleep epochs. Further, we conduct an in-depth analysis of the model performance based on patient demographics and EEG channels.

      Data illustrations by Storyset

Federated Learning with Noisy Labels

	  Project Page
	  PDF
	  BibTex

Vasileios Tsouvalas, Aaqib Saeed, Tanir Ozcelebi, Nirvana Meratnia

	Short Paper @ Interpolation and Beyond - Workshop at NeurIPS 2022

      Federated learning (FL) approaches assume high-quality labels are readily available on users' devices; in reality, label noise can naturally occur in the FL setting and follows a non-i.i.d. distribution among clients. Here, we propose FedLN, a framework to deal with label noise across different FL training stages: FL initialization, on-device model training, and server-side model aggregation.

      Extensive experiments on various publicly available vision and audio datasets demonstrate a 24% improvement on average compared to other existing methods for a label noise level of 70%. We further validate the efficiency of FedLN in human-annotated real-world noisy datasets and report a 9% increase on average in models' recognition performance.

Distilled Non-Semantic Speech Embeddings with Binary Neural Networks

	  PDF
	  BibTex

Harlin Lee, Aaqib Saeed

      We introduce BRILLsson, an approach for learning representations with binary neural networks for a broad range of non-semantic speech tasks. We leverage knowledge distillation for training binary models using a large and real-valued TRILLsson model with only a fraction of the dataset used to train the teacher model.

      Our models are only 2MB in size with a latency less than 8ms, making them suitable for deployment in low-resource devices, such as wearables. We evaluate BRILLsson models on eight benchmark tasks (including but not limited to spoken language identification, emotion recognition, health condition diagnosis, and keyword spotting), and demonstrate that our proposed approach results in ultra-light and low-latency models that perform as well as large-scale models.

Binary Early-Exit Network for Adaptive Inference on Low-Resource Devices

	  PDF
	  Link (Official)
	  Code
          BibTex

Aaqib Saeed @ Interspeech 2022

	Deep neural networks have become larger over the years with the increasing demand for computational resources for inference. Binary neural networks (BNNs) tackle the issue to an extent with extreme compression and speed-up gains compared to real-valued
	models. We propose a simple but effective method to accelerate inference through unifying BNNs with an early-exiting strategy.

	Our approach allows simple instances to exit early based on a decision threshold and utilizes output layers added to different intermediate layers to avoid executing the entire binary neural model. We extensively evaluate our method on three audio classification tasks and across four BNNs architectures to demonstrate favorable quality-efficiency trade-offs
	while being controllable with an entropy-based threshold specified by the system user.

COCOA: Cross Modality Contrastive Learning for Sensor Data

	  PDF
	  Link (Official)
	  BibTex

Shohreh Deldari, Hao Xue, Aaqib Saeed, Daniel V. Smith, Flora D. Salim @ ACM IMWUT 2022 - Ubicomp 2022

	We propose COCOA (Cross mOdality COntrastive leArning), a self-supervised model that employs a novel objective function to learn high-quality representations from multisensor data by computing the cross-correlation between different data modalities and minimizing the similarity between irrelevant instances.

	We evaluate the effectiveness of COCOA across a range of datasets and against several self-supervised methods. COCOA is highly label-efficient than the other baselines including the fully supervised model while using only one-tenth of available labeled data.

Beyond Just Vision: A Review on Self-Supervised Representation Learning on
Multimodal and Temporal Data

	  PDF
	  BibTex

Shohreh Deldari, Hao Xue, Aaqib Saeed, Jiayuan He, Daniel V. Smith, Flora D. Salim

	Self-supervised methods aim to improve data efficiency of deep neural networks through discriminative pre-training of models using supervisory signals that can be obtained from the raw data itself without any human intervention.

	We provide a comprehensive review of multimodal self-supervised learning methods for temporal data. To this end, we 1) provide a comprehensive categorization of existing SSRL methods, 2) introduce a generic pipeline by defining the key components of a SSRL framework, 3) compare existing models in terms of their objective function, network architecture and potential applications, and 4) review existing multimodal techniques in each category and various modalities, while also highlighting weaknesses and future opportunities.
	We believe our work develops a perspective on the requirements of SSRL in domains that utilize multimodal and/or temporal data.

Federated Self-Training for Semi-Supervised Audio Recognition

	  PDF
	  Link (Official)
	  Code
          BibTex

Vasileios Tsouvalas, Aaqib Saeed, Tanir Ozcelebi @ ACM TECS 2022

	Short Paper@  IEEE ICASSP 2022

	Federated Learning is a distributed machine learning paradigm dealing with decentralized and personal datasets. Since data reside on devices like smartphones and virtual assistants, labeling is entrusted to clients or labels are extracted in an automated way for learning models. However, in the case of audio data, acquiring semantic annotations can be prohibitively expensive and time-consuming. As a result, an abundance of audio samples remains unlabeled and unexploited. We propose FedSTAR, a semi-supervised learning approach for audio recognition. FedSTAR leverages unlabeled data via self-training to improve the generalization of audio models.

	We show that with as little as 3% labeled data available, FedSTAR on average can improve the recognition rate by 13.28% compared to the fully supervised federated model. We further demonstrate that self-supervised pre-trained models can accelerate the training of on-device models, significantly improving convergence within fewer training rounds.

Extrapolating from a Single Image to a Thousand Classes using Distillation

	  Project Page
	  PDF
	  Code
	  BibTex

Yuki M. Asano*, Aaqib Saeed*

      We developed a framework for training neural networks from scratch using a single image by means of knowledge distillation from a supervised pretrained teacher.

      We demonstrate that it is possible to extrapolate to semantic classes such as those of ImageNet using single datum as models' inputs. We leverage knowledge distillation for this and achieve performances of 74% on CIFAR-100, 66% on ImageNet,
      75.2% on UCF-101, 51% on Kinetics-400 and by extending this method to audio, 84% on SpeechCommands.

Recognizing Head Gestures and Facial Expressions with Earbuds

	  PDF
	  Link (Official)
          BibTex

Shkurta Gashi, Aaqib Saeed, Alessandra Vicini, Elena Di Lascio, Silvia Santini @ ACM ICMI 2021

	Head gestures and facial expressions -- like, e.g., nodding or smiling -- are important indicators of the quality of human interactions in physical meetings as well as in a computer-mediated environment. The automated systems able to recognize such behavioral cues can support and improve human interactions.

        In this work, we consider inertial signals collected from unobtrusive, ear-mounted devices to recognize gestures and facial expressions typically performed during social interactions -- head shaking, nodding, smiling, talking, and yawning. We propose a hierarchical classification approach with transfer learning to improve the generalization and data efficiency of the predictive model using raw IMU data.

LumNet: Learning to Estimate Vertical Visual Field Luminance for Adaptive Lighting Control

	  PDF
          BibTex

        Prince Songwa, Aaqib Saeed, Sachin Bhardwaj, Thijs Kruisselbrink, Tanir Ozcelebi @ ACM IMWUT 2021 - Ubicomp 2021

	We propose a novel approach to estimate desktop luminance using deep learning for adaptive lighting control. Our proposed LumNet model learns visual representations from ceiling-based images,
	which are collected in indoor spaces within the physical vicinity of the user to predict average desktop luminance as experienced in a real-life setting.

	We also present a self-supervised contrastive method for pre-training LumNet with unlabeled data and we demonstrate that the learned features are transferable onto a small labeled dataset which minimizes the requirement of costly data annotations.

Learning Sensory Representations with Minimal Supervision (PhD Thesis)

	  PDF
          BibTex

        Aaqib Saeed - PhD Thesis (2021) - Eindoven University of Technology

	We develop novel techniques that lie on the intersection of deep learning, ambient sensing, and ubiquitous computing to address issues pertaining to learning from unlabeled sensory data and making models robust to various input artifacts. The research focuses on representation learning with deep neural networks to realize the vision of self-learning for embedded intelligence in everyday devices, such as smartphones, wearables, earables, and more.

Our proposed methods are primarily based on the theme of self-supervised learning to extract generic representations from multi-modal sensory inputs, such as electroencephalogram, audio, accelerometer, and more. Our work enables deep neural networks to learn broadly useful representations that perform well on a spectrum of downstream tasks, are robust to noise and other artifacts, and generalize when transferred to other domains.

Contrastive Learning of General-Purpose Audio Representations

	  PDF
	  Code
          BibTex
	  Poster
	  Link (Official)

      Aaqib Saeed, David Grangier, Neil Zeghidour @ IEEE ICASSP 2021

      We introduce COLA, a self-supervised pre-training approach for learning a general-purpose representation of audio. We build on top of recent advances in contrastive learning for computer vision and reinforcement learning
      to design a lightweight, easy-to-implement self-supervised model of audio.

      We pre-train embeddings on the large-scale Audioset database and transfer these representations to 9 diverse classification tasks, including speech, music, animal sounds, and acoustic scenes.
      We show that despite its simplicity, our method significantly outperforms previous self-supervised systems.

Learning from Heterogeneous EEG Signals with Differentiable Channel Reordering

	  Project Page
	  PDF
     	  BibTex
	  Poster
	  Link (Official)

      Aaqib Saeed, David Grangier, Olivier Pietquin, Neil Zeghidour @ IEEE ICASSP 2021

	We propose CHARM, a method for training a single neural network across inconsistent input channels.
	Our work is motivated by Electroencephalography (EEG), where data collection protocols from different headsets result in varying channel ordering and number,
	which limits the feasibility of transferring trained systems across datasets.

	CHARM is differentiable and compatible with architectures (e.g. CNNs) that expect consistent channels. Across different input noising conditions we show its robustness.
        We also successfully perform transfer learning between datasets collected with different EEG headsets.

Sense and Learn: Self-Supervision for Omnipresent Sensors

	  Project Page
	  PDF
	  Link (Official)
      	  BibTex

	      Aaqib Saeed, Victor Ungureanu, Beat Gfeller @ Machine Learning with Applications

Looking for a way to utilize large-scale unlabeled sensory (time-series) data to improve generalization on downstream task with few-labeled datapoints? Try: Sense and Learn, a self-supervised learning framework.

We propose a suite of self-supervised pretext tasks for pre-training deep neural networks without semantic labels. We evaluate the quality of learned embedding with our framework on a wide variety of end-tasks with a linear classifier on top of a fixed encoder, effectiveness in the low-data regime, and transfer learning. Our approach opens up exciting possibilities for on-device continual learning without requiring supervision.

Federated Self-Supervised Learning of Multi-Sensor Representations for Embedded Intelligence

	      PDF
      Link (Official)
      BibTex

      Aaqib Saeed, Flora D. Salim, Tanir Ozcelebi, Johan Lukkien @ IEEE Internet of Things Journal 2020

We present a self-supervised method for learning multi-sensor representations in a federated learning setting from unlabeled and decentralized data. Our scalogram-signal correspondence learning (SSCL) technique utilize wavelet transform and a contrastive objective for training the deep network to determine if a given pair of a signal and its complementary view (i.e., a scalogram generated with wavelet transform) align with each other or not.

We extensively assess the quality of learned features with SSCL on diverse public datasets, which comprise signals like electroencephalography, blood volume pulse, accelerometer, and Wi-Fi channel state information. We conduct experiments to demonstrate our approach's effectiveness in both centralized and federated settings through linear classification. Mainly, SSCL significantly improves generalization in the low-data regime by reducing the volume of labeled data required through leveraging self-supervised learning.

On-device Learning of Activity Recognition Model (Blogpost)

      Project Page
      Code (Github)
      BibTex

      Leverage transfer learning for efficiently training activity sensing models directly on the Android device without the need for sending data to the server.

 Enabling next-generation privacy-preserving personal informatics apps!

Multi-Task Self-Supervised Learning for Human Activity Detection

      Project Page
      PDF
      Link (Official)
      BibTex

      Aaqib Saeed, Tanir Ozcelebi, Johan Lukkien @ IMWUT June 2019- Ubicomp 2019

      Workshop Paper@ Self-supervised Learning Workshop ICML 2019

      We've created a Transformation Prediction Network, a self-supervised neural network for representation learning from sensory data that does not require access to any form of semantic labels, e.g., activity classes in human context detection. We demonstrate that simple auxiliary tasks of recognizing signal transformations result in strong supervision for extracting high-level features that generalize well on the down-stream task; substantially improving performance under semi-supervised and transfer learning settings in the low-data regime.

End-to-End Multi-Modal Behavioral Context Recognition in a Real-Life Setting

      Paper
      BibTex

      Aaqib Saeed, Stojan Trajanovski, Tanir Ozcelebi, Johan Lukkien @ Fusion 2019

      The automatic and unobtrusive sensing of human context can help develop solutions for assisted living, fitness tracking, sleep monitoring, and several other fields. Towards addressing this issue, we develop a multi-modal neural network capable of multi-label behavioral context recognition. Our empirical evaluation suggests that a deep convolutional network trained end-to-end achieves comparable performance to manual feature engineering with minimal effort.

Synthesizing and Reconstructing Missing Sensory Modalities in Behavioral Context Recognition

      Project Page
      Paper
      BibTex

      Aaqib Saeed, Tanir Ozcelebi, Johan Lukkien @ MDPI Sensors 2018

      We propose a method based on an adversarial autoencoder for handling missing sensory features and synthesizing realistic samples. We empirically demonstrate the capability of our approach in comparison with classical techniques for filling-in missing values on a large-scale activity recognition dataset collected in-the-wild.

Model Adaptation and Personalization for Physiological Stress Detection

      Project Page
      Paper
      BibTex

      Aaqib Saeed, Tanir Ozcelebi, Johan Lukkien, Jan van Erp and Stojan Trajanovski @ IEEE DSAA 2018

      Long-Term exposure to stressful situations can have negative health consequences, such as the increased risk of cardiovascular diseases and immune system disorder. We utilize a deep reconstruction classification network and multitask learning for domain adaption and personalization of stress recognition models. The proposed methods performed significantly better than baselines on multimodal physiological (time-series) data collected during driving tasks, in both real-world and driving simulator.

Personalized Driver Stress Detection with Multi-Task Neural Networks using Physiological Signals

      Paper
      BibTex

      Aaqib Saeed and Stojan Trajanovski @ ML4H Workshop NeurIPS 2017

      Stress can be seen as a physiological response to everyday emotional, mental, and physical challenges. We suggest a subjects-as-tasks approach for multi-task learning based neural network (with hard parameter sharing of mutual representation and task-specific layers) for personalized stress detection using skin conductance and heart rate from wearable devices.

Deep Physiological Arousal Detection in a Driving Simulator using Wearable Sensors

      Paper
      BibTex

      Aaqib Saeed, Stojan Trajanovski, Maurice van Keulen and Jan van Erp @ DMBIH Workshop IEEE ICDM 2017

      Driving is an activity that requires considerable alertness. Insufficient attention, imperfect perception, inadequate information processing, and sub-optimal arousal are possible causes of poor human performance. Understanding of these causes and the implementation of effective remedies is of crucial importance to increase traffic safety and improve driver's well-being. For this purpose, we develop an arousal detection algorithm using a temporal convolutional neural network. The model is trained on raw physiological signals, i.e., heart rate, skin conductance, and skin temperature.

#WhoAmI in 160 Characters? Classifying Social Identities Based on Twitter

      Paper
      Code
      BibTex

      Anna Priante, Djoerd Hiemstra, Tijs van den Broek, Aaqib Saeed, Michel Ehrenhard and Ariana Need @ NLP and CSS Workshop EMNLP 2016

      We combine social theory and NLP methods to classify English-speaking Twitter users' online social identity in profile descriptions. Our study shows how social theory can be used to guide NLP methods, and how such methods provide input to revisit traditional social theory that is strongly consolidated in offline settings.

Acknowledgments

This site was prepared using the Distill template which is adapted and kindly open-sourced by Pierre Sermanet.


text:
require 'spec_helper'

describe('tomcat::service', :type => :define) do
  let(:title) { 'myapp:myService' }
  let(:facts) { {:osfamily => 'RedHat', :concat_basedir => '/tmp'} }
  let(:pre_condition) { [
    "class { 'tomcat': }"
  ] }

  context 'with server => myapp, service => myService' do
    let(:params) { {:connectors => {}, :engine => {}} }
    it do
      should contain_concat__fragment('server.xml-myapp:myService-header') \
        .with({ 'order' => '50_myService_00' }) \
        .with_content(/^\s*<Service name='myService'>/)
      should contain_concat__fragment('server.xml-myapp:myService-footer') \
        .with({ 'order' => '50_myService_99' }) \
        .with_content(/^\s*<\/Service>/)
    end
  end

  context 'with engine => foo (non valid value)' do
    let(:params) { {:connectors => {}, :engine => 'foo'} }
    it do
      expect {
        should contain_concat__fragment('server.xml-myapp:myService-header')
      }.to raise_error(Puppet::Error, /is not a Hash/)
    end
  end

  context 'with connectors => foo (non valid value)' do
    let(:params) { {:connectors => 'foo', :engine => {}} }
    it do
      expect {
        should contain_concat__fragment('server.xml-myapp:myService-header')
      }.to raise_error(Puppet::Error, /is not a Hash/)
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xmlns="http://maven.apache.org/POM/4.0.0"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-contract-parent</artifactId>
		<version>4.0.0-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>
	<artifactId>spring-cloud-contract-wiremock</artifactId>
	<packaging>jar</packaging>
	<name>spring-cloud-contract-wiremock</name>
	<description>Spring Cloud Contract Wiremock</description>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webflux</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>jakarta.servlet</groupId>
			<artifactId>jakarta.servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-mockmvc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-webtestclient</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-restassured</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<optional>true</optional>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.github.tomakehurst</groupId>
			<artifactId>wiremock-jre8-standalone</artifactId>
		</dependency>
		<dependency>
			<groupId>io.rest-assured</groupId>
			<artifactId>rest-assured</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents.client5</groupId>
			<artifactId>httpclient5</artifactId>
		</dependency>
		<dependency>
			<groupId>org.assertj</groupId>
			<artifactId>assertj-core</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-test-support</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-contract-verifier</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.example.github</groupId>
			<artifactId>github-webhook</artifactId>
			<classifier>stubs</classifier>
			<version>1.0.0.M1-190120_193303-VERSION</version><!-- @releaser:version-check-off -->
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>*</groupId>
					<artifactId>*</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.example.github</groupId>
			<artifactId>github-analytics</artifactId>
			<classifier>stubs</classifier>
			<version>1.0.0.M1-190120_105104-VERSION</version><!-- @releaser:version-check-off -->
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>*</groupId>
					<artifactId>*</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.junit.vintage</groupId>
			<artifactId>junit-vintage-engine</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
C turing machine simulator
--------------------------

A tiny turing machine simulator, written in C

Turing machine syntax
---------------------

Look for examples in the `./examples` directory.
The syntax is as follows:

	# the file
	# can start with
	# some comment lines
	# as long as they start with a # character
	#
	# note: this is the most bogus turing machine ever. No idea what it does. Don't try at home!
	#
	4							<- number of states
	q1							<- state names (parser expects 4); first one is start state
	q2
	q_accept A					<- states can get the A or R attribute
	q_reject R					<- denoting 'accept' or 'reject' state respectively
	q1 x -> q2 \ R				<- transitions:
	q2 _ -> q3 . R				<-	(from state) (on input) -> (to state) (write) (move)
	q3 . -> q_accept \ L		<-	where the (write) character \ is reserved for 'write nothing'
	q3 _ -> q_reject \ L		<- 	and (move) can be either 'R' or 'L'
	q4 x -> q1 \ R				<- 	(yes. it stands for 'right' and 'left' respectively. Good guess)


text:
/**
 * Mocha + Istanbul Test Suite Integration
 */
module.exports = function(grunt) {

  grunt.config.set('mocha_istanbul', {
      coverage: {
        src: 'api/test',
        options: {
          scriptPath: require.resolve('istanbul/lib/cli'),
          coverageFolder: 'bin/sails-coverage',
          mask: '**/*.test.js',
          root: 'api/',
          excludes: ['responses/**/*.js'],
          mochaOptions: ['--reporter', 'dot'],
          istanbulOptions: ['--print', 'none']
          // Once we catch up on the tests uncomment
          // check: {
          //   lines: 75,
          //   statements: 75,
          //   branches: 75,
          //   functions: 90
          // }
        }
      }
    });

    // Register tasks.
    grunt.loadNpmTasks('grunt-mocha-istanbul');
};


text:
import { reject } from "../index";
export = reject;


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Umbraco.Cms.Infrastructure.Serialization;

public class ForceInt32Converter : JsonConverter
{
    public override bool CanConvert(Type objectType) => objectType == typeof(object) || objectType == typeof(int);

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        JValue? jsonValue = serializer.Deserialize<JValue>(reader);

        return jsonValue?.Type == JTokenType.Integer
            ? jsonValue.Value<int>()
            : serializer.Deserialize(reader);
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) =>
        throw new NotImplementedException();
}


text: I am the trait defining how to manipulate entities of an Orion model.


text: <button type="button" class="end-document-selection-button btn button-primary"><%- i18n['search.documentSelection.end'] %></button>


text: dbutil is a library that contains a collection of auxiliary functions related to MySQL and TiDB.


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace FlickrNet.Exceptions
{
    /// <summary>
    /// No photo with the photo ID supplied to the method could be found.
    /// </summary>
    /// <remarks>
    /// This could mean the photo does not exist, or that you do not have permission to view the photo.
    /// </remarks>
    public class PhotoNotFoundException : FlickrApiException
    {
        internal PhotoNotFoundException(int code, string message)
            : base(code, message)
        {
        }
    }
}


text:
package v1

import (
	"context"

	"knative.dev/eventing/pkg/apis/config"
	"knative.dev/eventing/pkg/apis/eventing"
	"knative.dev/pkg/apis"
)

func (b *Broker) SetDefaults(ctx context.Context) {
	// Default Spec fields.
	withNS := apis.WithinParent(ctx, b.ObjectMeta)
	b.Spec.SetDefaults(withNS)
	eventing.DefaultBrokerClassIfUnset(withNS, &b.ObjectMeta)
}

func (bs *BrokerSpec) SetDefaults(ctx context.Context) {
	if bs.Config != nil {
		// Default the namespace if not given
		bs.Config.SetDefaults(ctx)
		return
	}

	cfg := config.FromContextOrDefaults(ctx)
	c, err := cfg.Defaults.GetBrokerConfig(apis.ParentMeta(ctx).Namespace)
	if err == nil {
		c.SetDefaults(ctx)
		bs.Config = c
	}
}


text:
		<title>SpaceShapeShifter</title>
		<meta name="description" content="About SpaceShapeShifter - small online shoot-em-up game.">
		<meta name="keywords" content="games, shootemup, online, fun, entertainment">
		<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
		<link rel="stylesheet" href="style.css?v=1.0">

		SpaceShapeShifter

Home

Play!

About

About

				Original author: Liviu Cristian Mirea-Ghiban - liviucmg.com

Credits

				LostGarden.com - Tyrian sprites

				Webtreats - Tilable space backgrounds

				Eric Skiff - Background music

				BXFR.net - Sound effect generator


text:
const aggregate = {
  requestSagaTest: (_, { payload }) => ({
    type: 'SagaTestRequested',
    payload,
  }),
  succeedSagaTest: (_, { payload }) => ({
    type: 'SagaTestSucceeded',
    payload,
  }),
}

export default aggregate


text:
using System;

/// <summary>
/// System.Convert.ToDecimal(Decimal)
/// </summary>
public class ConvertToDecimal9
{
    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;
        retVal = PosTest4() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Construct a random decimal");

        int low = TestLibrary.Generator.GetInt32(-55);
        int mid = TestLibrary.Generator.GetInt32(-55);
        int hi = TestLibrary.Generator.GetInt32(-55);
        int flags = 0x1C0000;
        int[] arrInt ={ low, mid, hi, flags };

        try
        {
            decimal decimalSource = new decimal(arrInt);
            decimal decimalValue = Convert.ToDecimal(decimalSource);
            if (decimalValue != decimalSource)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The decimal is zero");

        try
        {
            decimal decimalSource = new decimal(0);
            decimal decimalValue = Convert.ToDecimal(decimalSource);
            if (decimalValue != decimalSource)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Convert decimalMaxValue to decimal");

        try
        {
            decimal decimalSource = Decimal.MaxValue;
            decimal decimalValue = Convert.ToDecimal(decimalSource);
            if (decimalValue != decimalSource)
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4: Convert decimalMinValue to decimal");

        try
        {
            decimal decimalSource = Decimal.MinValue;
            decimal decimalValue = Convert.ToDecimal(decimalSource);
            if (decimalValue != decimalSource)
            {
                TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    #endregion

    #region Nagetive Test Cases
    #endregion
    #endregion

    public static int Main()
    {
        ConvertToDecimal9 test = new ConvertToDecimal9();

        TestLibrary.TestFramework.BeginTestCase("ConvertToDecimal9");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
'use strict';

angular.module('mean.mean-subscribe')
    .run(function ($rootScope, $state, Global, $location) {
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toState.sendMail === true && !Global.isAdmin) {
                $location.path('/meanSubscribe');
                event.preventDefault();
            }
        });
    })
    .controller('MeanSubscribeController', ['$scope', '$rootScope', '$http', '$location', 'Global', 'MeanSubscribe',
        function ($scope, $rootScope, $http, $location, Global, MeanSubscribe) {
            $scope.subSuccess = false;
            $scope.subError = false;
            $scope.global = Global;
            $scope.package = {
                name: 'mean-subscribe'
            };

            $scope.sendEmail = function () {

                if ($scope.htmlContent && $scope.subject && $scope.senderPasswd) {
                    $scope.loading = true;
                    $http({
                        url: '/MeanSubscribe/sendEmail',
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        data: {
                            content: $scope.htmlContent,
                            subject: $scope.subject,
                            senderPasswd: $scope.senderPasswd
                        }
                    }).success(function (data) {
                        $location.path('/MeanSubscribe/mailsend');
                        $rootScope.mailStatus = true;
                    }).error(function (data) {
                        $scope.loading = false;
                        $rootScope.mailStatus = false;
                        $rootScope.errorMessage = data.err;

                    });
                } else {
                    $rootScope.mailStatus = false;
                    $rootScope.errorMessage = 'You must enter the required fields';
                }
            };

            $scope.subscribeMail = function () {

                if ($scope.mailAddr) {
                    $http({
                        url: '/MeanSubscribe/saveEmailAddr',
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        data: {userEmailAddr: $scope.mailAddr}
                    }).success(function (data) {
                        $scope.mailAddr = '';
                        $scope.subSuccess = true;
                        $scope.subError = false;
                    }).error(function (data) {
                        $scope.mailAddr = '';
                        $scope.subSuccess = false;
                        $scope.subError = true;
                        $scope.errorMessage = data.err;
                    });
                }
            };

            $scope.unSubscribe = function () {
                console.log('Mail address is :' + $scope.mailAddr);
                if ($scope.mailAddr) {
                    $http({
                        url: '/MeanSubscribe/unsubscribe',
                        method: 'delete',
                        headers: { 'Content-Type': 'application/json' },
                        data: {userEmailAddr: $scope.mailAddr}
                    }).success(function (data) {
                        $scope.mailAddr = '';
                        $scope.subSuccess = true;
                        $scope.subError = false;
                    }).error(function (data) {
                        $scope.mailAddr = '';
                        $scope.subSuccess = false;
                        $scope.subError = true;
                        $scope.errorMessage = data.err;
                    });
                }
            };
        }
    ]);


text:
import * as React from "react";

import { computed } from "mobx";
import { observer } from "mobx-react";

import { rule, rules, TextInput, RuleBullets, field,
    numberAsString, numberLimits } from "../../index";

@observer
export default class Multiplier extends React.Component<{}, {}> {

    private static factor = field(numberLimits(1, 10)).also(numberAsString(2));

    private a = Multiplier.factor.create(1, "A");
    private b = Multiplier.factor.create(12, "B");

    private limit = rule(() =>
        (this.a.model + this.b.model > 10) ?
            `Total ${this.a.model} + ${this.b.model} is too big` : []);

    private validation = rules([this.a, this.b, this.limit]);

    @computed
    get product() { return this.a.model * this.b.model; }

    render() {
        const { a, b, product, validation } = this;

        return (

A = <TextInput value={a}/>

B = <TextInput value={b}/>

Product ({a.model} * {b.model}) = { product }

                <RuleBullets rule={validation} />

        );
    }
}


text:
package veneur

import (
	"fmt"
	"sort"
	"testing"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/segmentio/fasthash/fnv1a"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stripe/veneur/v14/protocol"
	"github.com/stripe/veneur/v14/protocol/dogstatsd"
	"github.com/stripe/veneur/v14/samplers"
	"github.com/stripe/veneur/v14/ssf"
)

func freshSSFMetric() *ssf.SSFSample {
	return &ssf.SSFSample{
		Metric:     0,
		Name:       "test.ssf_metric",
		Value:      5,
		Message:    "test_msg",
		Status:     0,
		SampleRate: 1,
		Tags: map[string]string{
			"tag1": "value1",
			"tag2": "value2",
		},
	}
}

func TestValidMetric(t *testing.T) {
	metric := freshSSFMetric()

	parser := samplers.Parser{}

	m, _ := parser.ParseMetricSSF(metric)
	assert.True(t, samplers.ValidMetric(m))

	metric.Name = ""
	m, _ = parser.ParseMetricSSF(metric)
	assert.False(t, samplers.ValidMetric(m))

	metric.SampleRate = 0
	m, _ = parser.ParseMetricSSF(metric)
	assert.False(t, samplers.ValidMetric(m))
}

func TestValidTrace(t *testing.T) {
	trace := &ssf.SSFSpan{}
	assert.False(t, protocol.ValidTrace(trace))

	trace.Id = 1
	trace.TraceId = 1
	trace.Name = "foo"
	trace.StartTimestamp = 1
	trace.EndTimestamp = 5
	assert.True(t, protocol.ValidTrace(trace))
}

func TestParseSSFUnmarshal(t *testing.T) {
	test := []byte{'0'}
	sample, err := protocol.ParseSSF(test)

	assert.Nil(t, sample)
	assert.NotNil(t, err)
	assert.Error(t, err)
}

func TestParseSSFEmpty(t *testing.T) {
	trace := &ssf.SSFSpan{}

	buff, err := proto.Marshal(trace)
	assert.Nil(t, err)

	_, err = protocol.ParseSSF(buff)
	assert.NoError(t, err)
}

func TestParseSSFValidTraceInvalidMetric(t *testing.T) {
	trace := &ssf.SSFSpan{}
	trace.Id = 1
	trace.TraceId = 1
	trace.Name = "foo"
	trace.StartTimestamp = 1
	trace.EndTimestamp = 5

	buff, err := proto.Marshal(trace)
	assert.Nil(t, err)

	span, err := protocol.ParseSSF(buff)
	assert.Nil(t, err)
	if assert.NotNil(t, span) {
		assert.NoError(t, protocol.ValidateTrace(span))
		assert.NotNil(t, span)
		assert.NotNil(t, span.Tags)

		metrics, err := (&samplers.Parser{}).ConvertMetrics(span)
		assert.NoError(t, err)
		assert.Empty(t, metrics)
	}
}

func TestParseSSFInvalidTraceValidMetric(t *testing.T) {
	metric := freshSSFMetric()

	trace := &ssf.SSFSpan{}
	trace.Tags = map[string]string{
		"foo": "bar",
	}
	trace.Metrics = make([]*ssf.SSFSample, 0)
	trace.Metrics = append(trace.Metrics, metric)

	buff, err := proto.Marshal(trace)
	assert.Nil(t, err)

	span, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	if assert.NotNil(t, span) {
		metrics, err := (&samplers.Parser{}).ConvertMetrics(span)
		assert.NoError(t, err)
		if assert.Equal(t, 1, len(metrics)) {
			m := metrics[0]
			assert.Equal(t, metric.Name, m.Name, "Name")
			assert.Equal(t, float64(metric.Value), m.Value, "Value")
			assert.Equal(t, "counter", m.Type, "Type")
			assert.NotContains(t, "foo:bar", m.Tags, "Should not pick up tag from parent span")
		}

		err = protocol.ValidateTrace(span)
		_, isInvalid := err.(*protocol.InvalidTrace)
		assert.True(t, isInvalid)
		assert.NotNil(t, span)
	}
}

func TestParseSSFValid(t *testing.T) {
	metric := freshSSFMetric()

	trace := &ssf.SSFSpan{}
	trace.Id = 1
	trace.TraceId = 1
	trace.StartTimestamp = 1
	trace.EndTimestamp = 5
	trace.Tags = map[string]string{}
	trace.Tags["foo"] = "bar"

	trace.Metrics = make([]*ssf.SSFSample, 0)
	trace.Metrics = append(trace.Metrics, metric)

	buff, err := proto.Marshal(trace)
	assert.Nil(t, err)

	msg, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	if assert.NotNil(t, msg) {
		noTags := samplers.NewParser([]string{})
		yesTags := samplers.NewParser([]string{"implicit"})

		metrics, err := noTags.ConvertMetrics(msg)
		assert.NoError(t, err)
		if assert.Equal(t, 1, len(metrics)) {
			m := metrics[0]
			assert.Equal(t, metric.Name, m.Name, "Name")
			assert.Equal(t, float64(metric.Value), m.Value, "Value")
			assert.Equal(t, "counter", m.Type, "Type")
			assert.NotContains(t, m.Tags, "foo", "Metric should not inherit tags from its parent span")
			assert.NotContains(t, m.Tags, "implicit")
		}

		metrics, err = yesTags.ConvertMetrics(msg)
		assert.NoError(t, err)
		if assert.Equal(t, 1, len(metrics)) {
			m := metrics[0]
			assert.Equal(t, metric.Name, m.Name, "Name")
			assert.Equal(t, float64(metric.Value), m.Value, "Value")
			assert.Equal(t, "counter", m.Type, "Type")
			assert.NotContains(t, m.Tags, "foo", "Metric should not inherit tags from its parent span")
			assert.Contains(t, m.Tags, "implicit")
		}
	}
}

func TestParseSSFIndicatorSpan(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "foo"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = true
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)
	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	require.NotNil(t, inSpan)
	require.NoError(t, protocol.ValidateTrace(span))

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	metrics, err := noTags.ConvertIndicatorMetrics(inSpan, "timer_name", "")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 2, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
		assert.NotContains(t, m.Tags, "implicit")
	}

	metrics, err = yesTags.ConvertIndicatorMetrics(inSpan, "timer_name", "")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 3, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				"implicit",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}
}

func TestParseSSFIndicatorSpanWithError(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "foo"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = true
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)
	span.Error = true
	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	require.NotNil(t, span)
	require.NoError(t, protocol.ValidateTrace(span))

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	metrics, err := noTags.ConvertIndicatorMetrics(inSpan, "timer_name", "")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001,
			"Duration seems incorrect: %f vs. %d", m.Value, duration/time.Nanosecond)
		if assert.Equal(t, 2, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:true",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}

	metrics, err = yesTags.ConvertIndicatorMetrics(inSpan, "timer_name", "")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001,
			"Duration seems incorrect: %f vs. %d", m.Value, duration/time.Nanosecond)
		if assert.Equal(t, 3, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:true",
				"implicit",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}
}

func TestParseSSFIndicatorObjective(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "foo"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = true
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)
	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	require.NotNil(t, inSpan)
	require.NoError(t, protocol.ValidateTrace(span))

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	metrics, err := noTags.ConvertIndicatorMetrics(inSpan, "", "timer_name")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 3, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				"objective:foo",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}

	metrics, err = yesTags.ConvertIndicatorMetrics(inSpan, "", "timer_name")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 4, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				"implicit",
				"objective:foo",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}
}

func TestParseSSFIndicatorObjectiveTag(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "foo"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = true
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
		"ssf_objective":  "bar",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)
	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	require.NotNil(t, inSpan)
	require.NoError(t, protocol.ValidateTrace(span))

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	metrics, err := noTags.ConvertIndicatorMetrics(inSpan, "", "timer_name")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 3, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				"objective:bar",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}

	metrics, err = yesTags.ConvertIndicatorMetrics(inSpan, "", "timer_name")
	assert.NoError(t, err)
	if assert.Equal(t, 1, len(metrics)) {
		m := metrics[0]
		assert.Equal(t, "timer_name", m.Name)
		assert.Equal(t, "histogram", m.Type)
		assert.InEpsilon(t, float32(duration/time.Nanosecond), m.Value, 0.001)
		if assert.Equal(t, 4, len(m.Tags)) {
			var tags sort.StringSlice = m.Tags
			sort.Sort(tags)
			assert.Equal(t, sort.StringSlice{
				"error:false",
				"implicit",
				"objective:bar",
				fmt.Sprintf("service:%s", span.Service),
			}, tags)
		}
	}
}

func TestParseSSFIndicatorSpanNotNamed(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "foo"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = true
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)
	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	require.NotNil(t, inSpan)
	require.NoError(t, protocol.ValidateTrace(inSpan))

	metrics, err := (&samplers.Parser{}).ConvertIndicatorMetrics(inSpan, "", "")
	assert.NoError(t, err)
	assert.Equal(t, 0, len(metrics))
}

func TestParseSSFNonIndicatorSpan(t *testing.T) {
	duration := 5 * time.Second
	start := time.Now()
	end := start.Add(duration)

	span := &ssf.SSFSpan{}
	span.Id = 1
	span.TraceId = 5
	span.Name = "no-timer"
	span.StartTimestamp = start.UnixNano()
	span.EndTimestamp = end.UnixNano()
	span.Indicator = false
	span.Service = "bar-srv"
	span.Tags = map[string]string{
		"this-tag":       "definitely gets ignored",
		"this-other-tag": "also gets dropped",
	}
	span.Metrics = make([]*ssf.SSFSample, 0)

	buff, err := proto.Marshal(span)
	assert.Nil(t, err)
	inSpan, err := protocol.ParseSSF(buff)
	require.NotNil(t, inSpan)
	require.NoError(t, err)
	require.NoError(t, protocol.ValidateTrace(inSpan))

	metrics, err := (&samplers.Parser{}).ConvertIndicatorMetrics(inSpan, "timer_name", "objective_name")
	assert.NoError(t, err)
	assert.Equal(t, 0, len(metrics))
}

func TestParseSSFBadMetric(t *testing.T) {
	metric := freshSSFMetric()
	metric.Metric = 5

	trace := &ssf.SSFSpan{}

	trace.Metrics = make([]*ssf.SSFSample, 0)
	trace.Metrics = append(trace.Metrics, metric)

	buff, err := proto.Marshal(trace)
	assert.Nil(t, err)

	span, err := protocol.ParseSSF(buff)
	assert.NoError(t, err)
	if assert.NotNil(t, span) {
		metrics, err := (&samplers.Parser{}).ConvertMetrics(span)
		assert.Error(t, err)
		assert.Equal(t, 0, len(metrics))
		invalid, ok := err.(samplers.InvalidMetrics)
		if assert.True(t, ok, "Error type incorrect: %v", err) {
			assert.Equal(t, 1, len(invalid.Samples()))
		}
	}
}

func TestParserSSF(t *testing.T) {
	standardMetric := freshSSFMetric()
	m, _ := (&samplers.Parser{}).ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, float64(standardMetric.Value), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
}

func TestParserSSFGauge(t *testing.T) {
	standardMetric := freshSSFMetric()
	standardMetric.Metric = ssf.SSFSample_GAUGE
	m, _ := (&samplers.Parser{}).ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, float64(standardMetric.Value), m.Value, "Value")
	assert.Equal(t, "gauge", m.Type, "Type")
}

func TestParserSSFSet(t *testing.T) {
	standardMetric := freshSSFMetric()
	standardMetric.Metric = ssf.SSFSample_SET
	m, _ := (&samplers.Parser{}).ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, standardMetric.Message, m.Value, "Value")
	assert.Equal(t, "set", m.Type, "Type")
}

func TestParserSSFWithTags(t *testing.T) {
	standardMetric := freshSSFMetric()

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, float64(standardMetric.Value), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, 2, len(m.Tags), "# of Tags")

	m, _ = yesTags.ParseMetricSSF(standardMetric)
	assert.Equal(t, 3, len(m.Tags), "# of Tags")
}

func TestParserSSFWithSampleRate(t *testing.T) {
	standardMetric := freshSSFMetric()
	standardMetric.SampleRate = 0.1
	m, _ := (&samplers.Parser{}).ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, float64(standardMetric.Value), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, float32(0.1), m.SampleRate, "Sample Rate")
}

func TestParserSSFWithSampleRateAndTags(t *testing.T) {
	standardMetric := freshSSFMetric()
	standardMetric.SampleRate = 0.1

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, float64(standardMetric.Value), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, float32(0.1), m.SampleRate, "Sample Rate")
	assert.Len(t, m.Tags, 2, "Tags")
	m, _ = yesTags.ParseMetricSSF(standardMetric)
	assert.Len(t, m.Tags, 3, "Tags")
}

func TestParserSSFWithStatusCheck(t *testing.T) {
	standardMetric := freshSSFMetric()
	standardMetric.Metric = ssf.SSFSample_STATUS
	standardMetric.Status = ssf.SSFSample_UNKNOWN

	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetricSSF(standardMetric)
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, standardMetric.Name, m.Name, "Name")
	assert.Equal(t, ssf.SSFSample_UNKNOWN, m.Value, "Value")
	assert.Equal(t, "status", m.Type, "Type")
	assert.Len(t, m.Tags, 2, "Tags")
	m, _ = yesTags.ParseMetricSSF(standardMetric)
	assert.Len(t, m.Tags, 3, "Tags")
}

func TestParser(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|c"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|c"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserGauge(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|g"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "gauge", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|g"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserHistogram(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|h"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "histogram", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|h"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserHistogramFloat(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1.234|h"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1.234), m.Value, "Value")
	assert.Equal(t, "histogram", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1.234|h"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserTimer(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|ms"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "timer", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|ms"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserDistribution(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:0.1716441474854946|d|#filter:flatulent"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(0.1716441474854946), m.Value, "Value")
	assert.Equal(t, "histogram", m.Type, "Type")
	assert.Equal(t, 1, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:0.1716441474854946|d|#filter:flatulent"))
	assert.Equal(t, 2, len(m.Tags), "# of tags")
}

func TestParserTimerFloat(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1.234|ms"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1.234), m.Value, "Value")
	assert.Equal(t, "timer", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1.234|ms"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserSet(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:foo|s"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, "foo", m.Value, "Value")
	assert.Equal(t, "set", m.Type, "Type")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:foo|s"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")
}

func TestParserWithTags(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|c|#foo:bar,baz:gorch"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.EqualValues(t, []string{"baz:gorch", "foo:bar"}, m.Tags, "Expected Tags")
	y, _ := yesTags.ParseMetric([]byte("a.b.c:1|c|#foo:bar,baz:gorch"))
	assert.EqualValues(t, []string{"baz:gorch", "foo:bar", "implicit"}, y.Tags, "Expected Tags")

	// ensure that tag order doesn't matter: it must produce the same digest
	m2, _ := noTags.ParseMetric([]byte("a.b.c:1|c|#baz:gorch,foo:bar"))
	assert.EqualValues(t, []string{"baz:gorch", "foo:bar"}, m2.Tags, "Expected Tags")
	assert.Equal(t, m.Digest, m2.Digest, "Digest must not depend on tag order")
	assert.Equal(t, m.MetricKey, m2.MetricKey, "MetricKey must not depend on tag order")
	y2, _ := yesTags.ParseMetric([]byte("a.b.c:1|c|#baz:gorch,foo:bar"))
	assert.EqualValues(t, []string{"baz:gorch", "foo:bar", "implicit"}, y2.Tags, "Expected Tags")
	assert.Equal(t, y.Digest, y2.Digest, "Digest must not depend on tag order")
	assert.Equal(t, y.MetricKey, y2.MetricKey, "MetricKey must not depend on tag order")

	// treated as an empty tag
	m, err := noTags.ParseMetric([]byte("a.b.c:1|c|#"))
	assert.Equal(t, nil, err, "not an error")
	assert.EqualValues(t, []string{""}, m.Tags, "expected empty tag")
	m, err = yesTags.ParseMetric([]byte("a.b.c:1|c|#"))
	assert.Equal(t, nil, err, "not an error")
	assert.EqualValues(t, []string{"", "implicit"}, m.Tags, "expected empty tag")

	_, valueError := noTags.ParseMetric([]byte("a.b.c:fart|c"))
	assert.NotNil(t, valueError, "No errors when parsing")
	assert.Contains(t, valueError.Error(), "Invalid number", "Invalid number error missing")
}

func TestParserWithSampleRate(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|c|@0.1"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, float32(0.1), m.SampleRate, "Sample Rate")
	assert.Equal(t, 0, len(m.Tags), "# of tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|c|@0.1"))
	assert.Equal(t, 1, len(m.Tags), "# of tags")

	_, valueError := (&samplers.Parser{}).ParseMetric([]byte("a.b.c:fart|c"))
	assert.NotNil(t, valueError, "No errors when parsing")
	assert.Contains(t, valueError.Error(), "Invalid number", "Invalid number error missing")

	_, valueError = (&samplers.Parser{}).ParseMetric([]byte("a.b.c:1|g|@0.1"))
	assert.NoError(t, valueError, "Got errors when parsing")
}

func TestParserWithSampleRateAndTags(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	m, _ := noTags.ParseMetric([]byte("a.b.c:1|c|@0.1|#foo:bar,baz:gorch"))
	assert.NotNil(t, m, "Got nil metric!")
	assert.Equal(t, "a.b.c", m.Name, "Name")
	assert.Equal(t, float64(1), m.Value, "Value")
	assert.Equal(t, "counter", m.Type, "Type")
	assert.Equal(t, float32(0.1), m.SampleRate, "Sample Rate")
	assert.Len(t, m.Tags, 2, "Tags")
	m, _ = yesTags.ParseMetric([]byte("a.b.c:1|c|@0.1|#foo:bar,baz:gorch"))
	assert.Len(t, m.Tags, 3, "Tags")

	_, valueError := (&samplers.Parser{}).ParseMetric([]byte("a.b.c:fart|c"))
	assert.NotNil(t, valueError, "No errors when parsing")
	assert.Contains(t, valueError.Error(), "Invalid number", "Invalid number error missing")
}

func TestInvalidPackets(t *testing.T) {
	table := map[string]string{
		"foo":                                "1 colon",
		"foo:1":                              "1 pipe",
		"foo:1||":                            "metric type",
		"foo:|c|":                            "metric value",
		"this_is_a_bad_metric:nan|g|#shell":  "metric value",
		"this_is_a_bad_metric:NaN|g|#shell":  "metric value",
		"this_is_a_bad_metric:-inf|g|#shell": "metric value",
		"this_is_a_bad_metric:+inf|g|#shell": "metric value",
		"foo:1|foo|":                         "Invalid type",
		"foo:1|c||":                          "pipes",
		"foo:1|c|foo":                        "unknown section",
		"foo:1|c|@-0.1":                      ">0",
		"foo:1|c|@1.1":                       "<=1",
		"foo:1|c|@0.5|@0.2":                  "multiple sample rates",
		"foo:1|c|#foo|#bar":                  "multiple tag sections",
	}

	for packet, errContent := range table {
		_, err := (&samplers.Parser{}).ParseMetric([]byte(packet))
		assert.NotNil(t, err, "Should have gotten error parsing %q", packet)
		assert.Contains(t, err.Error(), errContent, "Error should have contained text")
	}
}

func TestLocalOnlyEscape(t *testing.T) {
	m, err := (&samplers.Parser{}).ParseMetric([]byte("a.b.c:1|h|#veneurlocalonly,tag2:quacks"))
	assert.NoError(t, err, "should have no error parsing")
	assert.Equal(t, samplers.LocalOnly, m.Scope, "should have gotten local only metric")
	assert.NotContains(t, m.Tags, "veneurlocalonly", "veneurlocalonly should not actually be a tag")
	assert.Contains(t, m.Tags, "tag2:quacks", "tag2 should be preserved in the list of tags after removing magic tags")
}

func TestGlobalOnlyEscape(t *testing.T) {
	m, err := (&samplers.Parser{}).ParseMetric([]byte("a.b.c:1|h|#veneurglobalonly,tag2:quacks"))
	assert.NoError(t, err, "should have no error parsing")
	assert.Equal(t, samplers.GlobalOnly, m.Scope, "should have gotten local only metric")
	assert.NotContains(t, m.Tags, "veneurglobalonly", "veneurlocalonly should not actually be a tag")
	assert.Contains(t, m.Tags, "tag2:quacks", "tag2 should be preserved in the list of tags after removing magic tags")
}

func TestEvents(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	evt, err := noTags.ParseEvent([]byte("_e{3,3}:foo|bar|k:foos|s:test|t:success|p:low|#foo:bar,baz:qux|d:1136239445|h:example.com"))
	assert.NoError(t, err, "should have parsed correctly")
	assert.EqualValues(t, &ssf.SSFSample{
		Name:      "foo",
		Message:   "bar",
		Timestamp: 1136239445,
		Tags: map[string]string{
			dogstatsd.EventIdentifierKey:        "",
			dogstatsd.EventAggregationKeyTagKey: "foos",
			dogstatsd.EventSourceTypeTagKey:     "test",
			dogstatsd.EventAlertTypeTagKey:      "success",
			dogstatsd.EventPriorityTagKey:       "low",
			dogstatsd.EventHostnameTagKey:       "example.com",
			"foo":                               "bar",
			"baz":                               "qux",
		},
	}, evt, "should have parsed event")
	evt, err = yesTags.ParseEvent([]byte("_e{3,3}:foo|bar|k:foos|s:test|t:success|p:low|#foo:bar,baz:qux|d:1136239445|h:example.com"))
	assert.NoError(t, err, "should have parsed correctly")
	assert.Equal(t, map[string]string{
		dogstatsd.EventIdentifierKey:        "",
		dogstatsd.EventAggregationKeyTagKey: "foos",
		dogstatsd.EventSourceTypeTagKey:     "test",
		dogstatsd.EventAlertTypeTagKey:      "success",
		dogstatsd.EventPriorityTagKey:       "low",
		dogstatsd.EventHostnameTagKey:       "example.com",
		"foo":                               "bar",
		"baz":                               "qux",
		"implicit":                          "",
	}, evt.Tags)

	table := map[string]string{
		"_e{4,3}:foo|bar":               "title length",
		"_e{3,4}:foo|bar":               "text length",
		"_e{3,3}:foo|bar|d:abc":         "date",
		"_e{3,3}:foo|bar|p:baz":         "priority",
		"_e{3,3}:foo|bar|t:baz":         "alert",
		"_e{3,3}:foo|bar|t:info|t:info": "multiple alert",
		"_e{3,3}:foo|bar||":             "pipe",
		"_e{3,0}:foo||":                 "text length",
		"_e{3,3}:foo":                   "text",
		"_e{3,3}":                       "colon",
	}
	for packet, errContent := range table {
		_, err := (&samplers.Parser{}).ParseEvent([]byte(packet))
		assert.NotNil(t, err, "Should have gotten error parsing %q", packet)
		assert.Contains(t, err.Error(), errContent, "Error should have contained text")
	}
}

func TestServiceChecks(t *testing.T) {
	noTags := samplers.NewParser([]string{})
	yesTags := samplers.NewParser([]string{"implicit"})

	svcCheck, err := noTags.ParseServiceCheck([]byte("_sc|foo.bar|0|#foo:bar,qux:dor|d:1136239445|h:example.com"))
	assert.NoError(t, err, "should have parsed correctly")
	expected := &samplers.UDPMetric{
		MetricKey: samplers.MetricKey{
			Name:       "foo.bar",
			Type:       "status",
			JoinedTags: "foo:bar,qux:dor",
		},
		SampleRate: 1.0,
		Value:      ssf.SSFSample_OK,
		Timestamp:  1136239445,
		HostName:   "example.com",
		Tags: []string{
			"foo:bar",
			"qux:dor",
		},
	}
	h := fnv1a.Init32
	h = fnv1a.AddString32(h, expected.Name)
	h = fnv1a.AddString32(h, expected.Type)
	h = fnv1a.AddString32(h, expected.JoinedTags)
	expected.Digest = h

	assert.EqualValues(t, expected, svcCheck, "should have parsed event")

	svcCheck, err = yesTags.ParseServiceCheck([]byte("_sc|foo.bar|0|#foo:bar,qux:dor|d:1136239445|h:example.com"))
	assert.NoError(t, err, "should have parsed correctly")
	expected = &samplers.UDPMetric{
		MetricKey: samplers.MetricKey{
			Name:       "foo.bar",
			Type:       "status",
			JoinedTags: "foo:bar,implicit,qux:dor",
		},
		SampleRate: 1.0,
		Value:      ssf.SSFSample_OK,
		Timestamp:  1136239445,
		HostName:   "example.com",
		Tags: []string{
			"foo:bar",
			"implicit",
			"qux:dor",
		},
	}
	h = fnv1a.Init32
	h = fnv1a.AddString32(h, expected.Name)
	h = fnv1a.AddString32(h, expected.Type)
	h = fnv1a.AddString32(h, expected.JoinedTags)
	expected.Digest = h

	assert.EqualValues(t, expected, svcCheck, "should have parsed event")

	table := map[string]string{
		"foo.bar|0":           "_sc",
		"_sc|foo.bar":         "status",
		"_sc|foo.bar|5":       "status",
		"_sc|foo.bar|0||":     "pipe",
		"_sc|foo.bar|0|d:abc": "date",
	}
	for packet, errContent := range table {
		_, err := (&samplers.Parser{}).ParseServiceCheck([]byte(packet))
		assert.NotNil(t, err, "Should have gotten error parsing %q", packet)
		assert.Contains(t, err.Error(), errContent, "Error should have contained text")
	}
}

func TestEventMessageUnescape(t *testing.T) {
	packet := []byte("_e{3,15}:foo|foo\\nbar\\nbaz\\n")
	evt, err := (&samplers.Parser{}).ParseEvent(packet)
	assert.NoError(t, err, "Should have parsed correctly")
	assert.Equal(t, "foo\nbar\nbaz\n", evt.Message, "Should contain newline")
}

func TestServiceCheckMessageUnescape(t *testing.T) {
	packet := []byte("_sc|foo|0|m:foo\\nbar\\nbaz\\n")
	svcheck, err := (&samplers.Parser{}).ParseServiceCheck(packet)
	assert.NoError(t, err, "Should have parsed correctly")
	assert.Equal(t, "foo\nbar\nbaz\n", svcheck.Message, "Should contain newline")
}

func TestServiceCheckMessageStatus(t *testing.T) {
	packet := []byte("_sc|foo|1|m:foo")
	svcheck, err := (&samplers.Parser{}).ParseServiceCheck(packet)
	assert.NoError(t, err, "Should have parsed correctly")
	assert.Equal(t, "foo", svcheck.Message, "Should contain newline")
	assert.Equal(t, ssf.SSFSample_WARNING, svcheck.Value, "Should parse status correctly")
}

func TestConsecutiveParseSSF(t *testing.T) {

	span := &ssf.SSFSpan{
		Id:             12345678,
		TraceId:        1,
		StartTimestamp: 123,
		EndTimestamp:   124,
		Tags: map[string]string{
			"foo": "bar",
		},
	}
	buff1, err := proto.Marshal(span)
	assert.Nil(t, err)

	otherSpan := &ssf.SSFSpan{
		Id:             12345679,
		TraceId:        2,
		StartTimestamp: 125,
		EndTimestamp:   126,
	}
	buff2, err := proto.Marshal(otherSpan)
	assert.Nil(t, err)

	// Because ParseSSF reuses buffers via a Pool when parsing we
	// want to ensure that subsequent calls properly reset and
	// don't bleed into each other, so "parse" each and check.
	span1, err := protocol.ParseSSF(buff1)
	assert.Nil(t, err)
	span2, err := protocol.ParseSSF(buff2)
	assert.Nil(t, err)

	assert.Equal(t, int64(12345678), span1.Id)
	assert.Equal(t, "bar", span1.Tags["foo"], "Tagful span has no tags!")

	assert.Equal(t, int64(12345679), span2.Id)
	assert.Equal(t, "", span2.Tags["foo"], "Tagless span has tags!")
}

func BenchmarkParseSSF(b *testing.B) {
	span := &ssf.SSFSpan{}

	buff, err := proto.Marshal(span)
	assert.Nil(b, err)

	for n := 0; n < b.N; n++ {
		protocol.ParseSSF(buff)
	}
}

var benchResult uint32

func BenchmarkParseMetric(b *testing.B) {
	var total uint32

	metricName := "a.b.c"
	metricValues := []struct {
		name        string
		metricValue string
		metricType  string
	}{
		{"IntCount", "1", "c"},
		{"FloatHistogram", "4.5", "h"},
	}
	explicitTags := []struct {
		name       string
		metricTags string
	}{
		{"ZeroTags", ""},
		{"OneTag", "baz:gorch"},
		{"TwoTags", "foo:bar,baz:gorch"},
	}
	implicitTags := []struct {
		name       string
		metricTags []string
	}{
		{"NoImplicit", []string{}},
		{"OneImplicit", []string{"six:6"}},
		{"TwoImplicit", []string{"three:three", "six:6", "nine:9", "ten:10", "eleven:11", "twelve:12"}},
	}

	for _, mv := range metricValues {
		for _, it := range implicitTags {
			for _, et := range explicitTags {
				var statsd string
				if et.metricTags == "" {
					statsd = fmt.Sprintf("%s:%s|%s", metricName, mv.metricValue, mv.metricType)
				} else {
					statsd = fmt.Sprintf("%s:%s|%s#%s", metricName, mv.metricValue, mv.metricType, et.metricTags)
				}
				benchName := fmt.Sprintf("%s%s%s", mv.name, it.name, et.name)
				metricBytes := []byte(statsd)
				parser := samplers.NewParser(it.metricTags)
				b.Run(benchName, func(b *testing.B) {
					for n := 0; n < b.N; n++ {
						m, err := parser.ParseMetric(metricBytes)
						if err != nil {
							b.Fatal(err)
						}
						total += m.Digest
					}
				})
			}
		}
	}
	// Attempt to avoid compiler optimizations? Is this relevant?
	benchResult = total
}


text:
<?php
/*
Template Name: Homepage - No limit
Description: Section with 2 titles, 2 contents and 2 illustrations
---------------------------------------------------------------------
{"type": "title", "name": "no limit", "slug": "nolimit"}
---------------------------------------------------------------------
*/
?>

			<?php the_chapter_title('nolimit') ?>


text:
const Facts = {};
const FACTS_COLLECTION = 'meteor_Facts_server';
const FACTS_PUBLICATION = 'meteor_facts';

export {
  Facts,
  FACTS_COLLECTION,
  FACTS_PUBLICATION,
};


text:
package com.gs.collections.api.bag;

import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.predicate.primitive.IntPredicate;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.collection.MutableCollection;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MutableMapIterable;
import com.gs.collections.api.multimap.bag.MutableBagIterableMultimap;
import com.gs.collections.api.partition.bag.PartitionMutableBagIterable;
import com.gs.collections.api.set.MutableSetIterable;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.primitive.ObjectIntPair;

public interface MutableBagIterable<T> extends Bag<T>, MutableCollection<T>
{
    void addOccurrences(T item, int occurrences);

    boolean removeOccurrences(Object item, int occurrences);

    boolean setOccurrences(T item, int occurrences);

    MutableBagIterable<T> tap(Procedure<? super T> procedure);

    MutableBagIterable<T> select(Predicate<? super T> predicate);

    <P> MutableBagIterable<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter);

    MutableBagIterable<T> reject(Predicate<? super T> predicate);

    <P> MutableBagIterable<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter);

    PartitionMutableBagIterable<T> partition(Predicate<? super T> predicate);

    <P> PartitionMutableBagIterable<T> partitionWith(Predicate2<? super T, ? super P> predicate, P parameter);

    <S> MutableBagIterable<S> selectInstancesOf(Class<S> clazz);

    <V> MutableBagIterableMultimap<V, T> groupBy(Function<? super T, ? extends V> function);

    <V> MutableBagIterableMultimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function);

    MutableSetIterable<Pair<T, Integer>> zipWithIndex();

    MutableBagIterable<T> selectByOccurrences(IntPredicate predicate);

    MutableMapIterable<T, Integer> toMapOfItemToCount();

    /**
     * @since 6.0
     */
    MutableList<ObjectIntPair<T>> topOccurrences(int count);

    /**
     * @since 6.0
     */
    MutableList<ObjectIntPair<T>> bottomOccurrences(int count);

    MutableBagIterable<T> with(T element);

    MutableBagIterable<T> without(T element);

    MutableBagIterable<T> withAll(Iterable<? extends T> elements);

    MutableBagIterable<T> withoutAll(Iterable<? extends T> elements);
}