text:
require File.dirname(__FILE__) + '/../spec_helper'

describe Project, "#new with no attributes" do
  before do
    @project = Project.new
  end

  it "should not be valid" do
    @project.should_not be_valid
  end
end

describe Project, "#new with name attribute" do
  it "should be valid" do
    @project = Project.new :name => "foo"
    @project.should be_valid
  end

  it "should not be valid with an empty string for name" do
    @project = Project.new :name => ""
    @project.should_not be_valid
  end
end

describe Project, "starting a new iteration" do
  it "creates a new iteration" do
    project = Generate.project
    lambda {
      iteration = project.start_new_iteration!
      project.iterations.current.should == iteration
    }.should change(Iteration, :count).by(1)
  end

  context "when a previous iteration exists" do
    it "ends the previous iteration" do
      project = Generate.project :iterations => []
      project.iterations.find_or_build_current.save!
      iteration = project.iterations.current
      iteration.ended_at.should be_nil

      new_iteration = project.start_new_iteration!
      iteration.reload
      iteration.ended_at.should_not be_nil
      iteration.ended_at.should <= new_iteration.started_at
    end

    it "builds a snapshot for the previous iteration" do
      project = Generate.project :iterations => []
      iteration = project.iterations.find_or_build_current
      iteration.save!
      project.stub!(:total_points).and_return(1)
      project.stub!(:completed_points).and_return(2)
      project.stub!(:remaining_points).and_return(3)
      project.stub!(:average_velocity).and_return(4)
      project.stub!(:estimated_remaining_iterations).and_return(5)
      project.stub!(:estimated_completion_date).and_return(1.year.ago.to_date)

      new_iteration = project.start_new_iteration!

      snapshot = new_iteration.snapshot
      snapshot.total_points.should == 1
      snapshot.completed_points.should == 2
      snapshot.remaining_points.should == 3
      snapshot.average_velocity.should == 4
      snapshot.estimated_remaining_iterations.should == 5
      snapshot.estimated_completion_date.should == 1.year.ago.to_date
    end
  end
end

describe Project, '#story_tags' do
  before do
    @project = Generate.project :name => "foo"
    @stories = [
      Generate.story(:summary => "story 1", :project => @project),
      Generate.story(:summary => "story 2", :project => @project) ]
    @stories.first.tag_list = "foo, baz"
    @stories.last.tag_list = "foo, baz, bar"
    @stories.each{ |s| s.save! }
  end

  it "returns the unique tags that belong to the stories on this project" do
    @project.story_tags.should == (@stories.first.tags + @stories.last.tags).uniq
  end
end

describe Project, '#tagless_stories' do
  before do
    @project = Generate.project :name => "foo"
    @stories = [
      Generate.story(:summary => "story1", :project => @project),
      Generate.story(:summary => "story2", :project => @project),
      Generate.story(:summary => "story3", :project => @project) ]
    @stories[0].tag_list = ""
    @stories[1].tag_list = "foo, baz, bar"
    @stories[2].tag_list = ""
    @stories.each{ |s| s.save! }
  end

  it "returns stories which are not tagged" do
    @project.tagless_stories.should == [@stories[0], @stories[2]]
  end

  it "doesn't include stories from other projects" do
    @project2 = Generate.project :name => "baz"
    @story2 = Generate.story :summary => "another project's story", :project => @project2
    @project.tagless_stories.should_not include(@story2)
  end
end

describe Project, '#completed_iterations' do
  before do
    @project = Project.create :name=>"Project w/Activities"
    @completed_iterations = [
      Generate.iteration(:name => "iteration 1", :project => @project, :started_at => 4.weeks.ago, :ended_at => 3.weeks.ago),
      Generate.iteration(:name => "iteration 2", :project => @project, :started_at => 2.weeks.ago, :ended_at => 1.week.ago)
    ]
    Generate.iteration :name => "iteration 3", :project => @project, :started_at => Time.now, :ended_at => 1.week.from_now
    Generate.iteration :name => "iteration 4", :project => @project, :started_at => 2.weeks.from_now, :ended_at => 3.weeks.from_now
  end

  it "returns only iterations whose ended_at are before today" do
    @project.completed_iterations.size.should == @completed_iterations.size
    @completed_iterations.each do |iteration|
      @project.completed_iterations.should include(iteration)
    end
  end
end

describe Project, "#recent_activities" do
  def recent_activities(*args)
    @project.recent_activities *args
  end

  before do
    @project = Project.create :name=>"Project w/Activities"

    @activity1 = Activity.create(:project_id=>@project.id, :actor_id=>1, :action=>"creating", :affected_id=>1, :affected_type=>"story1")
    @activity1.update_attribute 'created_at', Date.today

    @activity2 = Activity.create(:project_id=>@project.id, :actor_id=>1, :action=>"editing", :affected_id=>2, :affected_type=>"story2")
    @activity2.update_attribute 'created_at', Date.today - 1

    @activity3 = Activity.create(:project_id=>@project.id, :actor_id=>1, :action=>"editing", :affected_id=>3, :affected_type=>"story3")
    @activity3.update_attribute 'created_at', Date.today - 2

    @activity4 = Activity.create(:project_id=>@project.id, :actor_id=>1, :action=>"editing", :affected_id=>4, :affected_type=>"story4")
    @activity4.update_attribute 'created_at', Date.today - 7

    @activity5 = Activity.create(:project_id=>@project.id, :actor_id=>1, :action=>"editing", :affected_id=>5, :affected_type=>"story5")
    @activity5.update_attribute 'created_at', Date.today - 8
  end

  describe "when no arguments are given" do
    it "returns only project activities from within the past day when given no arguments" do
      @project.recent_activities.should ==  [@activity1, @activity2]
    end
  end

  describe "when an argument is given" do
    it "returns project activities which originated within the past in timeframe" do
      @project.recent_activities(2.days).should == [@activity1, @activity2, @activity3]
      @project.recent_activities(1.week).should == [@activity1, @activity2, @activity3, @activity4]
    end
  end
end

describe Project, "iterations_ordered_by_started_at" do
  before do
    @project = Generate.project :name => "ProjectA"
    @iteration1 = (Generate.iteration :name => "Iteration5", :project => @project, :started_at => Date.today - 3.weeks)
    @iteration3 = (Generate.iteration :name => "Iteration5", :project => @project, :started_at => Date.today - 1.week)
    @iteration2 = (Generate.iteration :name => "Iteration5", :project => @project, :started_at => Date.today - 2.weeks)
    @project.iterations = [ @iteration1, @iteration3, @iteration2 ]
    @project.save!
  end

  it "returns all iterations ordered by their start date" do
    @project.iterations_ordered_by_started_at.should == [ @iteration1, @iteration2, @iteration3 ]
  end
end

describe Project, "#backlog_stories" do
  before do
    @project = Generate.project :name => "ProjectA"
    @iteration = Generate.iteration :name => "Iteration1", :project => @project

    @story1 = Generate.story :summary => "story1", :project => @project
    @story2 = Generate.story :summary => "story2", :project => @project
    @story3 = Generate.story :summary => "story3", :project => @project ; @story3.move_higher #acts_as_list
    @story4 = Generate.story :summary => "story4", :project => @project, :bucket => @iteration
  end

  it "returns all of the project not assigned to an iteration ordered by position" do
    @project.backlog_stories.should == [ @story1, @story3, @story2 ]
  end
end

describe Project, "#backlog_iteration" do
  before do
    @project = Generate.project :name => "ProjectA"
    @backlog = @project.backlog_iteration
  end

  it "returns a new Iteration" do
    @backlog.new_record?.should be_true
  end

  describe "the returned iteration" do
    it "has a name of 'Backlog'" do
      @backlog.name.should == "Backlog"
    end
  end
end

describe Project, '#update_members' do
  before do
    @members = [ Generate.user, Generate.user, Generate.user ]
    @project = Generate.project :name => "Foo", :members => @members
    @project.users.should == @members
  end

  it "grants permissions on the project to only the users with the passed ids" do
    @project.update_members [@members.first.id, @members.last.id]
    @project.users.reload.should == [@members.first, @members.last]
  end

  it "does nothing when passed a blank value" do
    @project.update_members ""
    @project.users.should == @members
    @project.update_members nil
    @project.users.should == @members
  end
end

describe Project, '#incomplete_stories' do
  def incomplete_stories
    @project.incomplete_stories
  end

  before do
    @project = Generate.project
    @incomplete_stories = []
    story_count = 3
    story_count.times do |i|
      @incomplete_stories << Generate.story(:project => @project)
      @incomplete_stories.last.update_attribute(:position, story_count - i)
    end
    @sorted_incomplete_stories = @incomplete_stories.sort_by{ |story| story.position }
  end

  it "returns incomplete stories ordered by position" do
    incomplete_stories.should == @sorted_incomplete_stories
    incomplete_stories.zip(@sorted_incomplete_stories) do |actual, expected|
      actual.should == expected
    end
  end

  describe "when stories are completed" do
    before do
      @completed_stories = []
      3.times { @completed_stories << Generate.story(:project => @project, :status => Status.complete) }
    end

    it "does not include completed stories" do
      incomplete_stories.should == @sorted_incomplete_stories
    end
  end
end

describe Project, "#iterations" do
  before do
    @project = Generate.project
  end

  it "can generate a dummy backlog iteration" do
    backlog = @project.iterations.backlog
    backlog.id.should be_nil
    backlog.name.should == "Backlog"
  end

  describe "returning the current iteration" do
    it "returns an iteration that started today and does not have an end date" do
      iteration = Generate.iteration :project => @project, :started_at => Time.now, :ended_at => nil
      @project.iterations.current.should == iteration
    end

    it "returns an iteration that started before today and does not have an end date" do
      iteration = Generate.iteration :project => @project, :started_at => 1.weeks.ago, :ended_at => nil
      @project.iterations.current.should == iteration
    end

    it "does not return an iteration that has a start date" do
      iteration = Generate.iteration :project => @project, :started_at => 1.weeks.ago, :ended_at => Time.now
      @project.iterations.current.should be_nil

      @project.iterations.clear
      iteration = Generate.iteration :project => @project, :started_at => Time.now, :ended_at => 1.day.from_now
      @project.iterations.current.should be_nil
    end
  end

  it "can return the iteration with the second latest start date as the previous iteration" do
    @project.iterations.clear
    @previous_iteration = Generate.iteration :project => @project, :started_at => 2.weeks.ago, :ended_at => 1.weeks.ago
    current_iteration = Generate.iteration :project => @project, :started_at => Date.today, :ended_at => nil
    @project.iterations.previous.should == @previous_iteration
  end

  it "can find or build the current iteration" do
    now = Time.now
    Time.stub!(:now).and_return(now)
    current_iteration = Generate.iteration :project => @project, :started_at => 1.day.ago, :ended_at => nil
    @project.iterations.find_or_build_current.should == current_iteration

    @project.iterations.clear
    @project.iterations.should be_empty
    iteration = @project.iterations.find_or_build_current
    iteration.started_at.should == now
    iteration.ended_at.should be_nil
  end
end


text:
#pragma once
#include <aws/firehose/Firehose_EXPORTS.h>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Firehose
{
namespace Model
{
  class AWS_FIREHOSE_API UntagDeliveryStreamResult
  {
  public:
    UntagDeliveryStreamResult();
    UntagDeliveryStreamResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    UntagDeliveryStreamResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

  };

} // namespace Model
} // namespace Firehose
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
package org.rocksdb;

import java.util.Random;

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.assertj.core.api.Assertions.assertThat;

public class ReadOptionsTest {

  @ClassRule
  public static final RocksMemoryResource rocksMemoryResource =
      new RocksMemoryResource();

  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void verifyChecksum() {
    try (final ReadOptions opt = new ReadOptions()) {
      final Random rand = new Random();
      final boolean boolValue = rand.nextBoolean();
      opt.setVerifyChecksums(boolValue);
      assertThat(opt.verifyChecksums()).isEqualTo(boolValue);
    }
  }

  @Test
  public void fillCache() {
    try (final ReadOptions opt = new ReadOptions()) {
      final Random rand = new Random();
      final boolean boolValue = rand.nextBoolean();
      opt.setFillCache(boolValue);
      assertThat(opt.fillCache()).isEqualTo(boolValue);
    }
  }

  @Test
  public void tailing() {
    try (final ReadOptions opt = new ReadOptions()) {
      final Random rand = new Random();
      final boolean boolValue = rand.nextBoolean();
      opt.setTailing(boolValue);
      assertThat(opt.tailing()).isEqualTo(boolValue);
    }
  }

  @Test
  public void snapshot() {
    try (final ReadOptions opt = new ReadOptions()) {
      opt.setSnapshot(null);
      assertThat(opt.snapshot()).isNull();
    }
  }

  @Test
  public void failSetVerifyChecksumUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.setVerifyChecksums(true);
    }
  }

  @Test
  public void failVerifyChecksumUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.verifyChecksums();
    }
  }

  @Test
  public void failSetFillCacheUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.setFillCache(true);
    }
  }

  @Test
  public void failFillCacheUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.fillCache();
    }
  }

  @Test
  public void failSetTailingUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.setTailing(true);
    }
  }

  @Test
  public void failTailingUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.tailing();
    }
  }

  @Test
  public void failSetSnapshotUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.setSnapshot(null);
    }
  }

  @Test
  public void failSnapshotUninitialized() {
    try (final ReadOptions readOptions =
             setupUninitializedReadOptions(exception)) {
      readOptions.snapshot();
    }
  }

  private ReadOptions setupUninitializedReadOptions(
      ExpectedException exception) {
    final ReadOptions readOptions = new ReadOptions();
    readOptions.close();
    exception.expect(AssertionError.class);
    return readOptions;
  }
}


text:
package com.moon.signaldetector;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;

import com.google.common.io.Files;

public class Logger {
	private static final String TAG = "Logger";
	private static final boolean D = true;

	private final int mId;
	private final File mFile;

	private int mHeaderNum;

	public Logger(int id, String tag) {
		super();
		mId = id;

		File dir = new File(Environment.getExternalStorageDirectory(),
				"signal_log");
		if (!dir.exists()) {
			dir.mkdir();
		}

		mFile = new File(dir, mId + "_"
				+ DateFormat.format("yyyyMMdd_kkmmss", new Date()) + "_" + tag
				+ ".txt");
	}

	/**
	 *
	 * @param metaData
	 *            metaData = #id | time | device
	 */
	public void setMetaData(String metaData) {
		append(metaData);
	}

	/**
	 *
	 * @param header
	 *            header = $line | time
	 */
	public void setHeader(long time) {
		append("$" + mHeaderNum + "|" + time);
		mHeaderNum++;
	}

	/**
	 *
	 * @param location
	 *            location = @ lat,lng | accu
	 */
	public void setLocation(String location) {
		append(location);
	}

	/**
	 *
	 * @param aps
	 *            aps = %ap\n%ap ap = ssid | bssid | level | frequency |
	 *            timestamp
	 */
	public void setAps(List<String> aps) {
		for (String ap : aps) {
			append(ap);
		}
	}

	/**
	 *
	 * @param cell
	 *            cell = ? lac|cid|rssi
	 */
	public void setCell(String cell) {
		append(cell);
	}

	private void append(String msg) {
		try {
			Files.append(msg + "\n", mFile, Charset.defaultCharset());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
		}
	}
}


text:
namespace node {
namespace {

using v8::Array;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::Map;
using v8::Object;
using v8::String;
using v8::Value;

// TODO(joyeecheung): deprecate this function in favor of
// lib/util.getSystemErrorName()
void ErrName(const FunctionCallbackInfo<Value>& args) {
  Environment* env = Environment::GetCurrent(args);
  int err = args[0]->Int32Value();
  CHECK_LT(err, 0);
  const char* name = uv_err_name(err);
  args.GetReturnValue().Set(OneByteString(env->isolate(), name));
}

void Initialize(Local<Object> target,
                Local<Value> unused,
                Local<Context> context) {
  Environment* env = Environment::GetCurrent(context);
  Isolate* isolate = env->isolate();
  target->Set(FIXED_ONE_BYTE_STRING(isolate, "errname"),
              env->NewFunctionTemplate(ErrName)->GetFunction());

#define V(name, _) NODE_DEFINE_CONSTANT(target, UV_##name);
  UV_ERRNO_MAP(V)
#undef V

  Local<Map> err_map = Map::New(isolate);

#define V(name, msg) do {                                                     \
  Local<Array> arr = Array::New(isolate, 2);                                  \
  arr->Set(0, OneByteString(isolate, #name));                                 \
  arr->Set(1, OneByteString(isolate, msg));                                   \
  err_map->Set(context,                                                       \
               Integer::New(isolate, UV_##name),                              \
               arr).ToLocalChecked();                                         \
} while (0);
  UV_ERRNO_MAP(V)
#undef V

  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "errmap"),
              err_map).FromJust();
}

}  // anonymous namespace
}  // namespace node

NODE_BUILTIN_MODULE_CONTEXT_AWARE(uv, node::Initialize)


text:
module.exports = {

  name: 'Class',
  description: 'The base class is the essential building block for Ouro applications.',

  methods: {

    init: {
      description: 'The init method is the constructor for the class.'
    },

    get: {
      description: 'The default get method allows you to quickly get a value at a specified path (e.g. object.x).'
    },

    set: {
      description: 'The default set method allows you to quickly save a value at a specified path (e.g. object.x).'
    },

    _metaFile: {
      description: 'The meta file method is the hook that classes can use to load meta data via _loadMeta.',
    },

    _loadMeta: {
      description: 'The load meta method loads a meta file from a specified path and merges data onto existing data.'
    },

    _processMeta: {
      description: 'The process meta method checks and sanitizes the meta data.'
    },

    _modulePath: {
      description: 'Get a modules path from a nested class path.'
    },

    _load: {
      description: 'The load class method allows any class to load classes into the local or global namespace.'
    },

    _class: {
      description: 'The get module method attempts to find a class in either the local or global namespace.'
    }

  }
};


text:
import { getCounterData } from "./utils";

let dummy: any;

describe("Visualizations -> Counter -> Utils", () => {
  beforeEach(() => {
    dummy = {
      rows: [
        { city: "New York City", population: 18604000 },
        { city: "Shangai", population: 24484000 },
        { city: "Tokyo", population: 38140000 },
      ],
      options: {},
      visualisationName: "Visualisation Name",
      result: {
        counterLabel: "Visualisation Name",
        counterValue: "",
        targetValue: null,
        counterValueTooltip: "",
        targetValueTooltip: "",
      },
    };
  });

  describe("getCounterData()", () => {
    describe('"Count rows" option is disabled', () => {
      test("No target and counter values return empty result", () => {
        const result = getCounterData(dummy.rows, dummy.options, dummy.visualisationName);
        expect(result).toEqual({
          ...dummy.result,
          showTrend: false,
        });
      });

      test('"Counter label" overrides vizualization name', () => {
        const result = getCounterData(dummy.rows, { counterLabel: "Counter Label" }, dummy.visualisationName);
        expect(result).toEqual({
          ...dummy.result,
          counterLabel: "Counter Label",
          showTrend: false,
        });
      });

      test('"Counter Value Column Name" must be set to a correct non empty value', () => {
        const result = getCounterData(dummy.rows, { rowNumber: 3 }, dummy.visualisationName);
        expect(result).toEqual({
          ...dummy.result,
          showTrend: false,
        });

        const result2 = getCounterData(dummy.rows, { counterColName: "missingColumn" }, dummy.visualisationName);
        expect(result2).toEqual({
          ...dummy.result,
          showTrend: false,
        });
      });

      test('"Counter Value Column Name" uses correct column', () => {
        const result = getCounterData(dummy.rows, { counterColName: "population" }, dummy.visualisationName);
        expect(result).toEqual({
          ...dummy.result,
          counterValue: "18,604,000.000",
          counterValueTooltip: "18,604,000",
          showTrend: false,
        });
      });

      test("Counter and target values return correct result including trend", () => {
        const result = getCounterData(
          dummy.rows,
          {
            rowNumber: 1,
            counterColName: "population",
            targetRowNumber: 2,
            targetColName: "population",
          },
          dummy.visualisationName
        );
        expect(result).toEqual({
          ...dummy.result,
          counterValue: "18,604,000.000",
          counterValueTooltip: "18,604,000",
          targetValue: "24484000",
          targetValueTooltip: "24,484,000",
          showTrend: true,
          trendPositive: false,
        });

        const result2 = getCounterData(
          dummy.rows,
          {
            rowNumber: 2,
            counterColName: "population",
            targetRowNumber: 1,
            targetColName: "population",
          },
          dummy.visualisationName
        );
        expect(result2).toEqual({
          ...dummy.result,
          counterValue: "24,484,000.000",
          counterValueTooltip: "24,484,000",
          targetValue: "18604000",
          targetValueTooltip: "18,604,000",
          showTrend: true,
          trendPositive: true,
        });
      });
    });

    describe('"Count rows" option is enabled', () => {
      beforeEach(() => {
        dummy.result = {
          ...dummy.result,
          counterValue: "3.000",
          counterValueTooltip: "3",
          showTrend: false,
        };
      });

      test("Rows are counted correctly", () => {
        const result = getCounterData(dummy.rows, { countRow: true }, dummy.visualisationName);
        expect(result).toEqual(dummy.result);
      });

      test("Counter value is ignored", () => {
        const result = getCounterData(
          dummy.rows,
          {
            countRow: true,
            rowNumber: 3,
            counterColName: "population",
          },
          dummy.visualisationName
        );
        expect(result).toEqual(dummy.result);
      });

      test("Target value and trend are computed correctly", () => {
        const result = getCounterData(
          dummy.rows,
          {
            countRow: true,
            targetRowNumber: 2,
            targetColName: "population",
          },
          dummy.visualisationName
        );
        expect(result).toEqual({
          ...dummy.result,
          targetValue: "24484000",
          targetValueTooltip: "24,484,000",
          showTrend: true,
          trendPositive: false,
        });
      });

      test("Empty rows return counter value 0", () => {
        const result = getCounterData([], { countRow: true }, dummy.visualisationName);
        expect(result).toEqual({
          ...dummy.result,
          counterValue: "0.000",
          counterValueTooltip: "0",
        });
      });
    });
  });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>zorns-lemma: 12 s 🏆</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / released

8.13.2 / zorns-lemma - 10.0.1

            « Up

              zorns-lemma

                10.0.1
                12 s 🏆

📅  (2022-09-11 19:32:31 UTC)

Context

# Packages matching: installed
# Name                # Installed # Synopsis
base-bigarray         base
base-threads          base
base-unix             base
conf-findutils        1           Virtual package relying on findutils
conf-gmp              4           Virtual package relying on a GMP lib system installation
coq                   8.13.2      Formal proof management system
num                   1.4         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml                 4.13.1      The OCaml compiler (virtual package)
ocaml-base-compiler   4.13.1      Official release 4.13.1
ocaml-config          2           OCaml Switch Configuration
ocaml-options-vanilla 1           Ensure that OCaml is compiled with no special options enabled
ocamlfind             1.9.5       A library manager for OCaml
zarith                1.12        Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/coq-community/topology"
dev-repo: "git+https://github.com/coq-community/topology.git"
bug-reports: "https://github.com/coq-community/topology/issues"
license: "LGPL-2.1-or-later"
synopsis: "This library develops some basic set theory in Coq"
description: """
This Coq library develops some basic set theory.
The main purpose the author had in writing it
was as support for the Topology library.
"""
build: ["dune" "build" "-p" name "-j" jobs]
depends: [
  "dune" {>= "2.5"}
  "coq" {(>= "8.10" & < "8.16~") | (= "dev")}
]
tags: [
  "category:Mathematics/Logic/Set theory"
  "keyword:set theory"
  "keyword:cardinals"
  "keyword:ordinals"
  "keyword:finite"
  "keyword:countable"
  "keyword:quotients"
  "keyword:well-orders"
  "keyword:Zorn's lemma"
  "logpath:ZornsLemma"
]
authors: [
  "Daniel Schepler"
]
url {
  src: "https://github.com/coq-community/topology/archive/v10.0.1.tar.gz"
  checksum: "sha512=c3b76b128d318e99a149ff8a018bdddf823dc68abc43b67c68600023d095f2ed97b610063b264b85d032127300fab262b90e19d1525cccb3535036eed8eea946"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-zorns-lemma.10.0.1 coq.8.13.2

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-zorns-lemma.10.0.1 coq.8.13.2

Return code

0

Duration

24 s

Install 🚀

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-zorns-lemma.10.0.1 coq.8.13.2

Return code

0

Duration

12 s

Installation size

Total: 1 M

137 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/WellOrders.vo

95 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Filters.vo

87 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteTypes.vo

79 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteIntersections.vo

76 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Cardinals.vo

61 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/CountableTypes.vo

56 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/InverseImage.vo

55 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/ZornsLemma.vo

47 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Quotients.vo

41 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/CSB.vo

41 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Ordinals.vo

39 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/IndexedFamilies.vo

35 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsembleProduct.vo

34 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Families.vo

29 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FunctionProperties.vo

28 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/InfiniteTypes.vo

26 K ../ocaml-base-compiler.4.13.1/doc/coq-zorns-lemma/LICENSE

26 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteTypes.v

25 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Image.vo

24 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Classical_Wf.vo

24 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DirectedSets.vo

23 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Powerset_facts.vo

22 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesUtf8.vo

17 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DependentTypeChoice.vo

16 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DecidableDec.vo

16 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/WellOrders.v

14 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Cardinals.v

12 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Filters.v

11 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/ImageImplicit.vo

11 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Ordinals.v

11 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/ZornsLemma.v

9 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/InverseImage.v

9 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteIntersections.v

8 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Quotients.v

8 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/CountableTypes.v

6 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesSpec.vo

6 K ../ocaml-base-compiler.4.13.1/doc/coq-zorns-lemma/README.md

6 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/IndexedFamilies.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Classical_Wf.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Families.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/CSB.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/InfiniteTypes.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsembleProduct.v

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Relation_Definitions_Implicit.vo

4 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Powerset_facts.v

3 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Proj1SigInjective.vo

3 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesImplicit.vo

3 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesTactics.vo

3 K ../ocaml-base-compiler.4.13.1/lib/coq-zorns-lemma/dune-package

3 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FunctionProperties.v

3 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DirectedSets.v

2 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesUtf8.v

2 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteImplicit.vo

2 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Image.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesSpec.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq-zorns-lemma/opam

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Relation_Definitions_Implicit.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DecidableDec.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/DependentTypeChoice.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesImplicit.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/EnsemblesTactics.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/ImageImplicit.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/Proj1SigInjective.v

1 K ../ocaml-base-compiler.4.13.1/lib/coq/user-contrib/ZornsLemma/FiniteImplicit.v

0 K ../ocaml-base-compiler.4.13.1/lib/coq-zorns-lemma/META

Uninstall 🧹

Command

opam remove -y coq-zorns-lemma.10.0.1

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
if sed -i "/BasePathOverride/c\\\"BasePathOverride\": null," "$APPSETTINGS"; then
    echo "Updated BasePathOverride in $APPSETTINGS"
fi


text:
package com.sparkwing.localview;

import com.sparkwing.localview.Models.Photo;

import java.util.List;

/**
 * Created by zachfreeman on 9/19/15.
 */
public interface PhotoListManagerListener {
    public void photoListManagerDidFinish(List<Photo> photoList);
}


text:
[![Travis CI](https://travis-ci.org/openzipkin/zipkin-go.svg?branch=master)](https://travis-ci.org/openzipkin/zipkin-go)
[![CircleCI](https://circleci.com/gh/openzipkin/zipkin-go.svg?style=shield)](https://circleci.com/gh/openzipkin/zipkin-go)
[![Appveyor CI](https://ci.appveyor.com/api/projects/status/1d0e5k96g10ajl63/branch/master?svg=true)](https://ci.appveyor.com/project/basvanbeek/zipkin-go)
[![Coverage Status](https://img.shields.io/coveralls/github/openzipkin/zipkin-go.svg)](https://coveralls.io/github/openzipkin/zipkin-go?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/openzipkin/zipkin-go)](https://goreportcard.com/report/github.com/openzipkin/zipkin-go)
[![GoDoc](https://godoc.org/github.com/openzipkin/zipkin-go?status.svg)](https://godoc.org/github.com/openzipkin/zipkin-go)
[![Gitter chat](https://badges.gitter.im/openzipkin/zipkin.svg)](https://gitter.im/openzipkin/zipkin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Sourcegraph](https://sourcegraph.com/github.com/openzipkin/zipkin-go/-/badge.svg)](https://sourcegraph.com/github.com/openzipkin/zipkin-go?badge)

Zipkin Go is the official Go Tracer implementation for Zipkin, supported by the
OpenZipkin community.

## package organization
`zipkin-go` is built with interoperability in mind within the OpenZipkin
community and even 3rd parties, the library consists of several packages.

The main tracing implementation can be found in the root folder of this
repository. Reusable parts not considered core implementation or deemed
beneficiary for usage by others are placed in their own packages within this
repository.

### model
This library implements the Zipkin V2 Span Model which is available in the model
package. It contains a Go data model compatible with the Zipkin V2 API and can
automatically sanitize, parse and (de)serialize to and from the required JSON
representation as used by the official Zipkin V2 Collectors.

### propagation
The propagation package and B3 subpackage hold the logic for propagating
SpanContext (span identifiers and sampling flags) between services participating
in traces. Currently Zipkin B3 Propagation is supported for HTTP and GRPC.

### middleware
The middleware subpackages contain officially supported middleware handlers and
tracing wrappers.

#### http
An easy to use http.Handler middleware for tracing server side requests is
provided. This allows one to use this middleware in applications using
standard library servers as well as most available higher level frameworks. Some
frameworks will have their own instrumentation and middleware that maps better
for their ecosystem.

For HTTP client operations `NewTransport` can return a `http.RoundTripper`
implementation that can either wrap the standard http.Client's Transport or a
custom provided one and add per request tracing. Since HTTP Requests can have
one or multiple redirects it is advisable to always enclose HTTP Client calls
with a `Span` either around the `*http.Client` call level or parent function
level.

For convenience `NewClient` is provided which returns a HTTP Client which embeds
`*http.Client` and provides an `application span` around the HTTP calls when
calling the `DoWithAppSpan()` method.

#### grpc
Easy to use grpc.StatsHandler middleware are provided for tracing gRPC server and
client requests.

For a server, pass `NewServerHandler` when calling `NewServer`, e.g.,

```go
import (
	"google.golang.org/grpc"
	zipkingrpc "github.com/openzipkin/zipkin-go/middleware/grpc"
)

server = grpc.NewServer(grpc.StatsHandler(zipkingrpc.NewServerHandler(tracer)))
```

For a client, pass `NewClientHandler` when calling `Dial`, e.g.,

```go
import (
	"google.golang.org/grpc"
	zipkingrpc "github.com/openzipkin/zipkin-go/middleware/grpc"
)

conn, err = grpc.Dial(addr, grpc.WithStatsHandler(zipkingrpc.NewClientHandler(tracer)))
```

### reporter
The reporter package holds the interface which the various Reporter
implementations use. It is exported into its own package as it can be used by
3rd parties to use these Reporter packages in their own libraries for exporting
to the Zipkin ecosystem. The `zipkin-go` tracer also uses the interface to
accept 3rd party Reporter implementations.

#### HTTP Reporter
Most common Reporter type used by Zipkin users transporting Spans to the Zipkin
server using JSON over HTTP. The reporter holds a buffer and reports to the
backend asynchronously.

#### Kafka Reporter
High performance Reporter transporting Spans to the Zipkin server using a Kafka
Producer digesting JSON V2 Spans. The reporter uses the
[Sarama async producer](https://godoc.org/github.com/Shopify/sarama#AsyncProducer)
underneath.

## usage and examples
[HTTP Server Example](example_httpserver_test.go)


text:
from noaaclass import core
import re
from datetime import datetime, timedelta

select = lambda i, n, data: [d for d in data if d['id'] == i or d['name'] == n]
changed = lambda x, data: x != select(x['id'], x['name'], data)[0]
is_new = lambda e, old_data: (e['id'] is '+'
                              and not select(e['id'], e['name'], old_data))
is_removed = lambda e, data: e['id'] not in [x['id'] for x in data]
need_id = lambda e, old_data: not e['id'].isdigit() and not is_new(e, old_data)
enabled = lambda x: re.match(r'.*%22(.*)%22.*', x).group(1) == 'Y'
element = lambda t, ptrn, idx: t.select(ptrn)[idx].text
file_item = lambda row, i: element(row, 'td', i)
file_data = lambda row: (file_item(row, 3), int(file_item(row, 5)),
                         file_item(row, 4) == 'GVAR_IMG')
resume_id = lambda t: element(t, 'td a', 0)
resume_activity = (lambda t:
                   datetime.strptime(element(t, 'td', -1).split('.')[0],
                                     '%Y-%m-%d %H:%M:%S')
                   if element(t, 'td', -1) else datetime.utcnow())
resume_status = lambda t: element(t, 'td', -3).lower()
resume_size = lambda t: int(element(t, 'td', -4))
resume_order = lambda t: {
    'id': resume_id(t),
    'last_activity': resume_activity(t),
    'status': resume_status(t),
    'size': resume_size(t),
}

class api(core.api):
    def initialize(self):
        self.name = 'GVAR_IMG'
        self.name_upper = self.name.upper()
        direct = lambda x: x
        enabled_to_local = lambda x: x == 'Y'
        enabled_to_remote = lambda x: 'Y' if x else 'N'
        single = lambda x, t: t(x[0])
        multiple = lambda l, t: list(map(t, l))
        self.translate(single, 'enabled', enabled_to_local,
                       'subhead_sub_enabled', enabled_to_remote)
        self.translate(single, 'name', direct, 'subhead_sub_description', str)
        self.translate(single, 'north', float, 'nlat', str)
        self.translate(single, 'south', float, 'slat', str)
        self.translate(single, 'west', float, 'wlon', str)
        self.translate(single, 'east', float, 'elon', str)
        self.translate(multiple, 'coverage', direct, 'Coverage', direct)
        self.translate(multiple, 'schedule', direct, 'Satellite Schedule',
                       direct)
        self.translate(multiple, 'satellite', direct, 'Satellite', direct)
        self.translate(multiple, 'channel', int, 'chan_%s' % self.name, str)
        self.translate(single, 'format', direct, 'format_%s' % self.name, str)

    def subscribe_get_append_orders(self, noaa, d, append_files, hours, async):
        page = noaa.get('order_list?order=%s&type=SUBS&displayDetails=Y'
                        '&hours=%i&status_page=1&group_size=25&orderby=1' %
                        (d['id'], hours))
        d['orders'] = self.initialize_orders(page)
        self.parse_orders(noaa, d['orders'], append_files, hours, async)

    def subscribe_get(self, append_orders=False, append_files=False, hours=1,
                      async=False):
        # If append_files also automatically should append_orders.
        append_orders = append_files or append_orders
        noaa = self.conn
        page = noaa.get('subscriptions')
        data = page.select('.class_table td a')
        data = [{'id': d.text, 'enabled': enabled(d['href'])}
                for d in data if d.text.isdigit()]
        for d in data:
            noaa.get('sub_details?sub_id=%s&enabled=%s'
                     % (d['id'], 'Y' if d['enabled'] else 'N'))
            forms = noaa.translator.get_forms(noaa.last_response_soup)
            tmp = forms['sub_frm']
            noaa.post('sub_deliver', tmp, form_name='sub_frm')
            forms = noaa.translator.get_forms(noaa.last_response_soup)
            join = lambda x, y: dict(x.items() + y.items())
            tmp = join(tmp, forms['sub_frm'])
            d.update(self.post_to_local(tmp))
            if append_orders:
                self.subscribe_get_append_orders(noaa, d, append_files,
                                                 hours, async)
        return data

    def subscribe_new(self, e):
        self.conn.get('sub_details?sub_id=0&'
                      'datatype_family=%s&submit.x=40&submit.y=11' %
                      self.name_upper)
        data = self.local_to_post(e)
        self.conn.post('sub_deliver', data, form_name='sub_frm')
        channel_mask = list('000000' + 'X' * 24)
        data = self.local_to_post(e)
        for i in e['channel']:
            channel_mask[i-1] = '1'
            data['channels_%s' % self.name_upper] = ''.join(channel_mask),
        self.conn.post('sub_save', data, form_name='sub_frm')

    def subscribe_edit(self, e):
        data = self.local_to_post(e)
        self.conn.get('sub_details?sub_id=%s&enabled=%s'
                      % (e['id'], data['subhead_sub_enabled']))
        data = self.local_to_post(e)
        self.conn.post('sub_deliver', data, form_name='sub_frm')
        channel_mask = list('000000' + 'X' * 24)
        data = self.local_to_post(e)
        for i in e['channel']:
            channel_mask[i-1] = '1'
            data['channels_%s' % self.name_upper] = ''.join(channel_mask),
        self.conn.post('sub_save', data, form_name='sub_frm')

    def subscribe_remove(self, e):
        self.conn.get('sub_delete?actionbox=%s' % e['id'])

    def subscribe_classify(self, data, async):
        old_data = self.subscribe_get(append_orders=False, async=async)
        incomplete = [d for d in data if need_id(d, old_data)]
        for d in incomplete:
            d['id'] = select(d['id'], d['name'], old_data)[0]['id']
        remove = [e for e in old_data if is_removed(e, data)]
        new = [e for e in data if is_new(e, old_data)]
        edit = [e for e in data if e not in new and changed(e, old_data)]
        return remove, new, edit

    def subscribe_set(self, data, append_orders=False, async=False):
        remove, new, edit = self.subscribe_classify(data, async)
        list(map(self.subscribe_new, new))
        list(map(self.subscribe_edit, edit))
        list(map(self.subscribe_remove, remove))

    def parse_area(self, head, order):
        coords = ['south', 'north', 'west', 'east']
        cast = lambda n, v: self.keys['get'][self.keys['set'][n][0]][1](v)
        for index in range(len(coords)):
            name = coords[index]
            value = head[8+index].text
            order[name] = cast(name, value) / 100

    def obtain_items(self, last_response_soup, item_functor, check_functor):
        anchors = last_response_soup.select('.zebra td a')
        return map(item_functor, filter(check_functor, anchors))

    def parse_head(self, noaa, order, last_response_soup):
        url = last_response_soup.select('.zebra td a')[0].attrs['href']
        last_response_soup = noaa.get(url)
        head = last_response_soup.select('.class_table td')
        self.parse_area(head, order)
        other = {
            'format': head[1].text,
            'channel': range(int(head[12].text), int(head[13].text)+1),
        }
        order.update(other)

    def parse_order(self, noaa, order, last_response_soup, append_files):
        table = last_response_soup.select('.class_table td')
        order['datetime'] = datetime.strptime(table[3].text,
                                              '%Y-%m-%d %H:%M:%S')
        order['files'] = {'http': [], 'ftp': []}
        day_before_yesterday = datetime.utcnow() - timedelta(days=2)
        order['old'] = order['datetime'] < day_before_yesterday
        self.parse_head(noaa, order, last_response_soup)
        if append_files:
            item = lambda i: i['href'].split("'")[1]
            is_http = lambda i: 'www' in i.text
            is_ftp = lambda i: 'ftp' in i.text
            order['files']['http'].extend(
                self.obtain_items(last_response_soup, item, is_http))
            order['files']['ftp'].extend(
                self.obtain_items(last_response_soup, item, is_ftp))

    def parse_orders(self, noaa, orders, append_files, hours, async):
        urls = [('order_details?order=%s&hours=%i&status_page=1'
                 '&group_size=1000&orderby=1' % (order['id'], hours))
                for order in orders]
        responses = noaa.getmultiple(urls, async=async)
        list(map(lambda a, noaa=noaa, append_files=append_files:
                 self.parse_order(noaa, a[0], a[1], append_files),
                 zip(orders, responses)))

    def initialize_orders(self, page):
        # Filter old or unused data
        data = page.select('.zebra tr')
        data = filter(lambda t: len(t.select('td')) > 0, data)
        return filter(lambda o: o['status'] != 'delivered',
                      map(resume_order, data))

    def request_get(self, append_files=False, hours=1, async=False):
        noaa = self.conn
        page = noaa.get('order_list?order=&status=&type=USER'
                        '&displayDetails=N&hours=%i&status_page=1'
                        '&large_status=&group_size=1000&orderby=1' %
                        (hours))
        orders = self.initialize_orders(page)
        self.parse_orders(noaa, orders, append_files, hours, async)
        key = lambda x: str(x['id'])
        orders.sort(key=key)
        return orders

    def request_new(self, e):
        noaa = self.conn
        noaa.get('search?sub_id=0&datatype_family=%s&submit.x=23&submit.y=7' %
                 self.name_upper)
        data = self.local_to_post(e)
        data['start_date'] = e['start'].strftime('%Y-%m-%d')
        data['start_time'] = e['start'].strftime('%H:%M:%S')
        data['end_date'] = e['end'].strftime('%Y-%m-%d')
        data['end_time'] = e['end'].strftime('%H:%M:%S')
        data['data_start'] = '1993-09-01'
        data['data_end'] = datetime.utcnow().strftime('%Y-%m-%d')
        data['dsname_pattern'] = "^GOES\d\d\.(19|20)\d\d\.[0123]\d\d(.{0,15})$"
        data['between_through'] = 'T'
        noaa.post('psearch%s' % self.name_upper, data=data,
                  form_name='search_frm')
        # It iterate over the pages to select the items of each page.
        page = 0
        lapse = timedelta(hours=0)
        while e['start'] + lapse <= e['end']:
            forms = noaa.translator.get_forms(noaa.last_response_soup)
            tab = e['start'] + lapse
            tmp = forms['rform']
            tmp['update_action'] = 'GotoInterval'
            tmp['GotoInterval'] = tab.strftime('%Y-%m-%d %H:%M:%S.000')
            tmp['page'] = page
            noaa.post('results%s' % self.name, data=tmp, form_name='rform')
            forms = noaa.translator.get_forms(noaa.last_response_soup)
            tmp = forms['rform']
            tmp['update_action'] = 'Select Page'
            tmp['GotoInterval'] = tab.strftime('%Y-%m-%d %H:%M:%S.000')
            tmp['page'] = page
            noaa.post('results%s' % self.name, data=tmp, form_name='rform')
            page += 1
            lapse += timedelta(hours=6)
        forms = noaa.translator.get_forms(noaa.last_response_soup)
        tmp = forms['rform']
        forms = noaa.translator.get_forms(noaa.last_response_soup)
        noaa.get('shopping_cart')
        forms = noaa.translator.get_forms(noaa.last_response_soup)
        tmp = forms['shop']
        trans = (lambda k, v, e: [e['format']]
                 if 'format' in k else (e['channel'] if 'channel' in k else v))
        tmp = {k: trans(k, v, e) for k, v in tmp.items()}
        tmp['cocoon-action'] = ['PlaceOrder']
        self.conn.post('shop', data=tmp, form_name='shop')
        forms = noaa.translator.get_forms(noaa.last_response_soup)
        tmp = forms['FORM1']
        tmp['purpose'] = ['education']
        tmp['postSurvey'] = ['Submit']
        self.conn.post('survey', data=tmp, form_name='FORM1')

    def request_set(self, data, async=False):
        new = [e for e in data if e['id'] is '+']
        list(map(self.request_new, new))


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.

/******************************************************************************
 * This file is auto-generated from a template file by the GenerateTests.csx  *
 * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make    *
 * changes, please update the corresponding template and run according to the *
 * directions listed in the file.                                             *
 ******************************************************************************/

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;

namespace JIT.HardwareIntrinsics.General
{
    public static partial class Program
    {
        private static void CreateVectorUInt16()
        {
            var test = new VectorCreate__CreateVectorUInt16();

            // Validates basic functionality works
            test.RunBasicScenario();

            // Validates calling via reflection works
            test.RunReflectionScenario();

            if (!test.Succeeded)
            {
                throw new Exception("One or more scenarios did not complete as expected.");
            }
        }
    }

    public sealed unsafe class VectorCreate__CreateVectorUInt16
    {
        private static readonly int LargestVectorSize = 32;

        private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);

        public bool Succeeded { get; set; } = true;

        public void RunBasicScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));

            UInt16 lowerValue = TestLibrary.Generator.GetUInt16();
            Vector128<UInt16> lower = Vector128.Create(lowerValue);

            UInt16 upperValue = TestLibrary.Generator.GetUInt16();
            Vector128<UInt16> upper = Vector128.Create(upperValue);

            Vector256<UInt16> result = Vector256.Create(lower, upper);

            ValidateResult(result, lowerValue, upperValue);
        }

        public void RunReflectionScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));

            UInt16 lowerValue = TestLibrary.Generator.GetUInt16();
            Vector128<UInt16> lower = Vector128.Create(lowerValue);

            UInt16 upperValue = TestLibrary.Generator.GetUInt16();
            Vector128<UInt16> upper = Vector128.Create(upperValue);

            object result = typeof(Vector256)
                                .GetMethod(nameof(Vector256.Create), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
                                .Invoke(null, new object[] { lower, upper });

            ValidateResult((Vector256<UInt16>)(result), lowerValue, upperValue);
        }

        private void ValidateResult(Vector256<UInt16> result, UInt16 expectedLowerValue, UInt16 expectedUpperValue, [CallerMemberName] string method = "")
        {
            UInt16[] resultElements = new UInt16[ElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
            ValidateResult(resultElements, expectedLowerValue, expectedUpperValue, method);
        }

        private void ValidateResult(UInt16[] resultElements, UInt16 expectedLowerValue, UInt16 expectedUpperValue, [CallerMemberName] string method = "")
        {
            bool succeeded = true;

            for (var i = 0; i < ElementCount / 2; i++)
            {
                if (resultElements[i] != expectedLowerValue)
                {
                    succeeded = false;
                    break;
                }
            }

            for (var i = ElementCount / 2; i < ElementCount; i++)
            {
                if (resultElements[i] != expectedUpperValue)
                {
                    succeeded = false;
                    break;
                }
            }

            if (!succeeded)
            {
                TestLibrary.TestFramework.LogInformation($"Vector256.Create(UInt16): {method} failed:");
                TestLibrary.TestFramework.LogInformation($"   lower: {expectedLowerValue}");
                TestLibrary.TestFramework.LogInformation($"   upper: {expectedUpperValue}");
                TestLibrary.TestFramework.LogInformation($"  result: ({string.Join(", ", resultElements)})");
                TestLibrary.TestFramework.LogInformation(string.Empty);

                Succeeded = false;
            }
        }
    }
}


text:
require "pastel"
require "tty-file"
require "tty-prompt"
require "tty-spinner"
require "tty-table"
require "pry"

# This code is mostly procedural, with a helper class (ConversionTarget) thrown in.

# ConversionTarget represents a single file to be converted to Prometheus metrics
class ConversionTarget

  attr_accessor :full_path, :top_level_directory, :edited,
                :variables_in_metrics_names, :decrements_found,
                :unknown_pattern, :first_def_string, :usage_map

  def initialize(path, parent)
    @full_path                  = path
    @top_level_directory        = parent
    @edited                     = false
    @variables_in_metrics_names = false
    @decrements_found           = false
    @unknown_pattern            = false
    @first_def_string           = nil
    @usage_map                  = {}
    # usage_map[usage_key] -> usage_entry[line_number] -> [indent, line]
    #   usage_key is one of METRICS_USAGE below
    #   line_number is self explanatory
    #   indent is the number of spaces/whitespace at the start of the line
    #   line is the actual line of code found
    #   example:
    #     <ConversionTarget:0x00007fe6100a7ca8
    #       @full_path = "/opt/code/platform/web/lib/pegasus/adwords/client.rb",
    #       @top_level_directory = "/opt/code/platform/web/lib",
    #       @edited = false,
    #       @usage_map = {
    #         "metrics.increment" => {
    #           430=>[6, "metrics.increment('adwords/cache_hit')"],
    #           433=>[8, "metrics.increment('adwords/cache_miss')"]
    #         },
    #         "metrics.timer(" => {
    #           435=>[6, "metrics.timer('adwords/google_api') do"]
    #         }
    #       }
    #     >
  end

  def add_usage(usage_key, line_number, indent, line)
    @usage_map[usage_key] = {} unless @usage_map.has_key?(usage_key)
    @usage_map[usage_key][line_number] = {} unless @usage_map[usage_key].has_key?(line_number)
    @usage_map[usage_key][line_number] = [indent, line.strip]
  end

  def select_by_usage_key(usage_key)
    usage_map.select { |k, _| k == usage_key }
  end

  def usage_counters
    select_by_usage_key("metrics.count(").merge(select_by_usage_key("metrics.counter("))
  end

  def usage_increments
    select_by_usage_key("metrics.increment")
  end

  def usage_gauges
    select_by_usage_key("metrics.gauge(")
  end

  def usage_decrements
    select_by_usage_key("metrics.decrement")
  end

  def usage_sets
    select_by_usage_key("metrics.set")
  end

  def usage_timers
    select_by_usage_key("metrics.time(").merge(select_by_usage_key("metrics.timer("))
  end

  def usage_includes
    select_by_usage_key("include Invoca::Metrics::Source\n")
  end
end

METRICS_USAGE = [ "metrics.count(",
                  "metrics.counter(",
                  "metrics.gauge(",
                  "metrics.increment",
                  "metrics.decrement",
                  "metrics.time(",
                  "metrics.timer(",
                  "metrics.set",
                  "include Invoca::Metrics::Source\n"
]

TOP_LEVEL_COMMANDS = [
  { key: "c", name: "Clear Screen",            value: :clear_screen },
  { key: "d", name: "Choose Directory",        value: :find_with_directory },
  { key: "e", name: "Edit/Show Configuration", value: :edit_config },
  { key: "w", name: "Write Report",            value: :write_report },
  { key: "q", name: "Quit",                    value: :quit },
]

REJECT_DIRS = [ ".", "..",
                ".buildkite",
                ".bundle",
                ".dependabot",
                ".git",
                ".github",
                ".invoca",
                "bin",
                "log",
                "node_modules",
                "public",
                "tmp",
                "vendor"
]

TODO_STRING = "# TODO-PROMETHEUS "

def clear_screen
  if Gem.win_platform?
    system("cls")
  else
    system("clear")
  end
end

# Ask the user to enter a 'root' directory to start looking for metrics usage.
def enter_directory
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { return :return_to_menu }

  puts Pastel.new.blue("\nHit esc to return to previous menu.\n")

  dir = prompt.ask("Please enter the directory (with full path, sorry no completion):")
  while !dir or !Dir.exist?(dir)
    if prompt.select("Sorry, we couldn't find directory '#{dir}'. Try again?", ["Yes", "No"]) == "No"
      return :return_to_menu
    else
      dir = prompt.ask("Please enter the directory (with full path):")
    end
  end

  dir
end

# Given a directory to start from, find the set of direct child directories, except for
# those in REJECT_DIRS. For example, given:
#
# $ pwd
# /opt/code/lib/invoca-metrics
#
# get these directories:
#
# ├── gemfiles
# ├── lib
# └── spec
def select_directories(supplied_directory = ".")
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { return [:return_to_menu] }

  choices = {}

  spinner = TTY::Spinner.new("[:spinner] Fetching directory size...", format: :dots_5)
  spinner.auto_spin

  supplied_directory_size = `du -sh "#{supplied_directory}" | awk '{print $1}'`.strip

  spinner.stop

  if supplied_directory_size.end_with?("G")
    message = Pastel.new.red("#{supplied_directory} is big: #{supplied_directory_size}. Do you want to proceed?")
    if !prompt.yes?(message)
      return choices
    end
  end

  directories = Dir.entries(supplied_directory).reject { |e| !File.directory?("#{supplied_directory}/#{e}") || REJECT_DIRS.include?(e) }

  spinner = TTY::Spinner.new("[:spinner] Fetching directories and sizes...", format: :dots_5)
  spinner.auto_spin

  directories.sort.each do |d|
    label = "#{d} (" + `du -sh "#{supplied_directory}/#{d}" | awk '{print $1}'`.strip + ")"
    choices[label] = "#{supplied_directory}/#{d}"
  end

  spinner.stop

  puts Pastel.new.blue("\nNote that large directories may take a while to process.\n")
  puts Pastel.new.blue("Hit enter with no selections to return.\n")
  puts Pastel.new.blue("Ctrl-A to select all.\n")
  puts Pastel.new.blue("Ctrl-R to reverse current selection.\n")

  prompt.multi_select("", choices, cycle: true, echo: false, per_page: 20)
end

# This looks for all ruby files under the supplied directory, and scans each file
# for any of the patterns in METRICS_USAGE; any usage found results in creating
# a ConversionTarget object with which pattern it was, the line number, and the
# line of code found. It creates and returns an array of ConversionTargets.
def find_metrics_usage(supplied_directory = ".", targets)
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { return :return_to_menu }

  puts Pastel.new.blue("\nHit esc to return to previous menu.\n")

  directories_to_files   = {}

  directories = select_directories(supplied_directory)

  # This is a little unwieldy but it's nice to be able to return to the menu without having
  # to do anything
  return :no_dir         if directories.empty?
  return :return_to_menu if directories[0] == :return_to_menu

  directories.sort.each do |k|
    directories_to_files[k] = {}
    directories_to_files[k] = Dir.glob(File.join("#{k}", "**", "*.rb"))
  end

  # directories_to_files is now a hash of directory name -> array of file names, e.g.:
  #   directories_to_files["app"] -> ["app/controllers/controller_one.rb", ..., "app/models/model_bar.rb"]

  spinner = TTY::Spinner.new("[:spinner] Finding metrics usage...", format: :dots_5)
  spinner.auto_spin

  directories_to_files.keys.sort.each do |dir|
    directories_to_files[dir].each do |file|
      c = ConversionTarget.new(file, dir)
      yep_found_one = false
      METRICS_USAGE.each do |m|
        File.foreach(file).each_with_index do |line, number|
          if line.include?("def ") && c.first_def_string.nil?
            c.first_def_string = line
          end
          if line.include?(m)
            indent = line.index("metrics") # this naively assumes metrics... appears first
            if m == "include Invoca::Metrics::Source\n"
              indent = line.index("include")
            end
            c.add_usage(m, number + 1, indent, line)
            yep_found_one = true
          end
        end
      end
      targets << c if yep_found_one
    end
  end

  spinner.stop

  targets.uniq
end

# Overwrite values in the configuration hash.
def edit_config_option(config, option, option_type)
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { || return }

  puts Pastel.new.blue("\nHit esc to return to previous menu.\n")

  puts "Current value for #{option}: #{config[option]}"
  value = prompt.ask("Please enter the new value")

  if !value
    puts "No value entered"
    return
  end

  case option_type
  when :bool
    config[option] = value == "true"
  when :string
    config[option] = value
  end
  puts "Changed #{option} to #{config[option]}"
  sleep 2
end

def parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: false)
  if parse_unique
    graphite_string.gsub(".", "_")
  else
    tokens = graphite_string.strip.gsub(/[\s'"]/, "").split(".")
    return tokens[0], tokens[1..].each_with_object({}) { |key, hash| hash[key.to_sym] = true }
  end
end

def parse_metric_names_values(metric_string, metric_type)
  case metric_type
  when :counter
    graphite_string = /metrics\.(?:increment|count|counter)\((.*)\)/.match(metric_string)[1].split(",").first
    metric_name     = graphite_string.split(".").first
    metric_value    = if metric_string.include?(",")
                        /metrics\.(?:increment|count|counter)\(.*,(.*)\)/.match(metric_string)[1]
                      else
                        1
                      end
  when :gauge
    graphite_string = /metrics\.(?:gauge|set)\((.*),/.match(metric_string)[1].split(",").first
    metric_name     = graphite_string.split(".").first
    metric_value    = /,(.*)\)/.match(metric_string)[1]
  when :timer
    graphite_string = /metrics\.timer\((.*)\)/.match(metric_string)[1].split(",").first
    metric_name     = graphite_string.split(".").first
    metric_value    = if metric_string.include?(",")
                        /metrics\.timer\(.*,(.*)\)/.match(metric_string)[1].gsub(/[\s'"]/, "")
                      else
                        1
                      end
  end

  return metric_name, metric_value, graphite_string
end

def unclear_usage?(metric_string, metric_type)
  return true if metric_string.include?("\#\{")         ||
                 !metric_string.start_with?("metrics.") ||
                 !metric_string.end_with?(")")

  case metric_type
  when :counter
    !/(count|counter|increment)\((\'|\")/.match(metric_string)
  when :gauge
    !/(gauge|set)\((\'|\")/.match(metric_string)
  when :timer
    !/timer\((\'|\")/.match(metric_string)
  end
end

def cannot_consume_reasons(metric_string, metric_type, config)
  reasons = []

  if config[:punt_on_slash]
    if metric_string.include?("/")
      reasons << "Forward slash in metric string"
    end
  end

  if config[:punt_on_comma]
    if /\".*,.*\"/.match(metric_string)
      reasons << "Comma in metric string"
    end
  end

  if config[:punt_on_variables]
    if metric_string.include?("\#\{")
      reasons << "Variable in metric string"
    end
  end

  if config[:punt_on_start_with_metrics]
    if !metric_string.start_with?("metrics")
      reasons << "Does not start with metrics"
    end
  end

  if config[:punt_on_end_with_paren]
    if !metric_string.end_with?(")")
      reasons << "Does not end with )"
    end
  end

  case metric_type
  when :counter
    if !metric_string.include?("count\(")     &&
       !metric_string.include?("counter\(")   &&
       !metric_string.include?("increment\(")
      reasons << "Counter did not start with count, counter, or increment"
    end
  when :gauge
    if !metric_string.include?("gauge\(") &&
       !metric_string.include?("set\(")
      reasons << "Gauge did not start with gauge or set"
    end
  when :timer
    if !metric_string.include?("timer\(")
      reasons << "Timer did not start with timer"
    end
  end

  reasons
end

def convert_counters(target, counter_map, config, declare_metrics_block)
  counter_map.keys.sort.each do |line_number|
    indents = " " * counter_map[line_number][0]

    reasons = cannot_consume_reasons(counter_map[line_number][1], :counter, config)
    if !reasons.empty?
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually (#{reasons.join(', ')})\n",
                                 after: "#{counter_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      declare_metrics_block << ["counter (convert manually): #{counter_map[line_number][1]}", :commented, :unknown]
      next
    end

    metric_name, metric_value, graphite_string = parse_metric_names_values(counter_map[line_number][1], :counter)
    name      = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: true)
    _, labels = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: false)

    # Unknown pattern; could involve logic, variable interpolation, function calls, ...
    if unclear_usage?(counter_map[line_number][1], :counter)
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually\n",
                                 after: "#{counter_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      target.unknown_pattern = true
      declare_metrics_block << ["counter (convert manually): #{counter_map[line_number][1]}", :commented, :unknown]
      next
    end

    prefix = TODO_STRING if config[:comment_prometheus_metrics]

    increment_zero_message = "# Note that increment(0) can be removed after the full conversion to Prometheus is complete"

    if metric_value.to_i == 1
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.increment"
    elsif metric_value.strip == "0"
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.increment(0) #{increment_zero_message}"
    else
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.increment(#{metric_value.strip}"
      if config[:parse_to_unique_metrics]
        prom_metrics_string += ")"
      else
        prom_metrics_string += if !labels.empty? && config[:write_parsed_labels]
                                 ", #{labels.map { |k, v| "#{k}: true" }.join(", ")})"
                               else
                                 ")"
                               end
      end
    end

    TTY::File.replace_in_file(target.full_path, Regexp.new(Regexp.escape(counter_map[line_number][1])),
                              prom_metrics_string, verbose: config[:verbose_tty])
    target.edited = true
    declare_metrics_block << ["counter #{name}", :uncommented, labels, graphite_string]
  end
end

def convert_gauges(target, gauge_map, config, declare_metrics_block)
  gauge_map.keys.sort.each do |line_number|
    next if target.full_path.split("/").last == "billing_controller_test.rb"

    indents = " " * gauge_map[line_number][0]

    reasons = cannot_consume_reasons(gauge_map[line_number][1], :gauge, config)
    if !reasons.empty?
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually (#{reasons.join(', ')})\n",
                                 after: "#{gauge_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      declare_metrics_block << ["gauge (convert manually): #{gauge_map[line_number][1]}", :commented, :unknown]
      next
    end

    metric_name, metric_value, graphite_string = parse_metric_names_values(gauge_map[line_number][1], :gauge)
    name      = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: true)
    _, labels = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: false)

    # Unknown pattern; could involve logic, variable interpolation, function calls, ...
    if unclear_usage?(gauge_map[line_number][1], :gauge)
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually\n",
                                 after: "#{gauge_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      target.edited = true
      declare_metrics_block << ["gauge (convert manually): #{gauge_map[line_number][1]}", :commented, :unknown]
      next
    end

    prefix = TODO_STRING if config[:comment_prometheus_metrics]

    if metric_value.to_i == 1
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.set"
    else
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.set(#{metric_value.strip}"
      if config[:parse_to_unique_metrics]
        prom_metrics_string += ")"
      else
        prom_metrics_string += if !labels.empty? && config[:write_parsed_labels]
                                 ", #{labels.map { |k, v| "#{k}: true" }.join(", ")})"
                               else
                                 ")"
                               end
      end
    end

    TTY::File.replace_in_file(target.full_path, Regexp.new(Regexp.escape(gauge_map[line_number][1])),
                              prom_metrics_string, verbose: config[:verbose_tty])
    target.edited = true
    declare_metrics_block << ["gauge #{name.gsub(/[\s'"]/, "")}", :uncommented, labels, graphite_string]
  end
end

def convert_timers(target, timer_map, config, declare_metrics_block)
  timer_map.keys.sort.each do |line_number|
    indents = " " * timer_map[line_number][0]

    reasons = cannot_consume_reasons(timer_map[line_number][1], :timer, config)
    if !reasons.empty?
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually (#{reasons.join(', ')})\n",
                                 after: "#{timer_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      declare_metrics_block << ["histogram (convert manually): #{timer_map[line_number][1]}", :commented, :unknown]
      next
    end

    metric_name, metric_value, graphite_string = parse_metric_names_values(timer_map[line_number][1], :timer)
    name      = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: true)
    _, labels = parse_name_and_labels_from_graphite_string(graphite_string, parse_unique: false)

    # Unknown pattern; could involve logic, variable interpolation, function calls, ...
    if unclear_usage?(timer_map[line_number][1], :timer)
      TTY::File.inject_into_file(target.full_path,
                                 indents + "#{TODO_STRING}Please convert the above line manually\n",
                                 after: "#{timer_map[line_number][1]}\n",
                                 verbose: config[:verbose_tty])

      target.unknown_pattern = true
      declare_metrics_block << ["histogram (convert manually): #{timer_map[line_number][1]}", :commented, :unknown]
      next
    end

    prefix = TODO_STRING if config[:comment_prometheus_metrics]

    if metric_value.to_i == 1
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.add"
    else
      prom_metrics_string = "#{prefix}prometheus_metrics.#{name.gsub(/[\s'"]/, "")}.add(#{metric_value.strip}"
      if config[:parse_to_unique_metrics]
        prom_metrics_string += ")"
      else
        prom_metrics_string += if !labels.empty? && config[:write_parsed_labels]
                                 ", #{labels.map { |k, v| "#{k}: true" }.join(", ")})"
                               else
                                 ")"
                               end
      end
    end

    TTY::File.replace_in_file(target.full_path, Regexp.new(Regexp.escape(timer_map[line_number][1])),
                              prom_metrics_string, verbose: config[:verbose_tty])
    target.edited = true
    declare_metrics_block << ["histogram #{name}", :uncommented, labels, graphite_string]
  end
end

# The ideal place to write out the declare_metrics block is the line after
# 'include Invoca::Metrics::Source'; however, that doesn't always appear in a
# file, because it may be a class inheriting or mixing in from somewhere that
# already includes it.  If it's there we add the declare_metrics block after
# it; otherwise we look for the first method definition ('def ...') and put
# it right above that.
#
# This strategy does have some pitfalls though - for example, the first def might
# occur in a module or class defined inside the (module or class), before any
# other def occurs.
def add_declare_metrics_block(target, declare_metrics_block, config, includes)

  if includes.empty? and target.first_def_string.nil?
    puts "File #{target.full_path} has no includes and no identified 'def ...'; skipping declare_metrics block."
    return
  end

  if !includes.empty?
    # For any file, there should only be one case of include Invoca::Metrics::Source
    # usage looks like {16=>[4, "include Invoca::Metrics::Source"]}
    usage = includes[includes.keys.first]

    line_number = usage.keys.first
    indents     = " " * usage[line_number][0]
  else
    indents = " " * target.first_def_string.index("def ")
  end

  block = "\n" + indents + "declare_metrics do\n"

  declare_metrics_block.each do |dmb|

    # this has got rather unwieldy.  i'm making it
    # less stylish so that it's at least a bit readable.
    #
    # if we've flagged this declare_metrics block item as unknown,
    # paste the original metric found into the declare_metrics block,
    # commented out
    if dmb.include?(:unknown)
      block += indents + "  # #{dmb[0]}\n"
    else
      # write out default empty labels and/or graphite string
      if config[:write_empty_labels]
        suffix = "labels: {}, graphite: \"\""
      else
        suffix = "graphite: \"\""
      end

      if dmb.size > 2 && dmb[2] != nil
        if !dmb[2].empty?
          if config[:write_parsed_labels]
           suffix = "labels: { #{dmb[2].map { |k, v| "#{k}" }.join(", ")} }, graphite: #{dmb[3]}"
          elsif config[:write_empty_labels]
           suffix = "labels: {}, graphite: #{dmb[3]}"
          else
           suffix = "graphite: #{dmb[3]}"
          end
        else
          if config[:write_empty_labels]
           suffix = "labels: {}, graphite: #{dmb[3]}"
          else
           suffix = "graphite: #{dmb[3]}"
          end
        end
      end

      metric_type, metric_name = dmb[0].split
      block += if dmb[1] == :uncommented
                 indents + "  #{metric_type} :#{metric_name.gsub(".", "_").gsub('"', '')}, #{suffix}\n"
               else
                 indents + "  # #{metric_type} :#{metric_name.gsub(".", "_").gsub('"', '')}, #{suffix}\n"
               end
    end
  end

  block += indents + "end\n"

  if !includes.empty?
    TTY::File.inject_into_file(target.full_path,
                               block,
                               after: includes.keys.first,
                               verbose: config[:verbose_tty])
  else
    TTY::File.inject_into_file(target.full_path,
                               block + "\n",
                               before: target.first_def_string,
                               verbose: config[:verbose_tty])
  end

end

# statsd -> prometheus metric type conversion heuristic:
# 1. statsd counters and statsd increments are prometheus counters
# 2. statsd gauges and sets are prometheus gauges
# 3. statsd timers are prometheus histograms
#
# It turns out that at the time of writing the only place decrement
# shows up across our codebases is here in invoca-metrics, in tests.
# (If it were actually used it might have meant that decrements and
# any 'matching' increments were being used as prometheus gauges
# rather than monotonically increasing counters.)
#
# We need to do two things:
# 1. Replace each statsd metrics call with the corresponding prometheus metrics call
# (leaving the original commented out if configured that way)
# 2. Write out the declare_metrics block
#
# We need to pay attention to whether variables are used in the metric names.
# In that case we can't statically create the declare_metrics block, because
# we don't know a priori what the values of the variables will be.  We could
# register the metrics in each instance (say, immediately above the call that
# uses a variable), but at this time I'm punting on that and leaving a comment
# in the code because it seems kind of fraught. For example, if the metrics call
# happens in a tight loop, or just a lot of times, that would register the metric
# each time before calling it, which maybe isn't a problem but seems bad to me.
#
# We also need to pay attention to whether we think metrics calls are taking place
# inside of some logic; we are calling that an "unknown metrics pattern", and
# as with variable usage we are punting and telling the user it should be
# converted manually.
def convert_file(target, config)
  counters   = target.usage_counters
  decrements = target.usage_decrements
  gauges     = target.usage_gauges
  increments = target.usage_increments
  sets       = target.usage_sets
  timers     = target.usage_timers
  includes   = target.usage_includes

  if !decrements.empty?
    target.decrements_found = true
    decrement_message = "statsd decrement calls were found in #{target.full_path}, which is unusual."
    decrement_message += "\nYou should probably convert it manually."
    puts Pastel.new.red(decrement_message)
  end

  counter_map   = {}

  # there might be count( and counter(, so collect them both; we're processing a single
  # file so there won't/can't be line number collisions
  counters.keys.each { |k| counter_map.merge!(counters[k]) }

  # add increment( to counters
  increments.keys.each { |k| counter_map.merge!(increments[k]) }

  # counter_map will now look something like this:
  # { 18=>[6, "metrics.count(\"\#{metric}.success\", 0)"],
  #   19=>[6, "metrics.count(\"\#{metric}.failure\", 0)"],
  #   20=>[4, "metrics.counter(\"\#{metric}.success\", 0)"],
  #   11=>[6, "metrics.increment(\"\#{metric}.success\")"],
  #   14=>[6, "metrics.increment(\"\#{metric}.failure\")"] }
  # that's a hash of line_num -> [indent, metric]

  declare_metrics_block = []

  convert_counters(target, counter_map, config, declare_metrics_block) unless counter_map.empty?

  gauge_map = {}
  gauges.keys.each { |k| gauge_map.merge!(gauges[k]) }
  sets.keys.each { |k| gauge_map.merge!(sets[k]) }
  convert_gauges(target, gauge_map, config, declare_metrics_block) unless gauge_map.empty?

  timer_map = {}
  timers.keys.each { |k| timer_map.merge!(timers[k]) }
  convert_timers(target, timer_map, config, declare_metrics_block) unless timer_map.empty?

  if !declare_metrics_block.empty? && config[:write_declare_metrics_block]
    add_declare_metrics_block(target, declare_metrics_block.uniq, config, includes)
  end
end

def select_files(targets, config)
  prompt = TTY::Prompt.new

  targets_with_usage = {}
  targets_with_usage[Pastel.new.blue("<< Return to menu >>")] = :return
  targets_with_usage[Pastel.new.blue("<< Convert all >>")] = :convert_all
  targets.each do |t|
    usage = ""
    t.usage_map.keys.each { |k| usage += "\n\tFound '#{k.tr('(', '').tr(')', '')}' #{t.usage_map[k].count} #{t.usage_map[k].count == 1 ? 'time' : 'times'}" }
    targets_with_usage["In #{t.full_path} #{usage}"] = t.full_path
  end

  loop do
    message = Pastel.new.bright_white("#{targets_with_usage.size - 2}") + " files were found with metrics usage.\nChoose a file (15 per page, paginated)\n"
    file_name = prompt.select(message, targets_with_usage, cycle: true, echo: false, per_page: 15)

    if file_name == :return
      return
    end

    if file_name == :convert_all
      targets.each do |target|
        puts Pastel.new.blue("Converting #{target.full_path}")
        convert_file(target, config)
      end

      puts Pastel.new.green("Selected files converted.")
      return
    end

    target = targets.select { |t| t.full_path == file_name }.first
    puts
    puts "#{file_name} has the following metrics usage:"

    target.usage_map.keys.each do |k|
      puts
      puts "  Pattern: #{k.tr(')', '').tr('(', '')}"
      target.usage_map[k].keys.each do |line_number|
        puts "    On line #{line_number}: \"#{target.usage_map[k][line_number][1]}\""
      end
    end

    puts
    if prompt.yes?("Convert #{file_name}?")
      convert_file(target, config)
    end
  end
end

def default_config
  configuration = {}

  configuration[:parse_to_unique_metrics]       = false

  configuration[:comment_prometheus_metrics]    = false

  configuration[:write_declare_metrics_block]   = true

  configuration[:write_parsed_labels]           = false
  configuration[:write_empty_labels]            = true

  configuration[:report_name]                   = "metrics_usage"
  configuration[:write_report]                  = true

  configuration[:verbose_tty]                   = false

  configuration[:punt_on_variables]             = false
  configuration[:punt_on_comma]                 = false
  configuration[:punt_on_start_with_metrics]    = false
  configuration[:punt_on_slash]                 = true
  configuration[:punt_on_end_with_paren]        = true

  configuration
end

def print_config(config)
  table = TTY::Table.new(header: ["Config Option", "Current Value", "Description"])

  table << ["Parse statsd Strings to Unique Metrics", config[:parse_to_unique_metrics], "Parse metrics into names instead of names + labels"]

  table << ["Comment prometheus_metrics.*", config[:comment_prometheus_metrics], "Comment out added prometheus_metrics.* code"]

  table << ["Write Declare Metrics Block", config[:write_declare_metrics_block], "Whether or not to write out declare_metrics block"]

  table << ["Write Parsed Labels", config[:write_parsed_labels], "Whether or not to write labels from graphite string into declare_metrics block and prometheus_metrics calls"]
  table << ["Write Empty Labels", config[:write_empty_labels], "Whether or not to write empty labels into the declare_metrics block if there aren't any"]

  table << ["Report Name", config[:report_name] + "-(generated timestamp)", "The name of the report file to write"]
  table << ["Write Report", config[:write_report], "Write out a report after conversion"]

  table << ["Verbose TTY", config[:verbose_tty], "Whether to print all replace and inject TTY::File actions"]

  table << ["Punt On Variables", config[:punt_on_variables], "Don't try to process metrics with a variable in the metrics string"]
  table << ["Punt On Commas", config[:punt_on_comma], "Don't try to process metrics with a comma in the metrics string"]
  table << ["Punt On Not Start With 'metrics'", config[:punt_on_start_with_metrics], "Don't try to process metrics if the metrics string doesn't start with metrics"]
  table << ["Punt On Slash", config[:punt_on_slash], "Don't try to process metrics with a slash in the metrics string"]
  table << ["Punt On Not End With Paren", config[:punt_on_slash], "Don't try to process metrics if the metrics string doesn't end with a paren"]

  table.render(:unicode, multiline: true) { |renderer| renderer.border.separator = :each_row }
end

# This "report" is very bare bones. It could be augmented to include every metrics usage line found.
def write_report(targets, config)
  report_name = "#{config[:report_name]}-#{Time.now.strftime("%Y-%m-%d-%H:%M:%S")}"
  f = File.new(report_name, "w")

  config.keys.each { |k| f.write("#{k}: #{config[k]}\n") }

  f.write("\n")

  targets.each do |t|
    f.write("#{t.full_path}\n\tEdited: #{t.edited}\n\tVariables in metric names: #{t.variables_in_metrics_names}\n\tDecrements found: #{t.decrements_found}\n\tUnknown patterns: #{t.unknown_pattern}\n")

    if usage = t.usage_counters.values.first
      f.write("\tCounter metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end

    if usage = t.usage_decrements.values.first
      f.write("\tDecrement metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end

    if usage = t.usage_increments.values.first
      f.write("\tIncrement metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end

    if usage = t.usage_sets.values.first
      f.write("\tSet metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end

    if usage = t.usage_timers.values.first
      f.write("\tTimer metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end

    if usage = t.usage_gauges.values.first
      f.write("\tGauge metrics usage found:\n")
      usage.keys.each { |k| f.write("\t\tLine number #{k}: #{usage[k][1]}\n") }
    end
  end
  f.flush
  f.close

  report_name
end

def handle_optional_report_writing(targets, config, prompt = nil)
  # Probably called prior to doing any finding of metrics usage
  return if targets.empty?

  # No prompt means this was called by the menu selection "Write report" so no interaction is required
  if !prompt
    report_name = write_report(targets, config)
    puts Pastel.new.green("Report #{report_name} written to file.")
    sleep(2)
    targets.clear
    return
  end

  # Prompt is present, which means metrics usage was searched for at least once and something was found
  if !config[:write_report]
    puts Pastel.new.red("Write out report? Previous changes will be cleared when finding metrics usage (existing file changes will remain in place).")
    if !prompt.yes?(Pastel.new.red("Asking because config says not to."))
      write_report(targets, config)
      puts Pastel.new.green("Report written to file.")
      sleep(2)
    end
  else
    write_report(targets, config)
  end

  targets.clear
end

def find_usage(config, targets, dir = ".")
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { return :return_to_menu }

  conversion_targets = find_metrics_usage(dir, targets)
  if conversion_targets == :return_to_menu
    puts "\nReturning to main menu."
    sleep(1)
  elsif conversion_targets == :no_dir
    puts "\nNo directories were selected."
  elsif !conversion_targets.empty?
    clear_screen
    select_files(conversion_targets, config)
  else
    clear_screen
    puts "\nNo metrics usage was found."
    sleep(2)
  end
end

def edit_config(config)
  prompt = TTY::Prompt.new
  prompt.on(:keyescape) { || return }

  loop do
    clear_screen
    puts "Current configuration:"
    puts print_config(config)
    puts
    case prompt.select("Choose configuration option to change; hit esc to return to previous menu", config.keys, cycle: true, echo: false, per_page: 20)
    when :parse_to_unique_metrics
      edit_config_option(config, :parse_to_unique_metrics, :bool)
    when :comment_prometheus_metrics
      edit_config_option(config, :comment_prometheus_metrics, :bool)
    when :write_declare_metrics_block
      edit_config_option(config, :write_declare_metrics_block, :bool)
    when :write_parsed_labels
      edit_config_option(config, :write_parsed_labels, :bool)
    when :write_empty_labels
      edit_config_option(config, :write_empty_labels, :bool)
    when :report_name
      edit_config_option(config, :report_name, :string)
    when :write_report
      edit_config_option(config, :write_report, :bool)
    when :verbose_tty
      edit_config_option(config, :verbose_tty, :bool)
    when :punt_on_variables
      edit_config_option(config, :punt_on_variables, :bool)
    when :punt_on_comma
      edit_config_option(config, :punt_on_comma, :bool)
    when :punt_on_start_with_metrics
      edit_config_option(config, :punt_on_start_with_metrics, :bool)
    when :punt_on_slash
      edit_config_option(config, :punt_on_slash, :bool)
    when :punt_on_end_with_parent
      edit_config_option(config, :punt_on_send_with_parent, :bool)
    end
  end
end

# EXECUTION BEGINS HERE

begin
  clear_screen

  configuration = default_config

  prompt = TTY::Prompt.new

  targets = []

  loop do
    command = prompt.select("\nMain Menu", TOP_LEVEL_COMMANDS, cycle: true, echo: false, per_page: 10)
    case command
    when :clear_screen
      clear_screen
    when :edit_config
      edit_config(configuration)
    when :write_report
      handle_optional_report_writing(targets, configuration)
    when :find_with_directory
      handle_optional_report_writing(targets, configuration, prompt)
      directory = enter_directory
      next if directory == :return_to_menu
      find_usage(configuration, targets, directory)
    when :quit
      exit
    end
  end
rescue StandardError => ex
  puts "ERROR - " + ex.to_s
  puts ex.backtrace
end


text:
namespace Microsoft.Azure.Management.Monitor.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Metric namespace class specifies the metadata for a metric namespace.
    /// </summary>
    public partial class MetricNamespace
    {
        /// <summary>
        /// Initializes a new instance of the MetricNamespace class.
        /// </summary>
        public MetricNamespace()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the MetricNamespace class.
        /// </summary>
        /// <param name="id">The ID of the metricNamespace.</param>
        /// <param name="type">The type of the namespace.</param>
        /// <param name="name">The name of the namespace.</param>
        /// <param name="properties">Properties which include the fully
        /// qualified namespace name.</param>
        public MetricNamespace(string id = default(string), string type = default(string), string name = default(string), MetricNamespaceName properties = default(MetricNamespaceName))
        {
            Id = id;
            Type = type;
            Name = name;
            Properties = properties;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the ID of the metricNamespace.
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the type of the namespace.
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets the name of the namespace.
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets properties which include the fully qualified namespace
        /// name.
        /// </summary>
        [JsonProperty(PropertyName = "properties")]
        public MetricNamespaceName Properties { get; set; }

    }
}