text:
__author__ = 'boye'

from boye import Spotify
from time import sleep
from flask import Flask, url_for, redirect, render_template, request, Response

app = Flask(__name__)

@app.route('/')
def home():
    pl = [
        'spotify:user:lars_93:playlist:17dahvTFovxEqqEJLsDoNQ',
        'spotify:user:pumazz:playlist:2e3fd32clPYmADf809LrM6',
        'spotify:user:pumazz:playlist:7dD8A6HTNUYW6kgs9yvh28',
        'spotify:user:lars_93:playlist:1cURhgTeJBdZFuurOcjFRg',
        'spotify:user:pumazz:playlist:2Qn3V38vhATTp1M7wzYG0p',
        'spotify:user:pumazz:playlist:6wnTPemhthfpExS1W8jklx',
        'spotify:user:magnode:playlist:5NLNeYg2ZMM8Zb1KR2mtBl'
    ]

    playlists = list()
    for uri in pl:
        playlist = spotify.get_playlist(uri)
        images = list()
        for track in playlist.tracks:
            track.load()
            if not track.availability == 1:
                continue
            try:
                url = track.album.load().cover_link(2).url
                images.append(url)
            except AssertionError:
                pass
            if len(images) >= 4:
                break

        while len(images) < 4:
            images.append("http://placehold.it/200x200")

        playlists.append({"name": playlist.name, "owner": playlist.owner.display_name, "uri": uri, "image": images})

    tracks = list()
    for track in spotify.Queue.get_queue_tracks():
        track.load()
        name = track.name
        duration = '%d:%02d' % divmod(track.duration / 1000, 60)
        if len(name) > 28:
            name = name[:25] + '...'
        artist = ', '.join([artist.name for artist in track.artists])
        if len(artist) > 35:
            artist = artist[:30] + '...'
        uri = track.link.uri

        tracks.append({"name": name, "artist": artist, "uri": uri, "duration": duration})

    return render_template('home.html', playlists=playlists, tracks=tracks)

@app.route('/playlist/<uri>')
def playlist(uri):
    pl = spotify.get_playlist(uri)

    tracks = list()
    images = list()

    for track in pl.tracks:
        track.load()
        if not track.availability == 1:
            continue
        if len(images) < 4:
            try:
                url = track.album.load().cover_link(2).url
                images.append(url)
            except AssertionError:
                pass
        name = track.name
        duration = '%d:%02d' % divmod(track.duration / 1000, 60)
        if len(name) > 35:
            name = name[:30] + '...'
        artist = ', '.join([artist.name for artist in track.artists])
        if len(artist) > 35:
            artist = artist[:30] + '...'
        track_uri = track.link.uri

        tracks.append({"name": name, "artist": artist, "uri": track_uri, "duration": duration})

    while len(images) < 4:
        images.append("http://placehold.it/200x200")

    return render_template('playlist.html', uri=uri, name=pl.name, owner=pl.owner.display_name, image=images, tracks=tracks)

@app.route('/queue/<uri>')
def add_queue(uri):
    spotify.Queue.add_queue(uri)
    return ''

@app.route('/next/<uri>')
def add_next(uri):
    spotify.Queue.add_next(uri)
    return ''

@app.route('/now/<uri>')
def play_now(uri):
    spotify.Queue.add_next(uri)
    spotify.Player.play_next()
    return ''

@app.route('/play')
def play():
    if not spotify.Player.is_loaded():
        spotify.Player.restart()
    else:
        spotify.Player.play()
    return ''

@app.route('/pause')
def pause():
    if spotify.Player.is_loaded():
        spotify.Player.pause()
    return ''

@app.route('/view/queue')
def view_queue():
    tracks = list()

    for track in spotify.Queue.get_queue_tracks():
        track.load()
        name = track.name
        duration = '%d:%02d' % divmod(track.duration / 1000, 60)
        if len(name) > 35:
            name = name[:30] + '...'
        artist = ', '.join([artist.name for artist in track.artists])
        if len(artist) > 35:
            artist = artist[:30] + '...'
        uri = track.link.uri

        tracks.append({"name": name, "artist": artist, "uri": uri, "duration": duration})

    return render_template('queue.html', tracks=tracks)

@app.route('/queue/remove/index/<int:pos>')
def remove_track_index(pos):
    if 0 <= pos <= spotify.Queue.get_queue_size() - 1:
        if pos == spotify.Queue.get_position():
            spotify.Queue.remove_current()
            if spotify.Player.is_playing():
                spotify.Player.restart()
            else:
                spotify.Player.restart()
                spotify.Player.pause()
        else:
            spotify.Queue.remove(pos)
    return ''

@app.route('/replace/<uri>')
def replace_queue_song(uri):
    spotify.Queue.remove_all()
    spotify.Queue.add_queue(uri)
    spotify.Player.restart()
    return ''

@app.route('/album/queue/<uri>')
def add_queue_album(uri):
    tracks = spotify.get_tracks_of_album(spotify.get_album(uri))
    for track in tracks:
        if not track.availability == 1:
            continue
        add_queue(track.load().link.uri)
    return ''

@app.route('/album/next/<uri>')
def add_next_album(uri):
    tracks = [track for track in spotify.get_tracks_of_album(spotify.get_album(uri))]
    if spotify.Queue.get_queue_size() <= 0:
        for track in tracks:
            track.load()
            if not track.availability == 1:
                continue
            add_queue(track.link.uri)
    else:
        tracks.reverse()
        for track in tracks:
            track.load()
            if not track.availability == 1:
                continue
            add_next(track.link.uri)
    return ''

@app.route('/album/now/<uri>')
def add_now_album(uri):
    add_next_album(uri)
    if spotify.Player.is_playing():
        spotify.Player.play_next()
    else:
        if spotify.Queue.get_queue_size() <= 0:
            spotify.Player.restart()
        else:
            spotify.Player.play_next()
    return ''

@app.route('/album/replace/<uri>')
def add_replace_album(uri):
    spotify.Queue.remove_all()
    add_queue_album(uri)
    spotify.Player.restart()
    return ''

@app.route('/playlist/queue/<uri>')
def add_queue_playlist(uri):
    tracks = spotify.get_playlist(uri).tracks
    for track in tracks:
        track.load()
        if not track.availability == 1:
            continue
        add_queue(track.link.uri)
    return ''

@app.route('/playlist/next/<uri>')
def add_next_playlist(uri):
    tracks = [track for track in spotify.get_playlist(uri).tracks]
    if spotify.Queue.get_queue_size() <= 0:
        for track in tracks:
            track.load()
            if not track.availability == 1:
                continue
            add_queue(track.link.uri)
    else:
        tracks.reverse()
        for track in tracks:
            track.load()
            if not track.availability == 1:
                continue
            add_next(track.link.uri)
    return ''

@app.route('/playlist/now/<uri>')
def add_now_playlist(uri):
    add_next_playlist(uri)
    if spotify.Player.is_playing():
        spotify.Player.play_next()
    else:
        if spotify.Queue.get_queue_size() <= 0:
            spotify.Player.restart()
        else:
            spotify.Player.play_next()
    return ''

@app.route('/playlist/replace/<uri>')
def add_replace_playlist(uri):
    spotify.Queue.remove_all()
    add_queue_playlist(uri)
    spotify.Player.restart()
    return ''

@app.route('/album/<uri>')
def view_album(uri):
    album = spotify.get_album(uri)
    result = False

    track_list = list()

    for track in spotify.get_tracks_of_album(album):

        track.load()
        if not track.availability == 1:
            continue

        result = True
        name = track.name
        duration = '%d:%02d' % divmod(track.duration / 1000, 60)
        if len(name) > 35:
            name = name[:30] + '...'
        artist = ', '.join([artist.name for artist in track.artists])
        if len(artist) > 35:
            artist = artist[:30] + '...'
        track_uri = track.link.uri

        track_list.append({"name": name, "artist": artist, "uri": track_uri, "duration": duration})

    name = album.name

    artist = album.artist.name

    image = album.cover_link(2).url

    return render_template('album.html', uri=uri, result=result, image=image, artist=artist, name=name,
                           tracks=track_list)

@app.route('/search')
def search():
    try:
        s = request.args['s']
        result = spotify.search(s)

        artist_list = list()
        track_list = list()
        album_list = list()

        for artist in result.artists:
            artist.load()
            try:
                img = artist.portrait_link().url
            except AssertionError:
                # artist has no portrait
                img = 'http://placehold.it/300x300'
            name = artist.name
            if len(name) > 22:
                name = name[:20] + '...'
            uri = artist.link.uri

            artist_list.append({"image": img, "name": name, "uri": uri})

        for track in result.tracks:
            track.load()
            if not track.availability == 1:
                continue
            name = track.name
            duration = '%d:%02d' % divmod(track.duration / 1000, 60)
            if len(name) > 35:
                name = name[:30] + '...'
            artist = ', '.join([artist.name for artist in track.artists])
            if len(artist) > 35:
                artist = artist[:30] + '...'
            uri = track.link.uri

            track_list.append({"name": name, "artist": artist, "uri": uri, "duration": duration})

        for album in result.albums:
            album.load()
            name = album.name
            if len(name) > 22:
                name = name[:20] + '...'
            artist = album.artist.name
            if len(artist) > 22:
                artist = artist[:20] + '...'
            uri = album.link.uri
            img = album.cover_link().url

            album_list.append({"name": name, "artist": artist, "uri": uri, "image": img})

        result = album_list or track_list or artist_list
        r = len(track_list)
        if r > 10:
            r = 10

        return render_template('search.html', song_range=range(r), result=result, search=s, albums=album_list,
                               tracks=track_list, artists=artist_list)

    except KeyError:
        return redirect(url_for('home'))

@app.route('/artist/<uri>')
def view_artist(uri):
    image, name, artist_browser = spotify.get_artist(uri)

    biography = artist_browser.biography

    top_tracks = list()

    for track in artist_browser.tophit_tracks:
        track.load()
        if not track.availability == 1:
            continue
        track_name = track.name
        duration = '%d:%02d' % divmod(track.duration / 1000, 60)
        if len(track_name) > 35:
            track_name = track_name[:30] + '...'
        artist = ', '.join([artist.name for artist in track.artists])
        if len(artist) > 35:
            artist = artist[:30] + '...'
        uri = track.link.uri

        top_tracks.append({"name": track_name, "artist": artist, "uri": uri, "duration": duration})

    albums = list()

    for album in artist_browser.albums:
        album.load()
        album_name = album.name
        if len(album_name) > 42:
            album_name = album_name[:40] + '...'
        artist = album.artist.name
        if len(artist) > 22:
            artist = artist[:20] + '...'
        uri = album.link.uri
        img = album.cover_link().url

        albums.append({"name": album_name, "artist": artist, "uri": uri, "image": img})

    return render_template('artist.html', albums=albums, num_of_albums=len(albums), tracks=top_tracks[:5], image=image, name=name,
                           biography=biography)

@app.route('/stream/now_playing')
def stream_now_playing():
    def generate():
        old_index = -1
        while True:
            index = spotify.Queue.get_position()
            if old_index != index:
                old_index = index
                yield 'data: {}\n\n'.format(index)
            sleep(.1)

    return Response(generate(), mimetype='text/event-stream')

@app.route('/stream/queue_changed')
def stream_queue_changed():
    def generate():
        while True:
            if spotify.Queue.is_changed():
                yield 'data: 1\n\n'
            sleep(.1)
    return Response(generate(), mimetype='text/event-stream')

@app.route('/move/<int:index_from>/<int:index_to>')
def move_track(index_from, index_to):
    spotify.Queue.move(index_from, index_to)
    return ''

@app.route('/next')
def play_next():
    spotify.Player.play_next()
    return ''

@app.route('/previous')
def play_previous():
    spotify.Player.play_previous()
    return ''

@app.route('/user/<uri>')
def view_user(uri):
    user = spotify.get_user(uri)
    if user:
        name = user.display_name

        starred = list()

        for track in user.starred.load(2).tracks:
            track.load()
            if not track.availability == 1:
                continue
            track_name = track.name
            duration = '%d:%02d' % divmod(track.duration / 1000, 60)
            if len(track_name) > 35:
                track_name = track_name[:30] + '...'
            artist = ', '.join([artist.name for artist in track.artists])
            if len(artist) > 35:
                artist = artist[:30] + '...'
            uri = track.link.uri

            starred.append({"name": track_name, "artist": artist, "uri": uri, "duration": duration})

        playlists = list()

        for playlist in user.published_playlists.load():
            playlist.load()
            print playlist.name
            print playlist.link
            playlists.append({"name": playlist.name, "owner": playlist.owner, "subs": playlist.subscribers,
                              "uri": "hei"})

        return render_template('user.html', name=name, starred=starred, playlists=playlists)

    return render_template("user.html", name="No user", starred=list(), playlists=list())

@app.route('/play/index/<int:pos>')
def play_index(pos):
    spotify.Player.play_position(pos)
    return ''

if __name__ == '__main__':
    spotify = Spotify()
    app.run(debug=True, host='0.0.0.0', port=5001, threaded=True)


text:
    {!! Form::text('category', (isset($category_name) ? $category_name : null), ['readonly', 'class'=>'form-control', 'placeholder'=>"Click 'Select'"]) !!}
    {!! Form::hidden('category_id', (isset($category_id) ? $category_id : null)) !!}

    	<button class="btn btn-primary" data-toggle="modal" data-target="#inventoryCategoryModal" type="button">Select
        </button>
        Manage

                <button type="button" class="close" data-dismiss="modal">×Close</button>

Select a Category

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button id="inventory-category-select" type="button" class="btn btn-primary" disabled="disabled"
                        data-dismiss="modal">Select
                </button>

redpajama_set_name: RedPajamaGithub


text:
module RailsElfinder
  VERSION = "0.0.1"
end


text:
describe('<InstituteCalendar />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});


text:
namespace rime {

Selector::Selector(const Ticket& ticket) : Processor(ticket) {
}

ProcessResult Selector::ProcessKeyEvent(const KeyEvent& key_event) {
  if (key_event.release() || key_event.alt())
    return kNoop;
  Context* ctx = engine_->context();
  if (ctx->composition().empty())
    return kNoop;
  Segment& current_segment(ctx->composition().back());
  if (!current_segment.menu || current_segment.HasTag("raw"))
    return kNoop;
  int ch = key_event.keycode();
  if (ch == XK_Prior || ch == XK_KP_Prior) {
    PageUp(ctx);
    return kAccepted;
  }
  if (ch == XK_Next || ch == XK_KP_Next) {
    PageDown(ctx);
    return kAccepted;
  }
  if (ch == XK_Up || ch == XK_KP_Up) {
    if (ctx->get_option("_horizontal")) {
      PageUp(ctx);
    } else {
      CursorUp(ctx);
    }
    return kAccepted;
  }
  if (ch == XK_Down || ch == XK_KP_Down) {
    if (ctx->get_option("_horizontal")) {
      PageDown(ctx);
    } else {
      CursorDown(ctx);
    }
    return kAccepted;
  }
  if (ch == XK_Left || ch == XK_KP_Left) {
    if (!key_event.ctrl() &&
        !key_event.shift() &&
        ctx->caret_pos() == ctx->input().length() &&
        ctx->get_option("_horizontal") &&
        CursorUp(ctx)) {
      return kAccepted;
    }
    return kNoop;
  }
  if (ch == XK_Right || ch == XK_KP_Right) {
    if (!key_event.ctrl() &&
        !key_event.shift() &&
        ctx->caret_pos() == ctx->input().length() &&
        ctx->get_option("_horizontal")) {
      CursorDown(ctx);
      return kAccepted;
    }
    return kNoop;
  }
  if (ch == XK_Home || ch == XK_KP_Home) {
    return Home(ctx) ? kAccepted : kNoop;
  }
  if (ch == XK_End || ch == XK_KP_End) {
    return End(ctx) ? kAccepted : kNoop;
  }
  int index = -1;
  const string& select_keys(engine_->schema()->select_keys());
  if (!select_keys.empty() &&
      !key_event.ctrl() &&
      ch >= 0x20 && ch < 0x7f) {
    size_t pos = select_keys.find((char)ch);
    if (pos != string::npos) {
      index = static_cast<int>(pos);
    }
  }
  else if (ch >= XK_0 && ch <= XK_9)
    index = ((ch - XK_0) + 9) % 10;
  else if (ch >= XK_KP_0 && ch <= XK_KP_9)
    index = ((ch - XK_KP_0) + 9) % 10;
  if (index >= 0) {
    SelectCandidateAt(ctx, index);
    return kAccepted;
  }
  // not handled
  return kNoop;
}

bool Selector::PageUp(Context* ctx) {
  Composition& comp = ctx->composition();
  if (comp.empty())
    return false;
  int page_size = engine_->schema()->page_size();
  int selected_index = comp.back().selected_index;
  int index = selected_index < page_size ? 0 : selected_index - page_size;
  comp.back().selected_index = index;
  comp.back().tags.insert("paging");
  return true;
}

bool Selector::PageDown(Context* ctx) {
  Composition& comp = ctx->composition();
  if (comp.empty() || !comp.back().menu)
    return false;
  int page_size = engine_->schema()->page_size();
  int index = comp.back().selected_index + page_size;
  int page_start = (index / page_size) * page_size;
  int candidate_count = comp.back().menu->Prepare(page_start + page_size);
  if (candidate_count <= page_start)
    return false;
  if (index >= candidate_count)
    index = candidate_count - 1;
  comp.back().selected_index = index;
  comp.back().tags.insert("paging");
  return true;

}

bool Selector::CursorUp(Context* ctx) {
  Composition& comp = ctx->composition();
  if (comp.empty())
    return false;
  int index = comp.back().selected_index;
  if (index <= 0)
    return false;
  comp.back().selected_index = index - 1;
  comp.back().tags.insert("paging");
  return true;
}

bool Selector::CursorDown(Context* ctx) {
  Composition& comp = ctx->composition();
  if (comp.empty() || !comp.back().menu)
    return false;
  int index = comp.back().selected_index + 1;
  int candidate_count = comp.back().menu->Prepare(index + 1);
  if (candidate_count <= index)
    return false;
  comp.back().selected_index = index;
  comp.back().tags.insert("paging");
  return true;
}

bool Selector::Home(Context* ctx) {
  if (ctx->composition().empty())
    return false;
  Segment& seg(ctx->composition().back());
  if (seg.selected_index > 0) {
    seg.selected_index = 0;
    return true;
  }
  return false;
}

bool Selector::End(Context* ctx) {
  if (ctx->caret_pos() < ctx->input().length()) {
    // navigator should handle this
    return false;
  }
  // this is cool:
  return Home(ctx);
}

bool Selector::SelectCandidateAt(Context* ctx, int index) {
  Composition& comp = ctx->composition();
  if (comp.empty())
    return false;
  int page_size = engine_->schema()->page_size();
  if (index >= page_size)
    return false;
  int selected_index = comp.back().selected_index;
  int page_start = (selected_index / page_size) * page_size;
  return ctx->Select(page_start + index);
}

}  // namespace rime


text:
MixedPack
=========

Projects publicly written/contributed by the MixedPack group.


text:
package org.literacyapp.content.task;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.literacyapp.R;

public class LessonCompleteActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(getClass().getName(), "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson_complete);
    }

}


text:
#include "bsonutil/bson-parser.h"
#include "entity-map.h"
#include "json-test.h"
#include "operation.h"
#include "runner.h"
#include "test-conveniences.h"
#include "test-libmongoc.h"
#include "test-diagnostics.h"
#include "utlist.h"
#include "util.h"

typedef struct {
   const char *file_description;
   const char *test_description;
} skipped_unified_test_t;

#define SKIP_ALL_TESTS NULL

// clang-format off
skipped_unified_test_t SKIPPED_TESTS[] = {
   // CDRIVER-4001, DRIVERS-1781, and DRIVERS-1448: 5.0 cursor behavior
   {"poc-command-monitoring", "A successful find event with a getmore and the server kills the cursor"},
   // CDRIVER-3867: drivers atlas testing (schema version 1.2)
   {"entity-client-storeEventsAsEntities", SKIP_ALL_TESTS},
   // libmongoc does not have a distinct helper, so skip snapshot tests testing particular distinct functionality
   {"snapshot-sessions", "Distinct operation with snapshot"},
   {"snapshot-sessions", "Mixed operation with snapshot"},
   // CDRIVER-3886: serverless testing (schema version 1.4)
   {"poc-crud", SKIP_ALL_TESTS},
   {"db-aggregate", SKIP_ALL_TESTS},
   {"mongos-unpin", SKIP_ALL_TESTS},
   // CDRIVER-2871: CMAP is not implemented
   {"assertNumberConnectionsCheckedOut", SKIP_ALL_TESTS},
   {"entity-client-cmap-events", SKIP_ALL_TESTS},
   {"expectedEventsForClient-eventType", SKIP_ALL_TESTS},
   // CDRIVER-4115: listCollections does not support batchSize.
   {"cursors are correctly pinned to connections for load-balanced clusters", "listCollections pins the cursor to a connection"},
   // CDRIVER-4116: listIndexes does not support batchSize.
   {"cursors are correctly pinned to connections for load-balanced clusters", "listIndexes pins the cursor to a connection"},
   // libmongoc does not pin connections to cursors. It cannot force an error from waitQueueTimeoutMS by creating cursors in load balanced mode.
   {"wait queue timeout errors include details about checked out connections", SKIP_ALL_TESTS},
   // libmongoc does not support the optional findOne helper.
   {"retryable reads handshake failures", "findOne succeeds after retryable handshake network error"},
   {"retryable reads handshake failures", "findOne succeeds after retryable handshake server error (ShutdownInProgress)"},
   // libmongoc does not support the optional count helper.
   {"retryable reads handshake failures", "count succeeds after retryable handshake network error"},
   {"retryable reads handshake failures", "count succeeds after retryable handshake server error (ShutdownInProgress)"},
   // libmongoc does not support the optional listIndexNames helper.
   {"retryable reads handshake failures", "listIndexNames succeeds after retryable handshake network error"},
   {"retryable reads handshake failures", "listIndexNames succeeds after retryable handshake server error (ShutdownInProgress)"},
   {0},
};
// clang-format on

static bool
is_test_file_skipped (test_file_t *test_file)
{
   skipped_unified_test_t *skip;

   for (skip = SKIPPED_TESTS; skip->file_description != NULL; skip++) {
      if (!strcmp (skip->file_description, test_file->description) &&
          skip->test_description == SKIP_ALL_TESTS) {
         return true;
      }
   }

   return false;
}

static bool
is_test_skipped (test_t *test)
{
   skipped_unified_test_t *skip;

   for (skip = SKIPPED_TESTS; skip->file_description != NULL; skip++) {
      if (!strcmp (skip->file_description, test->test_file->description) &&
          !strcmp (skip->test_description, test->description)) {
         return true;
      }
   }

   return false;
}

struct _failpoint_t {
   char *client_id;
   char *name;
   uint32_t server_id;
   struct _failpoint_t *next;
};

failpoint_t *
failpoint_new (char *name, char *client_id, uint32_t server_id)
{
   failpoint_t *fp = (failpoint_t *) bson_malloc0 (sizeof (failpoint_t));

   fp->name = bson_strdup (name);
   fp->client_id = bson_strdup (client_id);
   fp->server_id = server_id;
   return fp;
}

void
failpoint_destroy (failpoint_t *fp)
{
   if (!fp) {
      return;
   }
   bson_free (fp->name);
   bson_free (fp->client_id);
   bson_free (fp);
}

/* Set server_id to 0 if the failpoint was not against a pinned mongos. */
void
register_failpoint (test_t *test,
                    char *name,
                    char *client_id,
                    uint32_t server_id)
{
   failpoint_t *fp = NULL;

   fp = failpoint_new (name, client_id, server_id);
   LL_APPEND (test->failpoints, fp);
}

static bool
cleanup_failpoints (test_t *test, bson_error_t *error)
{
   bool ret = false;
   failpoint_t *iter = NULL;
   mongoc_read_prefs_t *rp = NULL;

   rp = mongoc_read_prefs_new (MONGOC_READ_PRIMARY_PREFERRED);

   LL_FOREACH (test->failpoints, iter)
   {
      mongoc_client_t *client = NULL;
      bson_t *disable_cmd = NULL;

      client = entity_map_get_client (test->entity_map, iter->client_id, error);
      if (!client) {
         goto done;
      }

      disable_cmd =
         tmp_bson ("{'configureFailPoint': '%s', 'mode': 'off' }", iter->name);
      if (iter->server_id != 0) {
         if (!mongoc_client_command_simple_with_server_id (client,
                                                           "admin",
                                                           disable_cmd,
                                                           rp,
                                                           iter->server_id,
                                                           NULL /* reply */,
                                                           error)) {
            bson_destroy (disable_cmd);
            goto done;
         }
      } else {
         if (!mongoc_client_command_simple (
                client, "admin", disable_cmd, rp, NULL /* reply */, error)) {
            bson_destroy (disable_cmd);
            goto done;
         }
      }
   }

   ret = true;
done:
   mongoc_read_prefs_destroy (rp);
   return ret;
}

static bool
test_has_operation (test_t *test, char *op_name)
{
   bson_iter_t iter;

   BSON_FOREACH (test->operations, iter)
   {
      bson_t op_bson;

      bson_iter_bson (&iter, &op_bson);
      if (0 == strcmp (bson_lookup_utf8 (&op_bson, "name"), op_name)) {
         return true;
      }
   }
   return false;
}

static const char *
get_topology_type (mongoc_client_t *client);

static bool
is_topology_type_sharded (const char *topology_type)
{
   return 0 == strcmp ("sharded", topology_type) ||
          0 == strcmp ("sharded-replicaset", topology_type);
}

static bool
is_topology_type_compatible (const char *test_topology_type,
                             const char *server_topology_type)
{
   if (0 == strcmp (test_topology_type, server_topology_type)) {
      return true;
   }
   /* If a requirement specifies a "sharded" topology and server is of type
    * "sharded-replicaset", that is also compatible. */
   return 0 == strcmp (test_topology_type, "sharded") &&
          is_topology_type_sharded (server_topology_type);
}

/* This callback tracks the set of server IDs for all connected servers.
 * The set of server IDs is used when sending a command to each individual
 * server.
 */
static void
on_topology_changed (const mongoc_apm_topology_changed_t *event)
{
   test_runner_t *test_runner = NULL;
   const mongoc_topology_description_t *td;
   mongoc_server_description_t **sds;
   size_t sds_len;
   size_t i;

   test_runner =
      (test_runner_t *) mongoc_apm_topology_changed_get_context (event);
   _mongoc_array_clear (&test_runner->server_ids);
   td = mongoc_apm_topology_changed_get_new_description (event);
   sds = mongoc_topology_description_get_servers (td, &sds_len);
   for (i = 0; i < sds_len; i++) {
      uint32_t server_id = mongoc_server_description_id (sds[i]);
      MONGOC_DEBUG ("topology changed, adding server id: %d", (int) server_id);
      _mongoc_array_append_val (&test_runner->server_ids, server_id);
   }
   mongoc_server_descriptions_destroy_all (sds, sds_len);
}

/* Returns an array of all known servers IDs that the test runner
 * is connected to. The server IDs can be used to target commands to
 * specific servers with mongoc_client_command_simple_with_server_id().
 */
static void
test_runner_get_all_server_ids (test_runner_t *test_runner, mongoc_array_t *out)
{
   bson_error_t error;
   bool ret;

   /* Run a 'ping' command to make sure topology has been scanned. */
   ret = mongoc_client_command_simple (test_runner->internal_client,
                                       "admin",
                                       tmp_bson ("{'ping': 1}"),
                                       NULL /* read prefs */,
                                       NULL /* reply */,
                                       NULL /* error */);
   ASSERT_OR_PRINT (ret, error);

   _mongoc_array_copy (out, &test_runner->server_ids);
}

/* Run killAllSessions against the primary or each mongos to terminate any
 * lingering open transactions.
 * See also: Spec section "Terminating Open Transactions"
 */
static bool
test_runner_terminate_open_transactions (test_runner_t *test_runner,
                                         bson_error_t *error)
{
   bson_t *kill_all_sessions_cmd = NULL;
   bool ret = false;
   bool cmd_ret = false;
   bson_error_t cmd_error = {0};

   if (0 == test_framework_skip_if_no_txns ()) {
      ret = true;
      goto done;
   }

   kill_all_sessions_cmd = tmp_bson ("{'killAllSessions': []}");
   /* Run on each mongos. Target each server individually. */
   if (is_topology_type_sharded (test_runner->topology_type)) {
      mongoc_array_t server_ids;
      size_t i;

      _mongoc_array_init (&server_ids, sizeof (uint32_t));
      test_runner_get_all_server_ids (test_runner, &server_ids);
      for (i = 0; i < server_ids.len; i++) {
         uint32_t server_id = _mongoc_array_index (&server_ids, uint32_t, i);

         cmd_ret = mongoc_client_command_simple_with_server_id (
            test_runner->internal_client,
            "admin",
            kill_all_sessions_cmd,
            NULL /* read prefs. */,
            server_id,
            NULL,
            &cmd_error);

         /* Ignore error code 11601 as a workaround for SERVER-38335. */
         if (!cmd_ret && cmd_error.code != 11601) {
            test_set_error (
               error,
               "Unexpected error running killAllSessions on server (%d): %s",
               (int) server_id,
               cmd_error.message);
            goto done;
         }
      }
      _mongoc_array_destroy (&server_ids);
   } else {
      /* Run on primary. */
      cmd_ret = mongoc_client_command_simple (test_runner->internal_client,
                                              "admin",
                                              kill_all_sessions_cmd,
                                              NULL /* read prefs. */,
                                              NULL,
                                              &cmd_error);

      /* Ignore error code 11601 as a workaround for SERVER-38335. */
      if (!cmd_ret && cmd_error.code != 11601) {
         test_set_error (
            error,
            "Unexpected error running killAllSessions on primary: %s",
            cmd_error.message);
         goto done;
      }
   }

   ret = true;
done:
   return ret;
}

static test_runner_t *
test_runner_new (void)
{
   test_runner_t *test_runner = NULL;
   mongoc_apm_callbacks_t *callbacks = NULL;
   mongoc_uri_t *uri = NULL;
   bson_error_t error;
   bson_t reply;

   test_runner = bson_malloc0 (sizeof (test_runner_t));
   /* Create a client for internal test operations (e.g. checking server
    * version) */
   _mongoc_array_init (&test_runner->server_ids, sizeof (uint32_t));
   callbacks = mongoc_apm_callbacks_new ();
   mongoc_apm_set_topology_changed_cb (callbacks, on_topology_changed);
   uri = test_framework_get_uri ();
   /* In load balanced mode, the internal client must use the
    * SINGLE_LB_MONGOS_URI. */
   if (!test_framework_is_loadbalanced ()) {
      /* Always use multiple mongoses if speaking to a mongos.
       * Some test operations require communicating with all known mongos */
      if (!test_framework_uri_apply_multi_mongos (uri, true, &error)) {
         test_error ("error applying multiple mongos: %s", error.message);
      }
   }
   test_runner->internal_client =
      test_framework_client_new_from_uri (uri, NULL);
   test_framework_set_ssl_opts (test_runner->internal_client);
   mongoc_uri_destroy (uri);

   mongoc_client_set_apm_callbacks (
      test_runner->internal_client, callbacks, test_runner);
   mongoc_client_set_error_api (test_runner->internal_client,
                                MONGOC_ERROR_API_VERSION_2);
   test_runner->topology_type =
      get_topology_type (test_runner->internal_client);
   server_semver (test_runner->internal_client, &test_runner->server_version);

   test_runner->is_serverless = test_framework_is_serverless ();

   /* Terminate any possible open transactions. */
   if (!test_runner_terminate_open_transactions (test_runner, &error)) {
      test_error ("error terminating transactions: %s", error.message);
   }
   mongoc_apm_callbacks_destroy (callbacks);

   /* Cache server parameters to check runOnRequirements. */
   if (!mongoc_client_command_simple (test_runner->internal_client,
                                      "admin",
                                      tmp_bson ("{'getParameter': '*'}"),
                                      NULL,
                                      &reply,
                                      &error)) {
      test_error ("error getting server parameters: %s, full reply: %s",
                  error.message,
                  tmp_json (&reply));
   }
   test_runner->server_parameters = bson_copy (&reply);
   bson_destroy (&reply);
   return test_runner;
}

static void
test_runner_destroy (test_runner_t *test_runner)
{
   mongoc_client_destroy (test_runner->internal_client);
   _mongoc_array_destroy (&test_runner->server_ids);
   bson_destroy (test_runner->server_parameters);
   bson_free (test_runner);
}

static test_file_t *
test_file_new (test_runner_t *test_runner, bson_t *bson)
{
   test_file_t *test_file = NULL;
   bson_parser_t *parser = NULL;
   char *schema_version = NULL;

   test_file = bson_malloc0 (sizeof (test_file_t));
   test_file->test_runner = test_runner;

   parser = bson_parser_new ();
   bson_parser_utf8 (parser, "description", &test_file->description);
   bson_parser_utf8 (parser, "schemaVersion", &schema_version);
   bson_parser_array_optional (
      parser, "runOnRequirements", &test_file->run_on_requirements);
   bson_parser_array_optional (
      parser, "createEntities", &test_file->create_entities);
   bson_parser_array_optional (parser, "initialData", &test_file->initial_data);
   bson_parser_doc_optional (parser, "_yamlAnchors", &test_file->yaml_anchors);
   bson_parser_array (parser, "tests", &test_file->tests);
   bson_parser_parse_or_assert (parser, bson);
   bson_parser_destroy (parser);

   semver_parse (schema_version, &test_file->schema_version);
   bson_free (schema_version);
   return test_file;
}

static void
test_file_destroy (test_file_t *test_file)
{
   bson_free (test_file->description);
   bson_destroy (test_file->tests);
   bson_destroy (test_file->initial_data);
   bson_destroy (test_file->create_entities);
   bson_destroy (test_file->run_on_requirements);
   bson_destroy (test_file->yaml_anchors);
   bson_free (test_file);
}

static test_t *
test_new (test_file_t *test_file, bson_t *bson)
{
   test_t *test = NULL;
   bson_parser_t *parser = NULL;

   test = bson_malloc0 (sizeof (test_t));
   test->test_file = test_file;
   parser = bson_parser_new ();
   bson_parser_utf8 (parser, "description", &test->description);
   bson_parser_array_optional (
      parser, "runOnRequirements", &test->run_on_requirements);
   bson_parser_utf8_optional (parser, "skipReason", &test->skip_reason);
   bson_parser_array (parser, "operations", &test->operations);
   bson_parser_array_optional (parser, "expectEvents", &test->expect_events);
   bson_parser_array_optional (parser, "outcome", &test->outcome);
   bson_parser_parse_or_assert (parser, bson);
   bson_parser_destroy (parser);

   test->entity_map = entity_map_new ();
   return test;
}

static void
test_destroy (test_t *test)
{
   failpoint_t *fpiter, *fptmp;

   LL_FOREACH_SAFE (test->failpoints, fpiter, fptmp)
   {
      failpoint_destroy (fpiter);
   }

   entity_map_destroy (test->entity_map);
   bson_destroy (test->outcome);
   bson_destroy (test->expect_events);
   bson_destroy (test->operations);
   bson_destroy (test->run_on_requirements);
   bson_free (test->description);
   bson_free (test->skip_reason);
   bson_free (test);
}

static bool
is_replset (bson_t *hello_reply)
{
   if (bson_has_field (hello_reply, "setName")) {
      return true;
   }

   if (bson_has_field (hello_reply, "isreplicaset") &&
       bson_lookup_bool (hello_reply, "isreplicaset") == true) {
      return true;
   }

   return false;
}

static bool
is_sharded (bson_t *hello_reply)
{
   const char *val;
   if (!bson_has_field (hello_reply, "msg")) {
      return false;
   }

   val = bson_lookup_utf8 (hello_reply, "msg");
   if (0 == strcmp (val, "isdbgrid")) {
      return true;
   }
   return false;
}

static const char *
get_topology_type (mongoc_client_t *client)
{
   bool ret;
   bson_t reply;
   bson_error_t error;
   const char *topology_type = "single";

   if (test_framework_is_loadbalanced ()) {
      return "load-balanced";
   }

   ret = mongoc_client_command_simple (
      client, "admin", tmp_bson ("{'hello': 1}"), NULL, &reply, &error);
   if (!ret) {
      bson_destroy (&reply);
      ret = mongoc_client_command_simple (
         client,
         "admin",
         tmp_bson ("{'" HANDSHAKE_CMD_LEGACY_HELLO "': 1}"),
         NULL,
         &reply,
         &error);
   }
   ASSERT_OR_PRINT (ret, error);

   if (is_replset (&reply)) {
      topology_type = "replicaset";
   } else if (is_sharded (&reply)) {
      bool is_sharded_replset;
      mongoc_collection_t *config_shards = NULL;
      mongoc_cursor_t *cursor = NULL;
      const bson_t *shard_doc;

      /* Check if this is a sharded-replicaset by querying the config.shards
       * collection. */
      is_sharded_replset = true;
      config_shards = mongoc_client_get_collection (client, "config", "shards");
      cursor = mongoc_collection_find_with_opts (config_shards,
                                                 tmp_bson ("{}"),
                                                 NULL /* opts */,
                                                 NULL /* read prefs */);
      if (mongoc_cursor_error (cursor, &error)) {
         test_error ("Attempting to query config.shards collection failed: %s",
                     error.message);
      }
      while (mongoc_cursor_next (cursor, &shard_doc)) {
         const char *host = bson_lookup_utf8 (shard_doc, "host");
         if (NULL == strstr (host, "/")) {
            is_sharded_replset = false;
            break;
         }
      }

      mongoc_cursor_destroy (cursor);
      mongoc_collection_destroy (config_shards);

      if (is_sharded_replset) {
         topology_type = "sharded-replicaset";
      } else {
         topology_type = "sharded";
      }
   }

   bson_destroy (&reply);
   return topology_type;
}

static void
check_schema_version (test_file_t *test_file)
{
   const char *supported_version_strs[] = {"1.8"};
   int i;

   for (i = 0; i < sizeof (supported_version_strs) /
                      sizeof (supported_version_strs[0]);
        i++) {
      semver_t supported_version;

      semver_parse (supported_version_strs[i], &supported_version);
      if (supported_version.major != test_file->schema_version.major) {
         continue;
      }
      if (!supported_version.has_minor) {
         /* All minor versions for this major version are supported. */
         return;
      }
      if (supported_version.minor >= test_file->schema_version.minor) {
         return;
      }
   }

   test_error ("Unsupported schema version: %s",
               semver_to_string (&test_file->schema_version));
}

static bool
check_run_on_requirement (test_runner_t *test_runner,
                          bson_t *run_on_requirement,
                          const char *server_topology_type,
                          semver_t *server_version,
                          char **fail_reason)
{
   bson_iter_t req_iter;

   BSON_FOREACH (run_on_requirement, req_iter)
   {
      const char *key = bson_iter_key (&req_iter);

      if (0 == strcmp (key, "minServerVersion")) {
         semver_t min_server_version;

         semver_parse (bson_iter_utf8 (&req_iter, NULL), &min_server_version);
         if (semver_cmp (server_version, &min_server_version) < 0) {
            *fail_reason = bson_strdup_printf (
               "Server version(%s) is lower than minServerVersion(%s)",
               semver_to_string (server_version),
               semver_to_string (&min_server_version));
            return false;
         }
         continue;
      }

      if (0 == strcmp (key, "maxServerVersion")) {
         semver_t max_server_version;

         semver_parse (bson_iter_utf8 (&req_iter, NULL), &max_server_version);
         if (semver_cmp (server_version, &max_server_version) > 0) {
            *fail_reason = bson_strdup_printf (
               "Server version(%s) is higher than maxServerVersion (%s)",
               semver_to_string (server_version),
               semver_to_string (&max_server_version));
            return false;
         }
         continue;
      }

      if (0 == strcmp (key, "topologies")) {
         bool found = false;
         bson_t topologies;
         bson_iter_t topology_iter;

         bson_iter_bson (&req_iter, &topologies);
         BSON_FOREACH (&topologies, topology_iter)
         {
            const char *test_topology_type =
               bson_iter_utf8 (&topology_iter, NULL);
            if (is_topology_type_compatible (test_topology_type,
                                             server_topology_type)) {
               found = true;
               continue;
            }
         }

         if (!found) {
            *fail_reason = bson_strdup_printf (
               "Topology (%s) was not found among listed topologies: %s",
               server_topology_type,
               tmp_json (&topologies));
            return false;
         }
         continue;
      }

      if (0 == strcmp (key, "serverParameters")) {
         bson_t expected_params;
         bson_val_t *actual_val = NULL;
         bson_val_t *expected_val = NULL;
         bool matched;
         bson_error_t error = {0};

         bson_iter_bson (&req_iter, &expected_params);
         expected_val = bson_val_from_bson (&expected_params);
         actual_val = bson_val_from_bson (test_runner->server_parameters);
         matched = bson_match (expected_val, actual_val, false, &error);
         bson_val_destroy (actual_val);
         bson_val_destroy (expected_val);
         if (!matched) {
            *fail_reason = bson_strdup_printf ("serverParameters mismatch: %s",
                                               error.message);
            return false;
         }
         continue;
      }

      if (0 == strcmp (key, "serverless")) {
         const char *serverless_mode = bson_iter_utf8 (&req_iter, NULL);

         if (0 == strcmp (serverless_mode, "allow")) {
            continue;
         } else if (0 == strcmp (serverless_mode, "require")) {
            if (!test_runner->is_serverless) {
               *fail_reason =
                  bson_strdup_printf ("Not running in serverless mode");
               return false;
            }

            continue;
         } else if (0 == strcmp (serverless_mode, "forbid")) {
            if (test_runner->is_serverless) {
               *fail_reason = bson_strdup_printf ("Running in serverless mode");
               return false;
            }

            continue;
         } else {
            test_error ("Unexpected serverless mode: %s", serverless_mode);
         }

         continue;
      }

      if (0 == strcmp (key, "auth")) {
         bool auth_requirement = bson_iter_bool (&req_iter);

         if (auth_requirement == test_framework_has_auth ()) {
            continue;
         }

         *fail_reason = bson_strdup_printf (
            "Server does not match auth requirement, test %s authentication.",
            auth_requirement ? "requires" : "forbids");

         return false;
      }

#if defined(MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION)
      if (0 == strcmp (key, "csfle")) {
         const bool csfle_required = bson_iter_bool (&req_iter);
         semver_t min_server_version;

         semver_parse ("4.2.0", &min_server_version);
         if (semver_cmp (server_version, &min_server_version) < 0) {
            *fail_reason =
               bson_strdup_printf ("Server version %s is lower than "
                                   "minServerVersion %s required by CSFLE",
                                   semver_to_string (server_version),
                                   semver_to_string (&min_server_version));
            return false;
         }

         if (csfle_required) {
            continue;
         }

         *fail_reason =
            bson_strdup_printf ("CSFLE is not allowed but libmongoc was built "
                                "with MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON");

         return false;
#else
      if (0 == strcmp (key, "csfle")) {
         const bool csfle_required = bson_iter_bool (&req_iter);

         if (!csfle_required) {
            continue;
         }

         *fail_reason = bson_strdup_printf (
            "CSFLE is required but libmongoc was built "
            "without MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION=ON");

         return false;
#endif /* !defined(MONGOC_CLIENT_SIDE_ENCRYPTION) */
      }

      test_error ("Unexpected runOnRequirement field: %s", key);
   }
   return true;
}

static bool
check_run_on_requirements (test_runner_t *test_runner,
                           bson_t *run_on_requirements,
                           const char **reason)
{
   bson_string_t *fail_reasons = NULL;
   bool requirements_satisfied = false;
   bson_iter_t iter;

   fail_reasons = bson_string_new ("");
   BSON_FOREACH (run_on_requirements, iter)
   {
      bson_t run_on_requirement;
      char *fail_reason = NULL;

      bson_iter_bson (&iter, &run_on_requirement);
      fail_reason = NULL;
      if (check_run_on_requirement (test_runner,
                                    &run_on_requirement,
                                    test_runner->topology_type,
                                    &test_runner->server_version,
                                    &fail_reason)) {
         requirements_satisfied = true;
         break;
      }

      bson_string_append_printf (fail_reasons,
                                 "- Requirement %s failed because: %s\n",
                                 bson_iter_key (&iter),
                                 fail_reason);
      bson_free (fail_reason);
   }

   *reason = NULL;
   if (!requirements_satisfied) {
      (*reason) =
         tmp_str ("runOnRequirements not satisfied:\n%s", fail_reasons->str);
   }
   bson_string_free (fail_reasons, true);
   return requirements_satisfied;
}

static bool
test_setup_initial_data (test_t *test, bson_error_t *error)
{
   test_runner_t *test_runner = NULL;
   test_file_t *test_file = NULL;
   bson_iter_t initial_data_iter;

   test_file = test->test_file;
   test_runner = test_file->test_runner;

   if (!test_file->initial_data) {
      return true;
   }

   BSON_FOREACH (test_file->initial_data, initial_data_iter)
   {
      bson_parser_t *parser = NULL;
      bson_t collection_data;
      char *collection_name = NULL;
      char *database_name = NULL;
      bson_t *documents = NULL;
      mongoc_database_t *db = NULL;
      mongoc_collection_t *coll = NULL;
      mongoc_bulk_operation_t *bulk_insert = NULL;
      mongoc_write_concern_t *wc = NULL;
      bson_t *bulk_opts = NULL;
      bson_t *drop_opts = NULL;
      bson_t *create_opts = NULL;
      bool ret = false;

      bson_iter_bson (&initial_data_iter, &collection_data);
      parser = bson_parser_new ();
      bson_parser_utf8 (parser, "databaseName", &database_name);
      bson_parser_utf8 (parser, "collectionName", &collection_name);
      bson_parser_array (parser, "documents", &documents);
      if (!bson_parser_parse (parser, &collection_data, error)) {
         goto loopexit;
      }

      wc = mongoc_write_concern_new ();
      mongoc_write_concern_set_w (wc, MONGOC_WRITE_CONCERN_W_MAJORITY);
      bulk_opts = bson_new ();
      mongoc_write_concern_append (wc, bulk_opts);

      /* Drop the collection. */
      /* Check if the server supports majority write concern on 'drop' and
       * 'create'. */
      if (semver_cmp_str (&test_runner->server_version, "3.4") >= 0) {
         drop_opts = bson_new ();
         mongoc_write_concern_append (wc, drop_opts);
         create_opts = bson_new ();
         mongoc_write_concern_append (wc, create_opts);
      }
      coll = mongoc_client_get_collection (
         test_runner->internal_client, database_name, collection_name);
      if (!mongoc_collection_drop_with_opts (coll, drop_opts, error)) {
         if (error->code != 26 &&
             (NULL == strstr (error->message, "ns not found"))) {
            /* This is not a "ns not found" error. Fail the test. */
            goto loopexit;
         }
         /* Clear an "ns not found" error. */
         memset (error, 0, sizeof (bson_error_t));
      }

      /* Insert documents if specified. */
      if (bson_count_keys (documents) > 0) {
         bson_iter_t documents_iter;

         bulk_insert =
            mongoc_collection_create_bulk_operation_with_opts (coll, bulk_opts);

         BSON_FOREACH (documents, documents_iter)
         {
            bson_t document;

            bson_iter_bson (&documents_iter, &document);
            mongoc_bulk_operation_insert (bulk_insert, &document);
         }

         if (!mongoc_bulk_operation_execute (bulk_insert, NULL, error)) {
            goto loopexit;
         }
      } else {
         mongoc_collection_t *new_coll = NULL;
         /* Test does not need data inserted, just create the collection. */
         db = mongoc_client_get_database (test_runner->internal_client,
                                          database_name);
         new_coll = mongoc_database_create_collection (
            db, collection_name, create_opts, error);
         if (!new_coll) {
            goto loopexit;
         }
         mongoc_collection_destroy (new_coll);
      }

      ret = true;

   loopexit:
      mongoc_bulk_operation_destroy (bulk_insert);
      bson_destroy (bulk_opts);
      bson_destroy (drop_opts);
      bson_destroy (create_opts);
      bson_destroy (documents);
      mongoc_write_concern_destroy (wc);
      mongoc_collection_destroy (coll);
      bson_free (database_name);
      bson_free (collection_name);
      bson_parser_destroy (parser);
      mongoc_database_destroy (db);
      if (!ret) {
         return false;
      }
   }
   return true;
}

static bool
test_create_entities (test_t *test, bson_error_t *error)
{
   test_file_t *test_file = NULL;
   bson_iter_t iter;

   test_file = test->test_file;

   if (!test_file->create_entities) {
      return true;
   }

   /* If a test runs a 'configureFailPoint' operation, reduce heartbeat on new
    * clients. */
   if (test_has_operation (test, "configureFailPoint")) {
      entity_map_set_reduced_heartbeat (test->entity_map, true);
   }

   BSON_FOREACH (test_file->create_entities, iter)
   {
      bson_t entity_bson;

      bson_iter_bson (&iter, &entity_bson);
      if (!entity_map_create (test->entity_map, &entity_bson, error)) {
         return false;
      }
   }
   return true;
}

static bool
test_run_operations (test_t *test, bson_error_t *error)
{
   bool ret = false;
   bson_iter_t iter;
   int i = 0;

   BSON_FOREACH (test->operations, iter)
   {
      bson_t op_bson;
      bson_iter_bson (&iter, &op_bson);

      if (!operation_run (test, &op_bson, error)) {
         test_diagnostics_error_info ("running operation: %s",
                                      tmp_json (&op_bson));
         goto done;
      }

      i++;
   }

   ret = true;
done:
   return ret;
}

static bool
test_check_event (test_t *test,
                  bson_t *expected,
                  event_t *actual,
                  bson_error_t *error)
{
   bool ret = false;
   bson_iter_t iter;
   bson_t expected_bson;
   bson_parser_t *bp = NULL;
   const char *expected_event_type;
   bson_t *expected_command = NULL;
   char *expected_command_name = NULL;
   char *expected_database_name = NULL;
   bson_t *expected_reply = NULL;
   bool *expected_has_service_id = NULL;
   bool *expected_has_server_connection_id = NULL;

   if (bson_count_keys (expected) != 1) {
      test_set_error (error,
                      "expected 1 key in expected event, but got: %s",
                      tmp_json (expected));
      goto done;
   }

   bson_iter_init (&iter, expected);
   bson_iter_next (&iter);
   expected_event_type = bson_iter_key (&iter);
   if (0 != strcmp (expected_event_type, actual->type)) {
      test_set_error (error,
                      "expected event type: %s, but got: %s",
                      expected_event_type,
                      actual->type);
      goto done;
   }

   if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) {
      test_set_error (error,
                      "unexpected non-document event assertion: %s",
                      tmp_json (expected));
      goto done;
   }
   bson_iter_bson (&iter, &expected_bson);

   bp = bson_parser_new ();
   bson_parser_doc_optional (bp, "command", &expected_command);
   bson_parser_utf8_optional (bp, "commandName", &expected_command_name);
   bson_parser_utf8_optional (bp, "databaseName", &expected_database_name);
   bson_parser_doc_optional (bp, "reply", &expected_reply);
   bson_parser_bool_optional (bp, "hasServiceId", &expected_has_service_id);
   bson_parser_bool_optional (
      bp, "hasServerConnectionId", &expected_has_server_connection_id);
   if (!bson_parser_parse (bp, &expected_bson, error)) {
      goto done;
   }

   if (expected_command) {
      bson_val_t *expected_val;
      bson_val_t *actual_val;

      if (!actual || !actual->command) {
         test_set_error (error, "Expected a value but got NULL");
         goto done;
      }

      expected_val = bson_val_from_bson (expected_command);
      actual_val = bson_val_from_bson (actual->command);

      if (!entity_map_match (
             test->entity_map, expected_val, actual_val, false, error)) {
         bson_val_destroy (expected_val);
         bson_val_destroy (actual_val);
         goto done;
      }
      bson_val_destroy (expected_val);
      bson_val_destroy (actual_val);
   }

   if (expected_command_name &&
       0 != strcmp (expected_command_name, actual->command_name)) {
      test_set_error (error,
                      "expected commandName: %s, but got: %s",
                      expected_command_name,
                      actual->command_name);
      goto done;
   }

   if (expected_database_name &&
       0 != strcmp (expected_database_name, actual->database_name)) {
      test_set_error (error,
                      "expected databaseName: %s, but got: %s",
                      expected_database_name,
                      actual->database_name);
      goto done;
   }

   if (expected_reply) {
      bson_val_t *expected_val = bson_val_from_bson (expected_reply);
      bson_val_t *actual_val = bson_val_from_bson (actual->reply);
      if (!entity_map_match (
             test->entity_map, expected_val, actual_val, false, error)) {
         bson_val_destroy (expected_val);
         bson_val_destroy (actual_val);
         goto done;
      }
      bson_val_destroy (expected_val);
      bson_val_destroy (actual_val);
   }

   if (expected_has_service_id) {
      char oid_str[25] = {0};
      bool has_service_id = false;

      bson_oid_to_string (&actual->service_id, oid_str);
      has_service_id =
         0 != bson_oid_compare (&actual->service_id, &kZeroServiceId);

      if (*expected_has_service_id && !has_service_id) {
         test_error ("expected serviceId, but got none");
      }

      if (!*expected_has_service_id && has_service_id) {
         test_error ("expected no serviceId, but got %s", oid_str);
      }
   }

   if (expected_has_server_connection_id) {
      const bool has_server_connection_id =
         actual->server_connection_id != MONGOC_NO_SERVER_CONNECTION_ID;

      if (*expected_has_server_connection_id && !has_server_connection_id) {
         test_error ("expected server connectionId, but got none");
      }

      if (!*expected_has_server_connection_id && has_server_connection_id) {
         test_error ("expected no server connectionId, but got %" PRId64,
                     actual->server_connection_id);
      }
   }

   ret = true;
done:
   bson_parser_destroy_with_parsed_fields (bp);
   return ret;
}

static bool
test_check_expected_events_for_client (test_t *test,
                                       bson_t *expected_events_for_client,
                                       bson_error_t *error)
{
   bool ret = false;
   bson_parser_t *bp = NULL;
   char *client_id = NULL;
   bson_t *expected_events = NULL;
   bool just_false = false;
   bool *ignore_extra_events = &just_false;
   entity_t *entity = NULL;
   bson_iter_t iter;
   event_t *eiter = NULL;
   uint32_t expected_num_events;
   uint32_t actual_num_events = 0;
   char *event_type = NULL;

   bp = bson_parser_new ();
   bson_parser_utf8 (bp, "client", &client_id);
   bson_parser_array (bp, "events", &expected_events);
   bson_parser_bool_optional (bp, "ignoreExtraEvents", &ignore_extra_events);
   bson_parser_utf8_optional (bp, "eventType", &event_type);
   if (!bson_parser_parse (bp, expected_events_for_client, error)) {
      goto done;
   }

   if (event_type) {
      if (0 == strcmp (event_type, "cmap")) {
         /* TODO: (CDRIVER-3525) Explicitly ignore cmap events until CMAP is
          * supported. */
         ret = true;
         goto done;
      } else if (0 != strcmp (event_type, "command")) {
         test_set_error (error, "unexpected event type: %s", event_type);
         goto done;
      }
   }

   entity = entity_map_get (test->entity_map, client_id, error);
   if (0 != strcmp (entity->type, "client")) {
      test_set_error (error,
                      "expected entity %s to be client, got: %s",
                      entity->id,
                      entity->type);
      goto done;
   }

   expected_num_events = bson_count_keys (expected_events);
   LL_COUNT (entity->events, eiter, actual_num_events);
   if (expected_num_events != actual_num_events) {
      bool too_many_events = actual_num_events > expected_num_events;
      if (ignore_extra_events && *ignore_extra_events) {
         // We can never have too many events
         too_many_events = false;
      }
      bool too_few_events = actual_num_events < expected_num_events;
      if (too_few_events || too_many_events) {
         test_set_error (error,
                         "expected: %" PRIu32 " events but got %" PRIu32,
                         expected_num_events,
                         actual_num_events);
         goto done;
      }
   }

   eiter = entity->events;
   BSON_FOREACH (expected_events, iter)
   {
      bson_t expected_event;

      bson_iter_bson (&iter, &expected_event);
      if (!eiter) {
         test_set_error (
            error, "could not find event: %s", tmp_json (&expected_event));
         goto done;
      }
      if (!test_check_event (test, &expected_event, eiter, error)) {
         test_diagnostics_error_info ("checking for expected event: %s",
                                      tmp_json (&expected_event));
         goto done;
      }
      eiter = eiter->next;
   }

   ret = true;
done:
   if (!ret) {
      if (entity && entity->events) {
         char *event_list_string = NULL;

         event_list_string = event_list_to_string (entity->events);
         test_diagnostics_error_info ("all captured events:\n%s",
                                      event_list_string);
         bson_free (event_list_string);
      }
   }
   bson_parser_destroy_with_parsed_fields (bp);
   return ret;
}

static bool
test_check_expected_events (test_t *test, bson_error_t *error)
{
   bool ret = false;
   bson_iter_t iter;

   if (!test->expect_events) {
      ret = true;
      goto done;
   }

   BSON_FOREACH (test->expect_events, iter)
   {
      bson_t expected_events_for_client;
      bson_iter_bson (&iter, &expected_events_for_client);
      if (!test_check_expected_events_for_client (
             test, &expected_events_for_client, error)) {
         test_diagnostics_error_info ("checking expectations: %s",
                                      tmp_json (&expected_events_for_client));
         goto done;
      }
   }

   ret = true;
done:
   return ret;
}

static bool
test_check_outcome_collection (test_t *test,
                               bson_t *collection_data,
                               bson_error_t *error)
{
   bool ret = false;
   bson_parser_t *bp = NULL;
   char *database_name = NULL;
   char *collection_name = NULL;
   bson_t *documents = NULL;
   mongoc_collection_t *coll = NULL;
   mongoc_cursor_t *cursor = NULL;
   bson_t *opts = NULL;
   mongoc_read_concern_t *rc = NULL;
   mongoc_read_prefs_t *rp = NULL;
   const bson_t *out;
   bson_t *actual_data = NULL;
   uint32_t i;
   bson_iter_t iter;
   bson_iter_t eiter;

   bp = bson_parser_new ();
   bson_parser_utf8 (bp, "databaseName", &database_name);
   bson_parser_utf8 (bp, "collectionName", &collection_name);
   bson_parser_array (bp, "documents", &documents);
   if (!bson_parser_parse (bp, collection_data, error)) {
      goto done;
   }

   coll = mongoc_client_get_collection (
      test->test_file->test_runner->internal_client,
      database_name,
      collection_name);
   opts = BCON_NEW ("sort", "{", "_id", BCON_INT32 (1), "}");
   rc = mongoc_read_concern_new ();
   mongoc_read_concern_set_level (rc, MONGOC_READ_CONCERN_LEVEL_LOCAL);
   rp = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);
   cursor = mongoc_collection_find_with_opts (
      coll, tmp_bson ("{}"), tmp_bson ("{'sort': {'_id': 1}}"), rp);
   /* Read the full cursor into a BSON array so error messages can include the
    * full list of documents. */
   actual_data = bson_new ();
   i = 0;
   while (mongoc_cursor_next (cursor, &out)) {
      char storage[16];
      const char *key;

      bson_uint32_to_string (i, &key, storage, sizeof (storage));
      BSON_APPEND_DOCUMENT (actual_data, key, out);
      i++;
   }

   if (mongoc_cursor_error (cursor, error)) {
      goto done;
   }

   if (bson_count_keys (actual_data) != bson_count_keys (documents)) {
      test_set_error (error,
                      "expected collection %s to contain: %s\nbut got: %s",
                      collection_name,
                      tmp_json (documents),
                      tmp_json (actual_data));
      goto done;
   }

   bson_iter_init (&eiter, documents);
   bson_iter_next (&eiter);

   BSON_FOREACH (actual_data, iter)
   {
      bson_t actual;
      bson_t expected;
      bson_t *actual_sorted = NULL;
      bson_t *expected_sorted = NULL;

      bson_iter_bson (&iter, &actual);
      actual_sorted = bson_copy_and_sort (&actual);

      bson_iter_bson (&eiter, &expected);
      expected_sorted = bson_copy_and_sort (&expected);

      if (!bson_equal (actual_sorted, expected_sorted)) {
         test_set_error (error,
                         "expected %s, but got %s",
                         tmp_json (expected_sorted),
                         tmp_json (actual_sorted));
         bson_destroy (actual_sorted);
         bson_destroy (expected_sorted);
         goto done;
      }

      bson_destroy (actual_sorted);
      bson_destroy (expected_sorted);

      bson_iter_next (&eiter);
   }

   ret = true;
done:
   bson_destroy (opts);
   mongoc_collection_destroy (coll);
   mongoc_cursor_destroy (cursor);
   mongoc_read_concern_destroy (rc);
   mongoc_read_prefs_destroy (rp);
   bson_destroy (actual_data);
   bson_parser_destroy_with_parsed_fields (bp);
   return ret;
}

static bool
test_check_outcome (test_t *test, bson_error_t *error)
{
   bool ret = false;
   bson_iter_t iter;

   if (!test->outcome) {
      ret = true;
      goto done;
   }

   BSON_FOREACH (test->outcome, iter)
   {
      bson_t collection_data;

      bson_iter_bson (&iter, &collection_data);
      if (!test_check_outcome_collection (test, &collection_data, error)) {
         goto done;
      }
   }

   ret = true;
done:
   return ret;
}

static bool
run_distinct_on_each_mongos (test_t *test,
                             char *db_name,
                             char *coll_name,
                             bson_error_t *error)
{
   bool ret = false;
   bson_t *cmd = NULL;
   int i;
   test_runner_t *runner = test->test_file->test_runner;

   cmd = BCON_NEW ("distinct", coll_name, "key", "x", "query", "{", "}");

   for (i = 0; i < runner->server_ids.len; i++) {
      uint32_t server_id;

      server_id = _mongoc_array_index (&runner->server_ids, uint32_t, i);
      if (!mongoc_client_command_simple_with_server_id (
             test->test_file->test_runner->internal_client,
             db_name,
             cmd,
             NULL /* read prefs */,
             server_id,
             NULL /* reply */,
             error)) {
         goto done;
      }
   }

   ret = true;
done:
   bson_destroy (cmd);
   return ret;
}

static bool
test_run_distinct_workaround (test_t *test, bson_error_t *error)
{
   bool ret = false;
   bson_iter_t iter;
   bson_parser_t *bp = NULL;
   mongoc_collection_t *coll = NULL;

   if (0 != strcmp (test->test_file->test_runner->topology_type, "sharded") &&
       0 != strcmp (test->test_file->test_runner->topology_type,
                    "sharded-replicaset")) {
      ret = true;
      goto done;
   }

   if (!test_has_operation (test, "distinct")) {
      ret = true;
      goto done;
   }

   /* Get the database/collection name from each collection entity. */
   BSON_FOREACH (test->test_file->create_entities, iter)
   {
      bson_t entity_bson;
      char *coll_name = NULL;
      char *db_id = NULL;
      char *db_name = NULL;
      mongoc_database_t *db = NULL;
      bson_iter_t entity_iter;

      if (!BSON_ITER_HOLDS_DOCUMENT (&iter)) {
         test_set_error (error,
                         "unexpected non-document createEntity: %s",
                         bson_iter_key (&iter));
         goto done;
      }

      bson_iter_recurse (&iter, &entity_iter);

      if (!bson_iter_find (&entity_iter, "collection")) {
         continue;
      }

      if (!BSON_ITER_HOLDS_DOCUMENT (&entity_iter)) {
         test_set_error (error,
                         "unexpected non-document in iter: %s",
                         bson_iter_key (&entity_iter));
         goto done;
      }

      bson_iter_bson (&entity_iter, &entity_bson);

      bp = bson_parser_new ();
      bson_parser_allow_extra (bp, true);
      bson_parser_utf8 (bp, "collectionName", &coll_name);
      bson_parser_utf8 (bp, "database", &db_id);
      if (!bson_parser_parse (bp, &entity_bson, error)) {
         goto done;
      }

      db = entity_map_get_database (test->entity_map, db_id, error);
      if (!db) {
         goto done;
      }

      db_name = (char *) mongoc_database_get_name (db);

      if (!run_distinct_on_each_mongos (test, db_name, coll_name, error)) {
         goto done;
      }

      bson_parser_destroy_with_parsed_fields (bp);
      bp = NULL;
   }

   ret = true;
done:
   mongoc_collection_destroy (coll);
   bson_parser_destroy_with_parsed_fields (bp);
   return ret;
}

/* This returns an error on failure instead of asserting where possible.
 * This allows the test runner to perform server clean up even on failure (e.g.
 * disable failpoints).
 */
bool
test_run (test_t *test, bson_error_t *error)
{
   bool ret = false;
   test_runner_t *test_runner = NULL;
   test_file_t *test_file = NULL;
   char *subtest_selector = NULL;
   bson_error_t nonfatal_error;

   test_file = test->test_file;
   test_runner = test_file->test_runner;

   if (is_test_skipped (test)) {
      MONGOC_DEBUG (
         "SKIPPING test '%s'. Reason: 'explicitly skipped in runner.c'",
         test->description);
      ret = true;
      goto done;
   }

   subtest_selector = _mongoc_getenv ("MONGOC_JSON_SUBTEST");
   if (subtest_selector &&
       NULL == strstr (test->description, subtest_selector)) {
      MONGOC_DEBUG (
         "SKIPPING test '%s'. Reason: 'skipped by MONGOC_JSON_SUBTEST'",
         test->description);
      ret = true;
      goto done;
   }

   if (test->skip_reason != NULL) {
      MONGOC_DEBUG ("SKIPPING test '%s'. Reason: '%s'",
                    test->description,
                    test->skip_reason);
      ret = true;
      goto done;
   }

   if (test->run_on_requirements) {
      const char *reason;
      if (!check_run_on_requirements (
             test_runner, test->run_on_requirements, &reason)) {
         MONGOC_DEBUG (
            "SKIPPING test '%s'. Reason: '%s'", test->description, reason);
         ret = true;
         goto done;
      }
   }

   if (!test_setup_initial_data (test, error)) {
      test_diagnostics_error_info ("%s", "setting up initial data");
      goto done;
   }

   if (!test_create_entities (test, error)) {
      test_diagnostics_error_info ("%s", "creating entities");
      goto done;
   }

   if (!test_run_distinct_workaround (test, error)) {
      test_diagnostics_error_info ("%s", "sending distinct to each mongos");
      goto done;
   }

   if (!test_run_operations (test, error)) {
      test_diagnostics_error_info ("%s", "running operations");
      goto done;
   }

   entity_map_disable_event_listeners (test->entity_map);

   if (!test_check_expected_events (test, error)) {
      test_diagnostics_error_info ("%s", "checking expectations");
      goto done;
   }

   if (!test_check_outcome (test, error)) {
      test_diagnostics_error_info ("%s", "checking outcome");
      goto done;
   }

   ret = true;
done:
   /* always clean up failpoints, even on test failure */
   if (!cleanup_failpoints (test, &nonfatal_error)) {
      MONGOC_DEBUG ("error cleaning up failpoints: %s", nonfatal_error.message);
   }
   /* always terminate transactions, even on test failure. */
   if (!test_runner_terminate_open_transactions (test_runner,
                                                 &nonfatal_error)) {
      MONGOC_DEBUG ("error terminating transactions: %s",
                    nonfatal_error.message);
   }
   bson_free (subtest_selector);
   return ret;
}

void
run_one_test_file (bson_t *bson)
{
   test_runner_t *test_runner = NULL;
   test_file_t *test_file = NULL;
   bson_iter_t test_iter;

   test_diagnostics_init ();

   test_runner = test_runner_new ();
   test_file = test_file_new (test_runner, bson);

   test_diagnostics_test_info ("test file: %s", test_file->description);

   if (is_test_file_skipped (test_file)) {
      MONGOC_DEBUG (
         "SKIPPING test file '%s'. Reason: 'explicitly skipped in runner.c'",
         test_file->description);
      goto done;
   }

   check_schema_version (test_file);
   if (test_file->run_on_requirements) {
      const char *reason;
      if (!check_run_on_requirements (
             test_runner, test_file->run_on_requirements, &reason)) {
         MONGOC_DEBUG ("SKIPPING test file (%s). Reason:\n%s",
                       test_file->description,
                       reason);
         goto done;
      }
   }

   BSON_FOREACH (test_file->tests, test_iter)
   {
      test_t *test = NULL;
      bson_t test_bson;
      bool test_ok;
      bson_error_t error = {0};

      test_diagnostics_reset ();
      test_diagnostics_test_info ("test file: %s", test_file->description);

      bson_iter_bson (&test_iter, &test_bson);
      test = test_new (test_file, &test_bson);
      test_diagnostics_test_info ("running test: %s", test->description);
      test_ok = test_run (test, &error);
      if (!test_ok) {
         test_diagnostics_abort (&error);
      }
      test_destroy (test);
   }

done:
   test_file_destroy (test_file);
   test_runner_destroy (test_runner);
   test_diagnostics_cleanup ();
}

void
run_unified_tests (TestSuite *suite, const char *base, const char *subdir)
{
   install_json_test_suite_with_check (suite,
                                       base,
                                       subdir,
                                       &run_one_test_file,
                                       TestSuite_CheckLive,
                                       test_framework_skip_if_no_crypto);
}

void
test_install_unified (TestSuite *suite)
{
   run_unified_tests (suite, JSON_DIR, "unified");

   run_unified_tests (suite, JSON_DIR, "crud/unified");

   run_unified_tests (suite, JSON_DIR, "transactions/unified");

   run_unified_tests (suite, JSON_DIR, "collection-management");

   run_unified_tests (suite, JSON_DIR, "sessions/unified");

   run_unified_tests (suite, JSON_DIR, "change_streams/unified");

   run_unified_tests (suite, JSON_DIR, "load_balancers");

   run_unified_tests (suite, JSON_DIR, "client_side_encryption/unified");

   run_unified_tests (suite, JSON_DIR, "retryable_reads/unified");

   run_unified_tests (suite, JSON_DIR, "retryable_writes/unified");
}


text:
angular.module('umbraco.resources')
    .factory('nuPickers.Shared.SaveFormat.SaveFormatResource',
        function () {

            return {

                /// returns a string representation of the picked options as per the configured SaveFormat
                /// pickedOptions expected to be an array of { 'key': '', 'label': '' } objects
                createSaveValue: function (config, pickedOptions) {

                    if (pickedOptions == null || pickedOptions.length == 0 || pickedOptions[0] == null) {
                        return null;
                    }

                    switch (config.saveFormat) {

                        case 'csv': // 'key, key...'
                        case 'relationsOnly': // special case - used server-side by relationsOnly mapping event (where this value is then wiped)
                            return pickedOptions.map(function (option) { return option.key; }).join();
                            break;

                        case 'json': // some pickers add extra data to the options, so only return a key/label collection
                            return JSON.stringify(
                                            pickedOptions.map(function (option) {
                                                return { 'key': option.key, 'label': option.label }
                                            }));
                            break;

                        case 'xml':
                            var xml = '<Picker>';

                            for (var i = 0; i < pickedOptions.length; i++) {
                                xml += '<Picked Key="' + pickedOptions[i].key + '">'
                                xml += '<![CDATA[' + pickedOptions[i].label + ']]>';
                                xml += '</Picked>';
                            }

                            xml += '</Picker>';

                            return xml;
                            break;

                        default:
                            return null;
                            break;
                    }
                },

                /// returns an array of strings
                /// saveValue is expected to be a string or an array of { 'key': '', 'label': '' } objects
                getSavedKeys: function (saveValue) {

                    // json save format
                    if (saveValue instanceof Array)
                    {
                        return saveValue.map(function (option) { return option.key }).join().split(',');
                    }

                    // parse string for nested json save format (fix to support the Doc Type Grid Editor package)
                    try {
                        var jsonSaveValue = JSON.parse(saveValue);
                        return jsonSaveValue.map(function (option) { return option.key }).join().split(',');
                    }
                    catch (error) { } // suppress

                    // xml save format
                    try {
                        var xml = $.parseXML(saveValue);
                        var keys = new Array();
                        $(xml).find('Picked').each(function () {
                            keys.push($(this).attr('Key'));
                        });

                        return keys;
                    }
                    catch (error) { } // suppress

                    // csv save format
                    return saveValue.split(',');
                },

                /// returns an array of { 'key': '', 'label': '' } objects
                /// saveValue expected to be either json or xml
                getSavedItems: function (saveValue) {

                    // json save format
                    if (saveValue instanceof Array)
                    {
                        return saveValue;
                    }

                    // parse string for nested json save format (fix to support the Doc Type Grid Editor package)
                    try {
                        return JSON.parse(saveValue);
                    }
                    catch (error) { } // suppress

                    // xml save format
                    try {
                        var xml = $.parseXML(saveValue);
                        var items = new Array();
                        $(xml).find('Picked').each(function () {
                            items.push({
                                'key': $(this).attr('Key'),
                                'label': $(this).text()
                            });
                        });

                        return items;
                    }
                    catch (error) { } // suppress

                    // csv save format - doesn't support storing of label data
                    return null;
                }
            };
        }
);


text:
//==============================================================================
//
// PLEASE DO NOT EDIT THIS FILE; IT WAS AUTOMATICALLY GENERATED BY GENCLASS.
//
//==============================================================================

#include <cimple/Meta_Class.h>
#include <cimple/Meta_Property.h>
#include <cimple/Meta_Reference.h>
#include "CIM_PhysicalPackage.h"

CIMPLE_NAMESPACE_BEGIN

using namespace cimple;

extern const Meta_Repository __meta_repository_75E2CB8B53E2155E90DBB99ABED114CA;

extern const Meta_Property _CIM_ManagedElement_Caption;

extern const Meta_Property _CIM_PhysicalElement_Description;

extern const Meta_Property _CIM_PhysicalElement_ElementName;

extern const Meta_Property _CIM_ManagedSystemElement_InstallDate;

extern const Meta_Property _CIM_ManagedSystemElement_Name;

extern const Meta_Property _CIM_ManagedSystemElement_OperationalStatus;

extern const Meta_Property _CIM_ManagedSystemElement_StatusDescriptions;

extern const Meta_Property _CIM_ManagedSystemElement_Status;

extern const Meta_Property _CIM_PhysicalElement_Tag;

extern const Meta_Property _CIM_PhysicalElement_CreationClassName;

extern const Meta_Property _CIM_PhysicalElement_Manufacturer;

extern const Meta_Property _CIM_PhysicalElement_Model;

extern const Meta_Property _CIM_PhysicalElement_SKU;

extern const Meta_Property _CIM_PhysicalElement_SerialNumber;

extern const Meta_Property _CIM_PhysicalElement_Version;

extern const Meta_Property _CIM_PhysicalElement_PartNumber;

extern const Meta_Property _CIM_PhysicalElement_OtherIdentifyingInfo;

extern const Meta_Property _CIM_PhysicalElement_PoweredOn;

extern const Meta_Property _CIM_PhysicalElement_ManufactureDate;

extern const Meta_Property _CIM_PhysicalElement_VendorEquipmentType;

extern const Meta_Property _CIM_PhysicalElement_UserTracking;

extern const Meta_Property _CIM_PhysicalElement_CanBeFRUed;

extern const Meta_Property _CIM_PhysicalPackage_RemovalConditions;

const Meta_Property _CIM_PhysicalPackage_RemovalConditions =
{
    CIMPLE_FLAG_PROPERTY,
    "RemovalConditions",
    UINT16,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,RemovalConditions)
};

extern const Meta_Property _CIM_PhysicalPackage_Removable;

const Meta_Property _CIM_PhysicalPackage_Removable =
{
    CIMPLE_FLAG_PROPERTY,
    "Removable",
    BOOLEAN,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Removable)
};

extern const Meta_Property _CIM_PhysicalPackage_Replaceable;

const Meta_Property _CIM_PhysicalPackage_Replaceable =
{
    CIMPLE_FLAG_PROPERTY,
    "Replaceable",
    BOOLEAN,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Replaceable)
};

extern const Meta_Property _CIM_PhysicalPackage_HotSwappable;

const Meta_Property _CIM_PhysicalPackage_HotSwappable =
{
    CIMPLE_FLAG_PROPERTY,
    "HotSwappable",
    BOOLEAN,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,HotSwappable)
};

extern const Meta_Property _CIM_PhysicalPackage_Height;

const Meta_Property _CIM_PhysicalPackage_Height =
{
    CIMPLE_FLAG_PROPERTY,
    "Height",
    REAL32,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Height)
};

extern const Meta_Property _CIM_PhysicalPackage_Depth;

const Meta_Property _CIM_PhysicalPackage_Depth =
{
    CIMPLE_FLAG_PROPERTY,
    "Depth",
    REAL32,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Depth)
};

extern const Meta_Property _CIM_PhysicalPackage_Width;

const Meta_Property _CIM_PhysicalPackage_Width =
{
    CIMPLE_FLAG_PROPERTY,
    "Width",
    REAL32,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Width)
};

extern const Meta_Property _CIM_PhysicalPackage_Weight;

const Meta_Property _CIM_PhysicalPackage_Weight =
{
    CIMPLE_FLAG_PROPERTY,
    "Weight",
    REAL32,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage,Weight)
};

static const Meta_Reference _CIM_PhysicalPackage_IsCompatible_ElementToCheck =
{
    CIMPLE_FLAG_REFERENCE|CIMPLE_FLAG_IN,
    "ElementToCheck",
    &CIM_PhysicalElement::static_meta_class,
    CIMPLE_OFF(CIM_PhysicalPackage_IsCompatible_method,ElementToCheck)
};

static const Meta_Property _CIM_PhysicalPackage_IsCompatible_return_value =
{
    CIMPLE_FLAG_PROPERTY|CIMPLE_FLAG_OUT,
    "return_value",
    UINT32,
    0,
    CIMPLE_OFF(CIM_PhysicalPackage_IsCompatible_method,return_value)
};

static Meta_Feature* _CIM_PhysicalPackage_IsCompatible_meta_features[] =
{
    (Meta_Feature*)&_CIM_PhysicalPackage_IsCompatible_ElementToCheck,
    (Meta_Feature*)&_CIM_PhysicalPackage_IsCompatible_return_value
};

const Meta_Method CIM_PhysicalPackage_IsCompatible_method::static_meta_class =
{
    CIMPLE_FLAG_METHOD,
    "IsCompatible",
    _CIM_PhysicalPackage_IsCompatible_meta_features,
    CIMPLE_ARRAY_SIZE(_CIM_PhysicalPackage_IsCompatible_meta_features),
    sizeof(CIM_PhysicalPackage_IsCompatible_method),
    UINT32,
};

static Meta_Feature* _CIM_PhysicalPackage_meta_features[] =
{
    (Meta_Feature*)&_CIM_ManagedElement_Caption,
    (Meta_Feature*)&_CIM_PhysicalElement_Description,
    (Meta_Feature*)&_CIM_PhysicalElement_ElementName,
    (Meta_Feature*)&_CIM_ManagedSystemElement_InstallDate,
    (Meta_Feature*)&_CIM_ManagedSystemElement_Name,
    (Meta_Feature*)&_CIM_ManagedSystemElement_OperationalStatus,
    (Meta_Feature*)&_CIM_ManagedSystemElement_StatusDescriptions,
    (Meta_Feature*)&_CIM_ManagedSystemElement_Status,
    (Meta_Feature*)&_CIM_PhysicalElement_Tag,
    (Meta_Feature*)&_CIM_PhysicalElement_CreationClassName,
    (Meta_Feature*)&_CIM_PhysicalElement_Manufacturer,
    (Meta_Feature*)&_CIM_PhysicalElement_Model,
    (Meta_Feature*)&_CIM_PhysicalElement_SKU,
    (Meta_Feature*)&_CIM_PhysicalElement_SerialNumber,
    (Meta_Feature*)&_CIM_PhysicalElement_Version,
    (Meta_Feature*)&_CIM_PhysicalElement_PartNumber,
    (Meta_Feature*)&_CIM_PhysicalElement_OtherIdentifyingInfo,
    (Meta_Feature*)&_CIM_PhysicalElement_PoweredOn,
    (Meta_Feature*)&_CIM_PhysicalElement_ManufactureDate,
    (Meta_Feature*)&_CIM_PhysicalElement_VendorEquipmentType,
    (Meta_Feature*)&_CIM_PhysicalElement_UserTracking,
    (Meta_Feature*)&_CIM_PhysicalElement_CanBeFRUed,
    (Meta_Feature*)&_CIM_PhysicalPackage_RemovalConditions,
    (Meta_Feature*)&_CIM_PhysicalPackage_Removable,
    (Meta_Feature*)&_CIM_PhysicalPackage_Replaceable,
    (Meta_Feature*)&_CIM_PhysicalPackage_HotSwappable,
    (Meta_Feature*)&_CIM_PhysicalPackage_Height,
    (Meta_Feature*)&_CIM_PhysicalPackage_Depth,
    (Meta_Feature*)&_CIM_PhysicalPackage_Width,
    (Meta_Feature*)&_CIM_PhysicalPackage_Weight,
    (Meta_Feature*)&CIM_PhysicalPackage_IsCompatible_method::static_meta_class,
};

static const char* _super_classes[] =
{
    "CIM_PhysicalElement",
    "CIM_ManagedSystemElement",
    "CIM_ManagedElement",
};

static const Meta_Feature_Local _locals[] =
{
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {0},
    {1},
    {1},
    {1},
    {1},
    {1},
    {1},
    {1},
    {1},
    {1},
};

const Meta_Class CIM_PhysicalPackage::static_meta_class =
{
    CIMPLE_FLAG_CLASS,
    "CIM_PhysicalPackage",
    _CIM_PhysicalPackage_meta_features,
    CIMPLE_ARRAY_SIZE(_CIM_PhysicalPackage_meta_features),
    sizeof(CIM_PhysicalPackage),
    _locals,
    &CIM_PhysicalElement::static_meta_class,
    _super_classes,
    CIMPLE_ARRAY_SIZE(_super_classes),
    2, /* num_keys */
    0xFDD6B396,/* crc */
    &__meta_repository_75E2CB8B53E2155E90DBB99ABED114CA,
};

CIMPLE_NAMESPACE_END

CIMPLE_ID("$Header: /home/cvs/cimple/src/pegasus/benchmark/Benchmark3/CIM_PhysicalPackage.cpp,v 1.2 2007/03/07 20:23:55 mbrasher-public Exp $");


text:
/* @flow */
import type {L10nsStrings} from '../formatters/buildFormatter'

// Welsh
const strings: L10nsStrings = {
  prefixAgo: null,
  prefixFromNow: null,
  suffixAgo: 'yn ôl',
  suffixFromNow: 'o hyn',
  seconds: 'llai na munud',
  minute: 'am funud',
  minutes: '%d munud',
  hour: 'tua awr',
  hours: 'am %d awr',
  day: 'y dydd',
  days: '%d diwrnod',
  month: 'tua mis',
  months: '%d mis',
  year: 'am y flwyddyn',
  years: '%d blynedd',
  wordSeparator: ' '
}

export default strings


text:
package com.treode.buffer

import java.io.DataInput

trait Input {

  def readBytes (data: Array [Byte], offset: Int, length: Int)
  def readByte(): Byte
  def readShort(): Short
  def readInt(): Int
  def readVarUInt(): Int
  def readVarInt(): Int
  def readLong(): Long
  def readVarULong(): Long
  def readVarLong(): Long
  def readFloat(): Float
  def readDouble(): Double
  def readString(): String
}

object Input {

  def asDataInput (in: Input): DataInput =
    new DataInputWrapper (in)
}


text:
local helpers = require "spec.helpers"
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local to_hex = require "resty.string".to_hex

local fmt = string.format

local function gen_trace_id()
  return to_hex(utils.get_rand_bytes(16))
end

local function gen_span_id()
  return to_hex(utils.get_rand_bytes(8))
end

for _, strategy in helpers.each_strategy() do
describe("propagation tests #" .. strategy, function()
  local service
  local proxy_client

  lazy_setup(function()
    local bp = helpers.get_db_utils(strategy, { "services", "routes", "plugins" })

    -- enable opentelemetry plugin globally pointing to mock server
    bp.plugins:insert({
      name = "opentelemetry",
      config = {
        -- fake endpoint, request to backend will sliently fail
        endpoint = "http://localhost:8080/v1/traces",
      }
    })

    service = bp.services:insert()

    -- kong (http) mock upstream
    bp.routes:insert({
      service = service,
      hosts = { "http-route" },
    })

    helpers.start_kong({
      database = strategy,
      nginx_conf = "spec/fixtures/custom_nginx.template",
    })

    proxy_client = helpers.proxy_client()
  end)

  teardown(function()
    helpers.stop_kong()
  end)

  it("default propagation headers (w3c)", function()
    local r = proxy_client:get("/", {
      headers = {
        host = "http-route",
      },
    })
    local body = assert.response(r).has.status(200)
    local json = cjson.decode(body)

    assert.matches("00%-%x+-%x+-01", json.headers.traceparent)
  end)

  it("propagates tracing headers (b3 request)", function()
    local trace_id = gen_trace_id()
    local r = proxy_client:get("/", {
      headers = {
        ["x-b3-sampled"] = "1",
        ["x-b3-traceid"] = trace_id,
        host  = "http-route",
      },
    })
    local body = assert.response(r).has.status(200)
    local json = cjson.decode(body)
    assert.equals(trace_id, json.headers["x-b3-traceid"])
  end)

  describe("propagates tracing headers (b3-single request)", function()
    it("with parent_id", function()
      local trace_id = gen_trace_id()
      local span_id = gen_span_id()
      local parent_id = gen_span_id()

      local r = proxy_client:get("/", {
        headers = {
          b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "1", parent_id),
          host = "http-route",
        },
      })
      local body = assert.response(r).has.status(200)
      local json = cjson.decode(body)
      assert.matches(trace_id .. "%-%x+%-1%-%x+", json.headers.b3)
    end)

    it("without parent_id", function()
      local trace_id = gen_trace_id()
      local span_id = gen_span_id()

      local r = proxy_client:get("/", {
        headers = {
          b3 = fmt("%s-%s-1", trace_id, span_id),
          host = "http-route",
        },
      })
      local body = assert.response(r).has.status(200)
      local json = cjson.decode(body)
      assert.matches(trace_id .. "%-%x+%-1", json.headers.b3)
    end)
  end)

  it("propagates w3c tracing headers", function()
    local trace_id = gen_trace_id() -- w3c only admits 16-byte trace_ids
    local parent_id = gen_span_id()

    local r = proxy_client:get("/", {
      headers = {
        traceparent = fmt("00-%s-%s-01", trace_id, parent_id),
        host = "http-route"
      },
    })
    local body = assert.response(r).has.status(200)
    local json = cjson.decode(body)
    assert.matches("00%-" .. trace_id .. "%-%x+-01", json.headers.traceparent)
  end)

  it("propagates jaeger tracing headers", function()
    local trace_id = gen_trace_id()
    local span_id = gen_span_id()
    local parent_id = gen_span_id()

    local r = proxy_client:get("/", {
      headers = {
        ["uber-trace-id"] = fmt("%s:%s:%s:%s", trace_id, span_id, parent_id, "1"),
        host = "http-route"
      },
    })
    local body = assert.response(r).has.status(200)
    local json = cjson.decode(body)
    -- Trace ID is left padded with 0 for assert
    assert.matches( ('0'):rep(32-#trace_id) .. trace_id .. ":%x+:" .. span_id .. ":01", json.headers["uber-trace-id"])
  end)

  it("propagates ot headers", function()
    local trace_id = gen_trace_id()
    local span_id = gen_span_id()
    local r = proxy_client:get("/", {
      headers = {
        ["ot-tracer-traceid"] = trace_id,
        ["ot-tracer-spanid"] = span_id,
        ["ot-tracer-sampled"] = "1",
        host = "http-route",
      },
    })
    local body = assert.response(r).has.status(200)
    local json = cjson.decode(body)

    assert.equals(trace_id, json.headers["ot-tracer-traceid"])
  end)
end)
end